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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)