http Programming
1 ) Go native support http: Import ( " NET / http " ) 2 ) Go's http service performance and nginx closer to 3 ) a few lines of code to implement a web service
http server
// sample code: Package main Import ( " FMT " " NET / HTTP " ) FUNC the Hello (http.ResponseWriter W, R & lt * http.Request) { fmt.Println ( " Hello World \ n- " ) fmt.Fprintf (W, " Hello World " ) // returns the response } FUNC main () { http.HandleFunc ( " / " , the Hello) // route; first parameter is the path, the second argument is the view function err: = http.ListenAndServe ( " 0.0.0.0:8080 " , nil) //Listens and waits for requests IF ERR! = Nil { fmt.Println ( " HTTP Listened failed " ) } }
http client
// sample code: Package main Import ( " FMT " " NET / HTTP " " IO / ioutil " ) FUNC main () { RET, ERR: = http.Get ( " https://www.baidu.com/ " ) // send GET request to a server; data returned in ret.Body inside IF ERR =! nil { fmt.Println ( " GET ERR: " , ERR) return } data, ERR: = ioutil.ReadAll (ret.Body ) // returned data are ret.Body inside IF ERR! = nil { fmt.Println ("get data err:",err) return } fmt.Printf("Type:%T\n",data) fmt.Println(string(data)) } // 运行结果: [root@NEO example01_http_client]# go run main/main.go Type:[]uint8 <html> <head> <script> location.replace(location.href.replace("https://","http://")); </script> </head> <body> <noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript> </body> </html> [root@NEO example01_http_client]#
http common request methods
. 1 ) the Get Request 2 ) Post request . 3 ) of Put request . 4 ) the Delete request . 5 ) Head Request -> Request header page only
Sends a HEAD request
// 示例代码: package main import ( "fmt" "net/http" ) var urls = []string{ "http://www.baidu.com", "http://www.google.com", "http://www.taobao.com", } func main(){ for _,v := range urls{ resp,err := http.Head(v) // 发送 Head 请求 if err != nil { fmt.Printf("head %s failed,err:%v\n",v,err) continue } fmt.Printf("head success,status:%v\n",resp.Status) // resp.Status --> 状态码 } } // 运行结果: [root@NEO example01_http_head_request]# go run main/main.go head success,status:200 OK head http://www.google.com failed,err:Head http://www.google.com: dial tcp 75.126.2.43:80: connect: connection timed out head success,status:200 OK [root@NEO example01_http_head_request]# // 自定义超时时间 // 示例代码: package main import ( "fmt" "net/http" "time" "net" ) var urls = []string{ "http://www.baidu.com", "http://www.google.com", "http://www.taobao.com", } func main(){ for _,v := range urls{ c := http.Client{ // 自定义客户端 Transport: &http.Transport{ The Dial: FUNC (Network, addr String ) (net.Conn, error) { timeout: = time.Second * 2 // custom timeout return net.DialTimeout (Network, addr, timeout) }, }, } Start: = Time.now () RESP, ERR: = c.Head (V) // with defined from the client sends a request end: = Time.now () interval the: = end.Sub (Start) fmt.Println ( " interval the: " , interval The) // RESP, ERR: = http.Head (v) // send request Head IF ERR =! Nil { fmt.Printf ( " head% S failed, ERR: V% \ n- " , V, ERR) Continue } fmt.Printf ( " head Success, Status:% V \ n- " , resp.Status) // resp.Status -> status code } } // run results: [@ NEO example01_http_head_request the root] # Go main rUN / main.go interval The: 171 is .062376ms head Success, status: 200 is the OK interval The: 2 .000789206s head HTTP: //www.google.com failed,err:Head http://www.google.com: dial tcp 69.63.184.142:80: i/o timeout interval: 749.542763ms head success,status:200 OK [root@NEO example01_http_head_request]#
http common status codes:
http.StatusContinue = 100 http.StatusOK = 200 http.StatusFound = 302 http.StatusBadRequest = 400 http.StatusUnauthorized = 401 http.StatusForbidden = 403 http.StatusNotFound = 404 http.StatusInternalServerError = 500
Form processing:
// 示例代码: package main import ( "io" "net/http" ) // 常量 form 是一段 html 代码 const form = `<html><body><form action="#" method="post" name="bar"> <input type="text" name="in"/> <input type="text" name="in"/> <input type="submit" value="Submit"/> </form></html></body>` func SimpleServer(w http.ResponseWriter, request *http.Request) { // 请求信息都在 request 中 io.WriteString(w, "<h1>hello, world</h1>") // 返回给客户端一段html代码 } func FormServer(w http.ResponseWriter, request *http.Request) { w.Header().Set("Content-Type", "text/html") // w.Head (). Set (key, val) ---> Set response header Switch request.method { // request.method -> Request Method Case " the GET " : io.WriteString (W, form) // the return form form to the client Case " the POST " : request.ParseForm () // required to parse form io.WriteString (W, request.Form [ " in " ] [ 0 ]) // request.Form [ "in"] is an array io.WriteString (W, " \ n- " ) io.WriteString (W, request.FormValue ( " in " )) // request.FormValue ( "in") ---> Get values in the form (name when repeated, rounded to the nearest a); this recommended } } main FUNC () { http.HandleFunc ( " / test1 " , SimpleServer) http.HandleFunc ( " / test2 " , FormServer) IF ERR: = http.ListenAndServe ( " : 8088 " !, nil); ERR = nil { } }