gitee.com/liuxuezhan/go-micro-v1.18.0@v1.0.0/api/handler/rpc/rpc_test.go (about) 1 package rpc 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "net/http" 7 "testing" 8 9 "github.com/golang/protobuf/proto" 10 go_api "gitee.com/liuxuezhan/go-micro-v1.18.0/api/proto" 11 ) 12 13 func TestRequestPayloadFromRequest(t *testing.T) { 14 15 // our test event so that we can validate serialising / deserializing of true protos works 16 protoEvent := go_api.Event{ 17 Name: "Test", 18 } 19 20 protoBytes, err := proto.Marshal(&protoEvent) 21 if err != nil { 22 t.Fatal("Failed to marshal proto", err) 23 } 24 25 jsonBytes, err := json.Marshal(protoEvent) 26 if err != nil { 27 t.Fatal("Failed to marshal proto to JSON ", err) 28 } 29 30 t.Run("extracting a proto from a POST request", func(t *testing.T) { 31 r, err := http.NewRequest("POST", "http://localhost/my/path", bytes.NewReader(protoBytes)) 32 if err != nil { 33 t.Fatalf("Failed to created http.Request: %v", err) 34 } 35 36 extByte, err := requestPayload(r) 37 if err != nil { 38 t.Fatalf("Failed to extract payload from request: %v", err) 39 } 40 if string(extByte) != string(protoBytes) { 41 t.Fatalf("Expected %v and %v to match", string(extByte), string(protoBytes)) 42 } 43 }) 44 45 t.Run("extracting JSON from a POST request", func(t *testing.T) { 46 r, err := http.NewRequest("POST", "http://localhost/my/path", bytes.NewReader(jsonBytes)) 47 if err != nil { 48 t.Fatalf("Failed to created http.Request: %v", err) 49 } 50 51 extByte, err := requestPayload(r) 52 if err != nil { 53 t.Fatalf("Failed to extract payload from request: %v", err) 54 } 55 if string(extByte) != string(jsonBytes) { 56 t.Fatalf("Expected %v and %v to match", string(extByte), string(jsonBytes)) 57 } 58 }) 59 60 t.Run("extracting params from a GET request", func(t *testing.T) { 61 62 r, err := http.NewRequest("GET", "http://localhost/my/path", nil) 63 if err != nil { 64 t.Fatalf("Failed to created http.Request: %v", err) 65 } 66 67 q := r.URL.Query() 68 q.Add("name", "Test") 69 r.URL.RawQuery = q.Encode() 70 71 extByte, err := requestPayload(r) 72 if err != nil { 73 t.Fatalf("Failed to extract payload from request: %v", err) 74 } 75 if string(extByte) != string(jsonBytes) { 76 t.Fatalf("Expected %v and %v to match", string(extByte), string(jsonBytes)) 77 } 78 }) 79 80 t.Run("GET request with no params", func(t *testing.T) { 81 82 r, err := http.NewRequest("GET", "http://localhost/my/path", nil) 83 if err != nil { 84 t.Fatalf("Failed to created http.Request: %v", err) 85 } 86 87 extByte, err := requestPayload(r) 88 if err != nil { 89 t.Fatalf("Failed to extract payload from request: %v", err) 90 } 91 if string(extByte) != "" { 92 t.Fatalf("Expected %v and %v to match", string(extByte), "") 93 } 94 }) 95 }