github.com/kaiya/goutils@v1.0.1-0.20230226104005-4ae4a4dc3688/http/http_test.go (about) 1 package http 2 3 import ( 4 "context" 5 "io" 6 "net" 7 "testing" 8 "time" 9 10 "gitlab.momoso.com/cm/kit/pkg/basic/logrender" 11 "gitlab.momoso.com/cm/kit/pkg/net/httpclient" 12 ) 13 14 func TestTinyHttp(t *testing.T) { 15 go func() { 16 //server 17 lis, err := net.Listen("tcp4", "127.0.0.1:3000") 18 if err != nil { 19 t.Errorf("listen error:%s", err) 20 } 21 // for { 22 conn, err := lis.Accept() 23 if err != nil { 24 t.Errorf("accept error:%s", err) 25 // break 26 } 27 /* 28 buf := make([]byte, 10240) 29 for { 30 n, err := conn.Read(buf) 31 t.Logf("got len:%d, err:%v, str:%s", n, err, string(buf)) 32 33 if err == io.EOF { 34 break 35 } 36 } 37 */ 38 39 // read using io.readall 40 reqBytes, err := io.ReadAll(conn) 41 if err != nil { 42 t.Errorf("readall from req error:%s", err) 43 44 } 45 t.Logf("req:%s", string(reqBytes)) 46 // read from scanner 47 /* 48 scanner := bufio.NewScanner(conn) 49 for scanner.Scan() { 50 t.Logf("got from conn:%s", scanner.Text()) 51 } 52 */ 53 54 // t.Logf("scanner error:%s", scanner.Err()) 55 /* 56 reader := bufio.NewReader(conn) 57 58 bytes, err := reader.ReadBytes('\n') 59 60 if err != nil { 61 t.Errorf("read bytes error:%s", err) 62 } 63 t.Logf("got from conn:%s", string(bytes)) 64 */ 65 // } 66 }() 67 68 //client 69 /* 70 _, err := http.Get("http://127.0.0.1:3000/test") 71 if err != nil { 72 t.Errorf("http get error:%s", err) 73 } 74 */ 75 httpclient.NewClient(&httpclient.Config{ 76 RequestTimeout: 10 * time.Second, 77 Render: &logrender.Config{ 78 Stdout: true, 79 StdoutPattern: "*", 80 }, 81 }).PostJSON(context.Background(), "http://127.0.0.1:3000/post-json", nil, nil, map[string]string{"json-key": "json-value"}) 82 time.Sleep(30 * time.Second) 83 84 }