Net/http Library Learning Concept Processor
- Servemux structure (with Servehttp method, signed as above)
- Handler structure
- Multiplexer Defaultservemux (example of SERVEMUX structure)
Processor functions
- Functions that have the same behavior as the processor
- Have the same signature as the Servehttp method
Servemux
- HTTP request Multiplexer
- __ receives the HTTP request and redirects the request to the correct processor based on the __url__ in the request
- The SERVEMUX structure also implements the Servehttp method, which is also a processor
- Servemux Servehttp method that calls the Servehttp method of the processor __ corresponding to the requested URL
The simplest Web server
import "fmt"import "net/http"// 处理器type HelloHandler struct{}func ( h *HelloHandler) ServeHTTP ( w http.ResponseWriter, r * http.Request){ fmt.Fprintf( w, "Hello" )}// 处理器函数func hello( w http.ResponseWriter, r * http.Request){ fmt.Fprintf( w, "Hello" )} func main () { server := http.Server{ Addr: "127.0.0.1:8080", //Handler: nil, //可以指定处理器 } fmt.Println("hello https://tool.lu/") //http.ListenAndServe(":8181", nil) //server.ListenAndServe() // 将 处理器 绑定到DefaultServeMux // Handle是ServeMux结构的方法,而DefaultServeMux是ServeMux的实例 //hello := HelloHandler{} //http.Handle("/hello", &hello) // 将函数转换为处理器,再将处理器绑定到DefaultServeMux //http.HandleFunc( "/hello", hello ) //使用默认的多路复用器DefaultServeMux作为处理器 server.ListenAndServeTLS("cert.pem", "key.pem")}
HTTP Client
http. Newrequest
- Htp. Client-Http.request (http. newrequest), client. Do (Request)
- Newrequest (method, urlstr string, body io. Reader)
- The third parameter is the contents of the requested body
- Request. Header.set
- Adding information to the request header
http. Clinet
- Cient Structure API
- Client parameter Configuration
- Transport Roundtripper
- Checkredirect func (req Request, via []request) error
- Jar Cookiejar
- Timeout time. Duration
- Transport
- To control the agent, Secure Sockets Layer settings, maintain connections , compression, timeout settings, and other settings, you need to create a transport
- Maxidleconns
- Maximum number of connections to all host
- Maxidleconnsperhost
- The maximum number of connections to __ per host__
tr := &http.Transport{ TLSClientConfig: &tls.Config{RootCAs: pool}, DisableCompression: true, } client := &http.Client{Transport: tr} resp, err := client.Get("https://example.com")tr := &http.Transport{ MaxIdleConnsPerHost: 1000, //是否表示最多建立1000个连接?}client := &http.Client{ Transport: tr,}
http
resp. Body.close ()
- When the client finishes using the response body, it must be closed with close
Httplib Learning
Https://github.com/astaxie/beego
Concept
- The Httplib library is primarily used to impersonate a client to send an HTTP request
- Similar to the Curl tool
Use
- Request Object
- Debug output
- Set TLS information for Clinet
Gin Learning
Package Testsimport ("Encoding/json" "FMT" "Github.com/astaxie/beego/httplib" "Github.com/gin-gonic/gin" " Io/ioutil "" "Log" "Net/http" "Strings" "Testing" "Time") func Handletestget (c *gin. Context) {c.string (http. Statusok, "Test get OK")}func Handletestpost (c *gin. Context) {C.json (http. Statusok, Gin. h{"Code": 1, "message": "Test post OK"})}func Handleparam (c *gin. Context) {Name: = C.param ("name") passwd: = C.param ("passwd") c.string (http. Statusok, "Name:%s, passwd:%s", name, passwd)}func handlequery (c *gin. Context) {Name: = C.query ("name") passwd: = C.query ("passwd") c.string (http. Statusok, "Name:%s, passwd:%s", name, passwd)}func handlehttplib (c *gin. Context) {C.indentedjson, gin. h{"Code": 1, "Data": "OK"})}func Runtbasicginserver () {fmt. Print ("AA") Router: = Gin. Default () router. GET ("/test_get", Handletestget) router. POST ("/test_post", Handletestpost) router. GET ("/test_param/:name/*passwd", HandleparAM) router. GET ("/test_query", Handlequery) router. GET ("/test_httplib", handlehttplib) Group: = Router. Group ("/V1") group. GET ("/test_group", Handletestget) router. Run (": 6543")}func Printgetresp (resp *http. Response) {Defer resp. Body.close () bodybytes, err: = Ioutil. ReadAll (resp. Body) If err! = Nil {log. Printf ("Read body err%s\n", err.) Error ())} log. Printf ("Resp body is:%+v\n", String (bodybytes))}func Printpostresp (resp *http. Response) {Defer resp. Body.close () bodybytes, err: = Ioutil. ReadAll (resp. Body) If err! = Nil {log. Printf ("Read body err%s\n", err.) Error ())} type body struct {code int ' JSON: ' Code ' ' message string ' JSON: ' Message ' '} res Pbody: = body{} err = json. Unmarshal (Bodybytes, &respbody) if err! = Nil {log. Printf ("Unmarshal Body err%s\n", err. Error ())} log. Printf ("Resp body is:%+v\n", Respbody)}func testbasicclient (t *testing. T) {Go runtbasicginserver () Time. Sleep (time. Second * 5) resp, err: = http. Get ("Http://127.0.0.1:6543/test_get") if err! = Nil {log. Printf ("Get resp err%s\n", err. Error ())} printgetresp (RESP) resp, err = http. Post ("Http://127.0.0.1:6543/test_post", "", Strings. Newreader ("")) if err! = Nil {log. Printf ("Get resp err%s\n", err. Error ())} printpostresp (RESP) resp, err = http. Get ("http://127.0.0.1:6543/test_param/name=Bob/passwd=1234") if err! = Nil {log. Printf ("Get resp err%s\n", err. Error ())} printgetresp (RESP) resp, err = http. Get ("http://127.0.0.1:6543/test_param/name=Bob/") if err! = Nil {log. Printf ("Get resp err%s\n", err. Error ())} printgetresp (RESP) resp, err = http. Get ("Http://127.0.0.1:6543/test_param/name=Bob") if err! = Nil {log. Printf ("Get resp err%s\n", err. Error ())} printgetresp (RESP) resp, err = http. Get ("http://127.0.0.1:6543/test_query?name=Alice&passwd=123") if err! = Nil {log.printf ("Get resp err%s\n", err. Error ())} printgetresp (RESP) resp, err = http. Get ("Http://127.0.0.1:6543/v1/test_group") if err! = Nil {log. Printf ("Get resp err%s\n", err. Error ())} PRINTGETRESP (resp) Res: = struct {code int ' JSON: ' Code ' ' Message string ' json: ' Me Ssage "'} {} if err: = Httplib. Get ("Http://127.0.0.1:6543/test_httplib"). ToJSON (&res); Err! = Nil {log. Println (Err. Error ())} log. Printf ("%+v", res)}func Testreusehttplink (t *testing. T) {go runtbasicginserver () time. Sleep (time. Second * 5) tr: = &http. transport{maxidleconnsperhost:100, Maxidleconns:100,} c: = http. CLIENT{TRANSPORT:TR} URL: = "http://127.0.0.1:6543/test_get"/* Number of connections that are currently created when no remaining available connections are present; Available connections do not create *//Use Channel to control HTTP port numbers ch: = Make (chan struct{}, +) for I: = 0; I < 5000; i++ {go func (i int) {ch <-struct{}{} defer func () {<-ch} () req, err: = http. Newrequest ("GET", url, nil) if err! = Nil {log. Printf ("Get req Error%s", err.) Error ())} resp, err: = C.do (req) If err! = Nil {log. Printf ("Do req error%s", err.) Error ())} Defer resp. Body.close () bodybytes, err: = Ioutil. ReadAll (resp. Body) If err! = Nil {log. Printf ("Read body error%s", err.) Error ())} log. Printf ("%d Body:%s", I, String (bodybytes))} (i)//time. Sleep (time. Microsecond *)//time. Sleep (time. Microsecond *)} time. Sleep (time. Second *)}func testseqdo (t *testing. T) {go runtbasicginserver () time. Sleep (time. Second * 5) c: = http. client{} URL: = "http://127.0.0.1:6543/test_get"/* Defaul reuse HTTP link There is one link to 6543 */For I: = 0; I < 5000; i++ {req, err: = http. Newrequest ("GET", url, nil) if err! = Nil {log. Printf ("Get req Error%s", err.) Error ())} resp, err: = C.do (req) If err! = Nil {log. Printf ("Do req error%s", err.) Error ())} Defer resp. Body.close () bodybytes, err: = Ioutil. ReadAll (resp. Body) If err! = Nil {log. Printf ("Read body error%s", err.) Error ())} log. Printf ("%d Body:%s", I, String (bodybytes))} time. Sleep (time. Second *)}func testseqhttplib (t *testing. T) {go runtbasicginserver () time. Sleep (time. Second * 5) URL: = "http://127.0.0.1:6543/test_get"/*??? NETSTAT-ANP | grep 6543 | grep established */For I: = 0; I < 5000; i++ {bodystring, err: = Httplib. Get (URL). String () if err! = Nil {log. Printf ("Httplib get error%s", err.) Error ())} log. Printf ("%d Body:%s", I, bodystring)} time. Sleep (time. Second * 10)}
Binding Learning
Github.com/gin-gonic/gin/binding
HTTPS Service Reference
"Go Web Programming"
Go Language _http Pack
Deep dive into the basic implementation of the Go Language network library
Several common scenarios for sending HTTP requests in Golang
Net/http Interpretation of Go language
Go net/http Client Use--use of long connect clients
Https://github.com/astaxie/beego
Beego Chinese Documents
Go Language HTTP Learning