go - Using protobuf with golang and handling []byte HTTP response body -
i using golang protobuf package , try write tests ensure api works properly.
i construct object on server-side generated .pb.go
file.
and return with
data, err := proto.marshal(p) fmt.fprint(w, data)
and in test 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 http request correct , displays []byte
correctly, if ioutil.readall
interprets http response string , converts []byte
.
for example response
[12 3 2 14 41]
then ioutil.readall
interprets string , not []byte
.
the problem was: tried write binary data output stream fmt.fprint
missing important fact, fmt
package converts (everything?) input "read-able" format (ie strings). correct way of writting data output of http response using responsewriter directly this:
k, err := w.write(data)
Comments
Post a Comment