go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/testing/httpmitm/example_httpmitm_test.go (about) 1 // Copyright 2015 The LUCI Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package httpmitm 16 17 import ( 18 "bytes" 19 "fmt" 20 "net/http" 21 "net/http/httptest" 22 "strings" 23 ) 24 25 func getBody(s string) (body []string) { 26 pastHeaders := false 27 for _, part := range strings.Split(s, "\r\n") { 28 if pastHeaders { 29 body = append(body, part) 30 } else if part == "" { 31 pastHeaders = true 32 } 33 } 34 return 35 } 36 37 func Example() { 38 // Setup test server. 39 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 40 w.Write([]byte("Hello, Client!")) 41 })) 42 defer ts.Close() 43 44 // Setup instrumented client. 45 type record struct { 46 o Origin 47 d string 48 } 49 var records []*record 50 client := http.Client{ 51 Transport: &Transport{ 52 Callback: func(o Origin, data []byte, err error) { 53 records = append(records, &record{o, string(data)}) 54 }, 55 }, 56 } 57 58 _, err := client.Post(ts.URL, "test", bytes.NewBufferString("Hail, Server!")) 59 if err != nil { 60 return 61 } 62 63 // There should be two records: request and response. 64 for idx, r := range records { 65 fmt.Printf("%d) %s\n", idx, r.o) 66 for _, line := range getBody(r.d) { 67 fmt.Println(line) 68 } 69 } 70 71 // Output: 72 // 0) Request 73 // Hail, Server! 74 // 1) Response 75 // Hello, Client! 76 }