Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Detailed introduction of Golang net/http knowledge

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "detailed introduction of Golang net/http knowledge". In the operation of actual cases, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

The following is the study of net/http.

Processing HTTP requests in the Go language is mainly related to two things: ServeMux and Handler. ServrMux is essentially an HTTP request router (or Multiplexor). It compares the received request with a predefined list of URL paths and then invokes the associated processor (Handler) when the path is matched.

The processor (Handler) is responsible for outputting the header and body of the HTTP response. Any object that satisfies the http.Handler interface can be used as a processor. Generally speaking, an object only needs to have a ServeHTTP method with the following signature:

ServeHTTP (http.ResponseWriter, * http.Request)

The HTTP package for the Go language comes with several functions that are used as common handlers, such as FileServer,NotFoundHandler and RedirectHandler. Let's start with a simple and concrete example:

Package mainimport ("log"net/http") func main () {mux: = http.NewServeMux () rh: = http.RedirectHandler ("http://www.baidu.com", 307) mux.Handle (" / foo ", rh) log.Println (" Listening... ") Http.ListenAndServe (": 3000", mux)}

A quick look at the code:

In the main function, we only use the http.NewServeMux function to create an empty ServeMux. Then we use the http.RedirectHandler function to create a new processor that performs 307 redirects to http://www.baidu.com for all requests received. Next we use the ServeMux.Handle function to register the processor with the newly created ServeMux, so all requests it receives on the URL path / foo are handed over to this processor. Finally, we create a new server and listen for all incoming requests through the http.ListenAndServe function, and match the corresponding processor for the request by passing the ServeMux we just created.

Then visit http://localhost:3000/foo in the browser and you should find that the request has been redirected successfully.

You should notice something interesting: ListenAndServer's function signature is ListenAndServe (addr string, handler Handler), but the second argument we pass is a ServeMux.

We can do this because ServeMux also has a ServeHTTP method, so it is also a legitimate Handler.

For me, using ServerMux as a special Handler is a simplification. Instead of outputting the response itself, it passes the request to other Handler registered with it. This doesn't sound like an obvious leap at first glance-but chaining Handler together is a very common use in Go.

Custom processor (Custom Handlers)

The real point is that we have an object (in this case a timerHandler structure, but it can also be a string, a function, or anything) on which we implement a ServeHTTP (http.ResponseWriter, * http.Request) signature method, which is all we need to create a processor.

Package mainimport ("log"net/http"time") type timeHandler struct {format string} func (th * timeHandler) ServeHTTP (w http.ResponseWriter R * http.Request) {tm: = time.Now () .Format (th.format) w.Write ([] byte ("The time is:" + tm))} func main () {mux: = http.NewServeMux () rh: = http.RedirectHandler ("http://www.baidu.com", 307) th: = & timeHandler {format: time.RFC1123} mux.Handle (" / a ") Rh) mux.Handle ("/ time", th) log.Println ("Listening.") Http.ListenAndServe (": 3000", mux)} uses a function as a processor

Http.HandlerFunc () can use a regular function as a Handler interface condition

Func timeHandler (w http.ResponseWriter, r * http.Request) {tm: = time.Now () .Format (time.RFC1123) w.Write ([] byte ("the time is:" + tm))} func main () {mux: = http.NewServeMux () rh: = http.RedirectHandler ("http://www.baidu.com", 307) th: = http.HandlerFunc (timeHandler) mux.Handle (" / a ") Rh) mux.Handle ("/ time", th) log.Println ("Listening.") Http.ListenAndServe (": 3000", mux)}

A more convenient way: ServerMux.HandlerFunc method

Func main () {mux: = http.NewServeMux () mux.HandleFunc ("/ time", timeHandler) log.Println ("Listening...") Http.ListenAndServe (": 3000", mux)}

If parameters are required in the method, you need to use a closure to bring the variable into:

/ / demo1 func timeHandler (format string) http.Handler {fn:=func (w http.ResponseWriter,r * http.Request) {tm:=time.Now () .Format (format) w.Write ([] byte ("The time is:" + tm))} return http.HandlerFunc (fn)} / / demo2 func timeHandler (format string) http.Handler {return http.HandlerFunc (func (w http.ResponseWriter) R * http.Request) {tm: = time.Now () .Format (format) w.Write ([] byte ("The time is:" + tm))})} / / demo3func timeHandler (format string) http.HandlerFunc {return func (w http.ResponseWriter) R * http.Request) {tm: = time.Now () .Format (format) w.Write ([] byte ("The time is:" + tm))}} more convenient DefaultServeMux

The net/http package provides a set of shortcuts to work with DefaultServeMux:http.Handle and http.HandleFunc. These functions are the same as the functions with similar names we've seen before, except that they register the processor with DefaultServerMux, whereas we previously registered with the ServeMux we created.

In addition, ListenAndServe uses DefaultServeMux internally when no other processor is provided (that is, the second parameter is set to nil).

So, as a final step, we use DefaultServeMux to rewrite our timeHandler application:

Func timeHandler (format string) http.Handler {fn: = func (w http.ResponseWriter) R * http.Request) {tm: = time.Now () .Format (format) w.Write ([] byte ("The time is:" + tm))} return http.HandlerFunc (fn)} func main () {/ * mux: = http.NewServeMux () rh: = http.RedirectHandler ("http://www.baidu.com", Th: = timeHandler (time.RFC1123) mux.Handle ("/ a", rh) mux.Handle ("/ time", th) log.Println ("Listening.") Http.ListenAndServe (": 3000" mux) * / var format string = time.RFC1123 th: = timeHandler (format) http.Handle ("/ time", th) log.Println ("listening....") This is the end of http.ListenAndServe (": 3000", nil)} "detailed introduction to Golang net/http knowledge". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report