Language basis of Go net / http
June 26, 2017
| Golang
| 302 Reading
Go languages built-in net/http
package is very good, provides an implementation of HTTP client and server.
net / http introduction
Go languages built-in net/http
package provides an implementation of HTTP client and server.
HTTP protocol
Hypertext Transfer Protocol (HTTP, HyperText Transfer Protocol) is the Internet's most widely used method of transmission protocols, all WWW documents must comply with this standard. HTTP was originally designed purpose is to provide a method to publish and receive HTML pages.
HTTP client
Basic HTTP / HTTPS requests
Get, Head, Post PostForm function issues and HTTP / HTTPS requests.
resp, err := http.Get("http://example.com/")
...
resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf)
...
resp, err := http.PostForm("http://example.com/form",
url.Values{"key": {"Value"}, "id": {"123"}})
Program must shut down the main reply after using response.
resp, err := http.Get("http://example.com/")
if err != nil {
// handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
// ...
Example GET request
Use net/http
packet write a simple transmission Client-side HTTP request, as follows:
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
resp, err := http.Get("https://www.liwenzhou.com/")
if err != nil {
fmt.Println("get failed, err:", err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("read from resp.Body failed,err:", err)
return
}
fmt.Print(string(body))
}
After the above code is compiled into an executable file saved, you can print in the terminal after the implementation of liwenzhou.com
the content of the website home page, our browser is actually a HTTP protocol to send and receive data to the client, we usually accessed through the web browser actually HTTP is to receive data from the server site, then the browser will follow the HTML, CSS and other rules will show up page rendering.
Example GET request with parameters
About GET request parameters need to use the built-in language Go net/url
to this standard library to handle.
func main() {
apiUrl := "http://127.0.0.1:9090/get"
// URL param
data := url.Values{}
data.Set("name", "小王子")
data.Set("age", "18")
u, err := url.ParseRequestURI(apiUrl)
if err != nil {
fmt.Printf("parse url requestUrl failed,err:%v\n", err)
}
u.RawQuery = data.Encode() // URL encode
fmt.Println(u.String())
resp, err := http.Get(u.String())
if err != nil {
fmt.Println("post failed, err:%v\n", err)
return
}
defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("get resp failed,err:%v\n", err)
return
}
fmt.Println(string(b))
}
Server side corresponding HandlerFunc follows:
func getHandler(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
data := r.URL.Query()
fmt.Println(data.Get("name"))
fmt.Println(data.Get("age"))
answer := `{"status": "ok"}`
w.Write([]byte(answer))
}
Post request Example
The above demonstrates the use of net/http
packet transmission GET
example of a request, send POST
the sample code request:
package main
import (
"fmt"
"io/ioutil"
"net/http"
"strings"
)
// net/http post demo
func main() {
url := "http://127.0.0.1:9090/post"
// 表单数据
//contentType := "application/x-www-form-urlencoded"
//data := "name=小王子&age=18"
// json
contentType := "application/json"
data := `{"name":"小王子","age":18}`
resp, err := http.Post(url, contentType, strings.NewReader(data))
if err != nil {
fmt.Println("post failed, err:%v\n", err)
return
}
defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("get resp failed,err:%v\n", err)
return
}
fmt.Println(string(b))
}
Server side corresponding HandlerFunc follows:
func postHandler(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
// 1. 请求类型是application/x-www-form-urlencoded时解析form数据
r.ParseForm()
fmt.Println(r.PostForm) // 打印form数据
fmt.Println(r.PostForm.Get("name"), r.PostForm.Get("age"))
// 2. 请求类型是application/json时从r.Body读取数据
b, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Println("read request.Body failed, err:%v\n", err)
return
}
fmt.Println(string(b))
answer := `{"status": "ok"}`
w.Write([]byte(answer))
}
Custom Client
To manage the client's HTTP header field, redirection policy and other settings, create a Client:
client := &http.Client{
CheckRedirect: redirectPolicyFunc,
}
resp, err := client.Get("http://example.com")
// ...
req, err := http.NewRequest("GET", "http://example.com", nil)
// ...
req.Header.Add("If-None-Match", `W/"wyzzy"`)
resp, err := client.Do(req)
// ...
Custom Transport
To manage the proxy, TLS configuration, keep-alive, compression and other settings, create a Transport:
tr := &http.Transport{
TLSClientConfig: &tls.Config{RootCAs: pool},
DisableCompression: true,
}
client := &http.Client{Transport: tr}
resp, err := client.Get("https://example.com")
Client and Transport types can be safely used simultaneously by multiple go away. For efficiency reasons, we should first establish, as far as possible reuse.
Server
Default Server
ListenAndServe specified listen address and the processor starts a HTTP server. Parameter processor usually is nil, which means that use of the package as the processor DefaultServeMux variable.
Handle and HandleFunc functions may be added to the processor DefaultServeMux.
http.Handle("/foo", fooHandler)
http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
})
log.Fatal(http.ListenAndServe(":8080", nil))
Default Server example
Go language used net/http
package to write a simple example of the receiving end Server HTTP request net/http
packet is further encapsulated packet to the net, and data dedicated to handling the HTTP protocol. Specific code as follows:
// http server
func sayHello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello 沙河!")
}
func main() {
http.HandleFunc("/", sayHello)
err := http.ListenAndServe(":9090", nil)
if err != nil {
fmt.Printf("http server failed, err:%v\n", err)
return
}
}
After the implementation of the above code is compiled, open your browser on your computer in the address bar 127.0.0.1:9090
Enter, at this time you can see the following page.
Custom Server
To manage the behavior of the server, you can create a custom Server:
s := &http.Server{
Addr: ":8080",
Handler: myHandler,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
log.Fatal(s.ListenAndServe())