doujin8476 2015-02-25 00:18
浏览 580
已采纳

如何将Golang中的[] []字节发送到浏览器以将其解码为图像

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条回答 默认 最新

  • drnycqxwz63508434 2015-02-25 19:28
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看