mirror of
https://github.com/google/flatbuffers.git
synced 2026-07-01 20:53:57 +00:00
Use FinshedBytes() in go-echo example instead of manually encoding offset (#7660)
Co-authored-by: Derek Bailey <derekbailey@google.com>
This commit is contained in:
@@ -16,13 +16,7 @@ func RequestBody() *bytes.Reader {
|
|||||||
b := flatbuffers.NewBuilder(0)
|
b := flatbuffers.NewBuilder(0)
|
||||||
r := net.RequestT{Player: &hero.WarriorT{Name: "Krull", Hp: 100}}
|
r := net.RequestT{Player: &hero.WarriorT{Name: "Krull", Hp: 100}}
|
||||||
b.Finish(r.Pack(b))
|
b.Finish(r.Pack(b))
|
||||||
|
return bytes.NewReader(b.FinishedBytes())
|
||||||
// Encode builder head in last 4 bytes of request body
|
|
||||||
buf := make([]byte, 4)
|
|
||||||
flatbuffers.WriteUOffsetT(buf, b.Head())
|
|
||||||
buf = append(b.Bytes, buf...)
|
|
||||||
|
|
||||||
return bytes.NewReader(buf)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func ReadResponse(r *http.Response) {
|
func ReadResponse(r *http.Response) {
|
||||||
@@ -32,18 +26,13 @@ func ReadResponse(r *http.Response) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Last 4 bytes is offset.
|
res := net.GetRootAsResponse(body, 0)
|
||||||
off := flatbuffers.GetUOffsetT(body[len(body)-4:])
|
|
||||||
buf := body[:len(body) - 4]
|
|
||||||
|
|
||||||
res := net.GetRootAsResponse(buf, off)
|
|
||||||
player := res.Player(nil)
|
player := res.Player(nil)
|
||||||
|
|
||||||
fmt.Printf("Got response (name: %v, hp: %v)\n", string(player.Name()), player.Hp())
|
fmt.Printf("Got response (name: %v, hp: %v)\n", string(player.Name()), player.Hp())
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
|
||||||
body := RequestBody()
|
body := RequestBody()
|
||||||
req, err := http.NewRequest("POST", "http://localhost:8080/echo", body)
|
req, err := http.NewRequest("POST", "http://localhost:8080/echo", body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -5,8 +5,6 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
flatbuffers "github.com/google/flatbuffers/go"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func echo(w http.ResponseWriter, r *http.Request) {
|
func echo(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -16,11 +14,7 @@ func echo(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Last 4 bytes is offset. See client.go.
|
req := net.GetRootAsRequest(body, 0)
|
||||||
off := flatbuffers.GetUOffsetT(body[len(body)-4:])
|
|
||||||
buf := body[:len(body) - 4]
|
|
||||||
|
|
||||||
req := net.GetRootAsRequest(buf, off)
|
|
||||||
player := req.Player(nil)
|
player := req.Player(nil)
|
||||||
|
|
||||||
fmt.Printf("Got request (name: %v, hp: %v)\n", string(player.Name()), player.Hp())
|
fmt.Printf("Got request (name: %v, hp: %v)\n", string(player.Name()), player.Hp())
|
||||||
|
|||||||
Reference in New Issue
Block a user