github.com/cloudwego/dynamicgo@v0.2.6-0.20240519101509-707f41b6b834/http/http_test.go (about) 1 /** 2 * Copyright 2023 CloudWeGo Authors. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package http 18 19 import ( 20 "bytes" 21 "net/http" 22 "net/url" 23 "strings" 24 "testing" 25 26 "github.com/stretchr/testify/require" 27 ) 28 29 func TestJSONBody(t *testing.T) { 30 var data = []byte(`{"name":"foo","age":18}`) 31 req, err := http.NewRequest("POST", "http://localhost:8080", bytes.NewBuffer(data)) 32 if err != nil { 33 t.Fatal(err) 34 } 35 req.Header.Set("Content-Type", "application/json") 36 r, err := NewHTTPRequestFromStdReq(req) 37 if err != nil { 38 t.Fatal(err) 39 } 40 require.Equal(t, `foo`, r.GetMapBody("name")) 41 require.Equal(t, "18", r.GetMapBody("age")) 42 } 43 44 func TestPostFormBody(t *testing.T) { 45 var data = url.Values{ 46 "name": {"{\"foo\":\"bar\"}", "bar"}, 47 "age": {"18"}, 48 }.Encode() 49 req, err := http.NewRequest("POST", "http://localhost:8080", strings.NewReader(data)) 50 if err != nil { 51 t.Fatal(err) 52 } 53 req.Header.Set("Content-Type", "application/x-www-form-urlencoded") 54 r, err := NewHTTPRequestFromStdReq(req) 55 if err != nil { 56 t.Fatal(err) 57 } 58 require.Equal(t, "{\"foo\":\"bar\"}", r.GetMapBody("name")) 59 require.Equal(t, "{\"foo\":\"bar\"}", r.FormValue("name")) 60 require.Equal(t, "18", r.GetMapBody("age")) 61 require.Equal(t, "18", r.FormValue("age")) 62 }