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

报告相同问题?

悬赏问题

  • ¥20 vue+UEditor附件上传问题
  • ¥15 想做个WPS的自动化代码,不知道能做的起不。
  • ¥15 uniApp,生成安卓安卓包后,黑暗主题中间内容不生效,底部导航正常
  • ¥15 斯坦福自动漂移非线性模型反解
  • ¥15 学习Python如何找兼职
  • ¥15 python结合Matlab仿真忆阻器
  • ¥35 有人会注册whatsaop协议号吗?
  • ¥15 lead dbs 无法导入影像数据
  • ¥15 多目标MPA算法优化编程实现
  • ¥15 反激PWM控制芯片调研