go语言之进阶篇http客户端编程
1、http客户端编程
示例:
http_server.go
package main import ( "fmt" "net/http" ) //w, 给客户端回复数据 //r, 读取客户端发送的数据 func HandConn(w http.ResponseWriter, r *http.Request) { fmt.Println("r.Method = ", r.Method) fmt.Println("r.URL = ", r.URL) fmt.Println("r.Header = ", r.Header) fmt.Println("r.Body = ", r.Body) w.Write([]byte("hello go")) //给客户端回复数据 } func main() { //注册处理函数,用户连接,自动调用指定的处理函数 http.HandleFunc("/", HandConn) //监听绑定 http.ListenAndServe(":8000", nil) }
http_client.go
package main import ( "fmt" "net/http" ) func main() { //resp, err := http.Get("http://www.baidu.com") resp, err := http.Get("http://127.0.0.1:8000") if err != nil { fmt.Println("http.Get err = ", err) return } defer resp.Body.Close() fmt.Println("Status = ", resp.Status) fmt.Println("StatusCode = ", resp.StatusCode) fmt.Println("Header = ", resp.Header) //fmt.Println("Body = ", resp.Body) buf := make([]byte, 4*1024) var tmp string for { n, err := resp.Body.Read(buf) if n == 0 { fmt.Println("read err = ", err) break } tmp += string(buf[:n]) } //读取网页内容,打印出来 fmt.Println("tmp = ", tmp) }
执行结果:
先运行服务端:
D:\GoFiles\src\hello_01>go run http_server.go r.Method = GET r.URL = / r.Header = map[User-Agent:[Go-http-client/1.1] Accept-Encoding:[gzip]] r.Body = {}
再运行客户端:
D:\GoFiles\src\hello_01>go run http_client.go Status = 200 OK StatusCode = 200 Header = map[Date:[Sat, 26 Jan 2019 07:04:09 GMT] Content-Length:[8] Content-Ty pe:[text/plain; charset=utf-8]] read err = EOF tmp = hello go