英文:
How does one send a [][]byte in Golang to the browser to be decoded as an image
问题
在我的后端Golang Web服务器中,我使用os.ReadDir
读取并处理了一个图像目录,这些图像被存储为[][]byte
。我希望能够通过GET请求将这些图像发送到浏览器中,并使用JavaScript显示。
我在如何开始发送数据的过程中遇到了困难。我目前正在使用的资源是典型的net/http包和Gorilla Mux/Websockets。
以下是一些示例代码,展示了我当前如何进行GET请求并返回一些JSON。我应该如何发送一个[][]byte
数组,而不是渲染模板或JSON呢?
import (
"html/template"
"log"
"net/http"
"encoding/json"
"github.com/gorilla/mux"
)
func ViewSample(rw http.ResponseWriter, req *http.Request) {
type Sample struct {
Id int `json:"id"`
Name string `json:"name"`
User string `json:"user"`
}
params := mux.Vars(req)
sampleId := params["id"]
sample := Sample{
Id: 3,
Name: "test",
User: "testuser",
}
json.NewEncoder(rw).Encode(sample)
}
英文:
In my back-end golang web server I have converted and processed a directory of images that i have read in using os.ReadDir
These images are stored as a [][]byte
. I want to be able to send these images through a GET request to be displayed in the browser using Javascript.
I am having trouble figuring out how to begin the process to send the data from the Golang web server. The resources I am currently using are the typical net/http package, and Gorilla Mux/Websockets.
Here is some sample code that shows how I am currently doing a get request which return some json. How can I similarly send a [][]byte array instead of rendering a template or JSON?
import (
"html/template"
"log"
"net/http"
"encoding/json"
"github.com/gorilla/mux"
)
func ViewSample(rw http.ResponseWriter, req *http.Request) {
type Sample struct {
Id int `json:"id"`
Name string `json:"name"`
User string `json:"user
}
params := mux.Vars(req)
sampleId := params["id"]
sample := Sample{
Id: 3,
Name: "test",
User: "testuser"
}
json.NewEncoder(rw).Encode(sample)
}
答案1
得分: 3
如果您的图像存储在[]byte
中,您可以直接将其写入http.ResponseWriter
。
func GetImage(w http.ResponseWriter, r *http.Request) {
image, err := getImage() // getImage示例返回([]byte, error)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(image)
}
没有一种原生被客户端理解的方式可以在单个响应中发送多个图像。您可以使用一种方法,在第一次调用时返回一个包含单独获取每个图像链接的JSON文档。
英文:
If your image is stored in a []byte
, you can write that directly to the http.ResponseWriter
func GetImage(w http.ResponseWriter, r *http.Request) {
image, err := getImage() // getImage example returns ([]byte, error)
if err != {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(image)
}
There's no way to send multiple images in a single response which is natively understood by clients. One method you could use is to return a json document on the first call, which contains a list of links to fetch each image individually.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论