github.com/gogf/gf@v1.16.9/.example/net/gtcp/gtcp_conn.go (about) 1 package main 2 3 import ( 4 "bytes" 5 "fmt" 6 "os" 7 8 "github.com/gogf/gf/net/gtcp" 9 "github.com/gogf/gf/util/gconv" 10 ) 11 12 func main() { 13 conn, err := gtcp.NewConn("www.baidu.com:80") 14 if err != nil { 15 panic(err) 16 } 17 defer conn.Close() 18 19 if err := conn.Send([]byte("GET / HTTP/1.1\r\n\r\n")); err != nil { 20 panic(err) 21 } 22 23 header := make([]byte, 0) 24 content := make([]byte, 0) 25 contentLength := 0 26 for { 27 data, err := conn.RecvLine() 28 // header读取,解析文本长度 29 if len(data) > 0 { 30 array := bytes.Split(data, []byte(": ")) 31 // 获得页面内容长度 32 if contentLength == 0 && len(array) == 2 && bytes.EqualFold([]byte("Content-Length"), array[0]) { 33 // http 以\r\n换行,需要把\r也去掉 34 contentLength = gconv.Int(string(array[1][:len(array[1])-1])) 35 } 36 header = append(header, data...) 37 header = append(header, '\n') 38 } 39 // header读取完毕,读取文本内容, 1为\r 40 if contentLength > 0 && len(data) == 1 { 41 content, _ = conn.Recv(contentLength) 42 break 43 } 44 if err != nil { 45 fmt.Fprintf(os.Stderr, "ERROR: %s\n", err.Error()) 46 break 47 } 48 } 49 50 if len(header) > 0 { 51 fmt.Println(string(header)) 52 } 53 if len(content) > 0 { 54 fmt.Println(string(content)) 55 } 56 }