http - 在 Go 中从 HTTP 请求的正文中读取图像

标签 http go

我正在玩 Go(有史以来第一次),我想构建一个工具来从 Internet 检索图像并剪切它们(甚至调整大小),但我停留在第一步。

package main

import (
  "fmt"
  "http"
)

var client = http.Client{}

func cutterHandler(res http.ResponseWriter, req *http.Request) {
  reqImg, err := client.Get("http://www.google.com/intl/en_com/images/srpr/logo3w.png")
  if err != nil {
    fmt.Fprintf(res, "Error %d", err)
    return
  }
  buffer := make([]byte, reqImg.ContentLength)
  reqImg.Body.Read(buffer)
  res.Header().Set("Content-Length", fmt.Sprint(reqImg.ContentLength)) /* value: 7007 */
  res.Header().Set("Content-Type", reqImg.Header.Get("Content-Type")) /* value: image/png */
  res.Write(buffer)
}

func main() {
  http.HandleFunc("/cut", cutterHandler)
  http.ListenAndServe(":8080", nil) /* TODO Configurable */
}

我可以请求图像(让我们使用 Google Logo )并获取其种类和大小。

事实上,我只是重写图像(将其视为玩具“代理”),设置 Content-Length 和 Content-Type 并写回字节 slice ,但我在某处弄错了。查看在 Chromium 12.0.742.112 (90304) 上渲染的最终图像的外观:

Grotesque result

我还检查了下载的文件,它是一个 7007 字节的 PNG 图像。如果我们查看请求,它应该可以正常工作:

GET /cut HTTP/1.1
User-Agent: curl/7.22.0 (i486-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.0e zlib/1.2.3.4 libidn/1.23 libssh2/1.2.8 librtmp/2.3
Host: 127.0.0.1:8080
Accept: /

HTTP/1.1 200 OK
Content-Length: 7007
Content-Type: image/png
Date: Tue, 27 Dec 2011 19:51:53 GMT

[PNG data]

你认为我做错了什么?

免责声明:我在挠自己的痒,所以可能我使用了错误的工具:)无论如何,我可以在 Ruby 上实现它,但在我想尝试一下 Go 之前。

更新:仍在挠痒痒,但...我认为这将是一个很好的副项目,所以我打开它 https://github.com/imdario/go-lazor如果它没有用,至少有人可以从用于开发它的引用中找到用处。他们是给我的。

最佳答案

我认为您在服务部分方面做得太快了。

关注第一步,下载图片

这里有一个小程序可以将该图像下载到内存中。
它适用于我的 2011-12-22 每周版本,对于 r60.3,您只需要修复导入。

package main

import (
    "log"
    "io/ioutil"
    "net/http"
)

const url = "http://www.google.com/intl/en_com/images/srpr/logo3w.png"

func main() {
    // Just a simple GET request to the image URL
    // We get back a *Response, and an error
    res, err := http.Get(url)

    if err != nil {
        log.Fatalf("http.Get -> %v", err)
    }

    // We read all the bytes of the image
    // Types: data []byte
    data, err = ioutil.ReadAll(res.Body)

    if err != nil {
        log.Fatalf("ioutil.ReadAll -> %v", err)
    }

    // You have to manually close the body, check docs
    // This is required if you want to use things like
    // Keep-Alive and other HTTP sorcery.
    res.Body.Close()

    // You can now save it to disk or whatever...
    ioutil.WriteFile("google_logo.png", data, 0666)

    log.Println("I saved your image buddy!")
}

瞧!

这会将图像获取到 data 中的内存中。
一旦你有了它,你就可以对其进行解码、裁剪并返回给浏览器。

希望这对您有所帮助。

关于http - 在 Go 中从 HTTP 请求的正文中读取图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8648682/

相关文章:

javascript - ExtJS 4 - 访问 REST 代理和/或存储中的自定义响应 header ?

http - 我们什么时候需要在 nginx 配置文件中使用 http block ?

cordova - 从 XHR 请求/响应中读取/写入 cookie (PhoneGap/Cordova)

PHP 或 Apache 删除文件

go - 无法访问结构的字段

csv - Golang : While processing CSV, 重新格式化单行?

c++ - vim折叠cpp和golang代码

Go 项目和依赖项

go - Golang 中的通知中心

http - text/html 的默认浏览器缓存有效期