duanganleng0577 2015-06-14 15:28
浏览 522
已采纳

将protobuf与golang结合使用并处理[] byte HTTP响应正文

I am using the Golang protobuf package and try to write some tests to ensure my API works properly.

I construct an Object on the server-side with a generated .pb.go file.

And return it with

data, err := proto.Marshal(p)
fmt.Fprint(w, data)

And in my test I do

func TestGetProduct(t *testing.T) {
    log.Println("Starting server")
    go startAPITestServer()
    time.Sleep(0 * time.Second)
    log.Println("Server started")
    //rq, err := http.NewRequest("GET", "localhost:8181/product/1", nil)
    client := &http.Client{}
    log.Println("Starting Request")
    resp, err := client.Get("http://localhost:8181/product/1")
    log.Println("Finished Request")
    if err != nil {
        t.Log(err)
    }
    defer resp.Body.Close()
    log.Println("Reading Request")
    data, err := ioutil.ReadAll(resp.Body)
    log.Println("Reading finished")
    if err != nil {
        t.Log(err)
    }
    log.Println("HTTP Resp", data)
    p := &Product{}
    proto.UnmarshalText(string(data), p)
    proto.Unmarshal(data, p2)
}

The Problem is that the HTTP Request is correct and displays the []byte correctly, but if I do ioutil.ReadAll it interprets the HTTP Response as a string and converts it to a []byte.

For example the response is

[12 3 2 14 41]

Then ioutil.ReadAll interprets this as a string and not as a []byte.

  • 写回答

1条回答 默认 最新

  • dtkwt62022 2015-06-27 11:15
    关注

    The problem was: I tried to write binary data to the output stream with fmt.Fprint missing the important fact, that the fmt package converts (everything?) input to a "read-able" format (ie strings). The correct way of writting data into the output of your HTTP Response is using the responsewriter directly like this:

    k, err := w.Write(data)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗