【go】http实验
实验1:上手篇
package main import ( "net/http" //"fmt" "os" ) func proxyFunc(response http.ResponseWriter, req *http.Request) { os.Stdout.WriteString(req.Host + "\n") response.Write([]byte(req.Host +"\n")) return } func main() { http.HandleFunc("/", proxyFunc) http.ListenAndServe(":9111", nil) }
编译:go build proxy.go
执行:./proxy
客户端测试:curl curl http://127.0.0.1:9111/
测试输出:127.0.0.1:9111
实验2:获取request的body数据长度
package main import ( "net/http" "fmt" "io/ioutil" ) func proxyFunc(response http.ResponseWriter, req *http.Request) { body, _ := ioutil.ReadAll(req.Body) bodyLen := len(string(body)) response.Write([]byte(fmt.Sprintf("body len: %d\n", bodyLen))) return } func main() { http.HandleFunc("/", proxyFunc) http.ListenAndServe(":9111", nil) }
执行:go build proxy.go && ./proxy
测试:curl --data "a=a" http://127.0.0.1:9111/
测试输出:body len: 3
实验3:做个中转机,前端请求,go中转给后端的服务
proxy.go代码
package main import ( "net/http" //"fmt" "io/ioutil" //"strings" ) func proxyFunc(response http.ResponseWriter, req *http.Request) { client := &http.Client{} path := req.URL.Path query := req.URL.RawQuery url := "http://127.0.0.1:9112" url += path if len(query) > 0 { url += "?" + query } proxyReq, err := http.NewRequest("POST", url, req.Body) if err != nil { response.Write([]byte("http proxy request fail\n")) return } proxyReq.Header.Set("Content-Type", "application/x-www-form-urlencoded") proxyReq.Header.Set("Cookie", "name=cookie") resp, err := client.Do(proxyReq) defer resp.Body.Close() out, _ := ioutil.ReadAll(resp.Body) response.Write(out) } func main() { http.HandleFunc("/", proxyFunc) http.ListenAndServe(":9111", nil) }
backend.go代码
package main import ( "io/ioutil" "net/http" ) func procFunc(response http.ResponseWriter, req *http.Request) { postBody, _ := ioutil.ReadAll(req.Body) response.Write([]byte("query: " + req.URL.RawQuery + "\nbody: ")) response.Write(postBody) response.Write([]byte("\n")) response.Write([]byte("backend port: 9112\n")) } func main() { http.HandleFunc("/", procFunc) http.ListenAndServe(":9112", nil) }
proxy负责中转客户端请求,转到backend来处理,backend根据输入,直接打印其输出 query + post body
测试:curl --data "a=a" http://127.0.0.1:9111/?b=b1111
测试输出:
query: b=b1111 body: a=a backend port: 9112
本篇文章测试了:go的http server,http server对应的post数据,和golang的http request能力,代码很简单
结束分隔符!