github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/testutil/httptransporttestutil/server/cmd/client_protobuf_req/main.go (about) 1 package main 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "fmt" 7 "io" 8 "log" 9 "net/http" 10 "os" 11 12 "github.com/golang/protobuf/proto" 13 14 testdatapb "github.com/machinefi/w3bstream/pkg/depends/kit/httptransport/transformer/testdata" 15 ) 16 17 var ( 18 url = "http://127.0.0.1:8080/demo/binary/protobuf" 19 contentType = "application/x-protobuf" 20 ) 21 22 func main() { 23 cli := &http.Client{} 24 25 // body1, err := genProtobufBody(&testdatapb.Event{Header: &testdatapb.Header{EventId: "1"}}) 26 // checkError(err) 27 // doRequestAndOutput(cli, body1) 28 // expected: 29 // {"event_id":"1","succeeded":true} 30 31 body2, err := genProtobufBody(&testdatapb.Event{}) 32 checkError(err) 33 doRequestAndOutput(cli, body2) 34 // expected: 35 // {"err_msg":"invalid event id"} 36 } 37 38 func doRequestAndOutput(cli *http.Client, body io.Reader) { 39 rsp, err := cli.Post(url, contentType, body) 40 checkError(err) 41 42 data, err := io.ReadAll(rsp.Body) 43 checkError(err) 44 defer rsp.Body.Close() 45 46 pbrsp := &testdatapb.HandleResult{} 47 checkError(proto.Unmarshal(data, pbrsp)) 48 49 jsonrsp, err := json.Marshal(pbrsp) 50 checkError(err) 51 52 fmt.Println(string(jsonrsp)) 53 } 54 55 func genProtobufBody(msg proto.Message) (*bytes.Buffer, error) { 56 data, err := proto.Marshal(msg) 57 if err != nil { 58 return nil, err 59 } 60 return bytes.NewBuffer(data), nil 61 } 62 63 func checkError(err error) { 64 if err != nil { 65 log.Fatal(err) 66 os.Exit(-1) 67 } 68 }