In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces golang to build HTTP service implementation steps, the content is very detailed, interested friends can refer to, hope to be helpful to you.
Reference:
The simplest Http server program for go
Package main import ("fmt"net/http") func IndexHandler (w http.ResponseWriter, r * http.Request) {fmt.Fprintln (w, "hello world")} func main () {http.HandleFunc ("/", IndexHandler) http.ListenAndServe ("127.0.0.0 IndexHandler 8000", nil)} HTTP
Apart from the details, understand that the web application built by HTTP only needs to focus on two sides-- the client (client) and the server (server). The interaction between the two sides comes from the request of client and the response on the server side. The so-called http server mainly lies in how to accept the request of client and return response to client.
In the process of receiving request, the most important thing is router, that is, the implementation of a Multiplexer. You can either use the built-in mutilplexer--DefaultServeMux or customize it in Go. The purpose of Multiplexer routing is to find the processor function (hander), which processes the request while building the response.
The simple summary is this process:
Therefore, the most important thing to understand http services in go is to understand the ServerMux-based structure of Multiplexer in Multiplexer and hander,Golang, while also implementing the Handler interface.
Hander function: a function with func (w http.ResponseWriter, r * http.Requests) signature
Handler processor (function): the handler function wrapped by the HanderFunc structure, which implements the function of the ServeHTTP interface method. When the ServeHTTP method of the handler processor is called, the handler function itself is called.
Handler object: implements the structure of the ServeHTTP method of the Hander interface.
The http processing flow of Golang can be represented by the following figure, which is explained later:
Handler
Golang does not inherit, and polymorphic-like methods can be implemented through interfaces. The so-called interface is that the definition declares the function signature. As long as any structure implements the same method as the interface function signature, it is equivalent to implementing the interface. Go's http services are all processed based on handler.
Type Handler interface {ServeHTTP (ResponseWriter, * Request)}
Any structure that implements the ServeHTTP method can be called a handler object. ServeMux uses handler and calls its ServeHTTP method to process the request and return the response.
ServeMux
After you learn about Handler, take a look at ServeMux. The ServeMux source code is simple:
Type ServeMux struct {mu sync.RWMutex m map[string] muxEntry hosts bool} type muxEntry struct {explicit bool h Handler pattern string}
The most important field in the ServeMux structure is m, which is an map,key is some url schema, and value is a muxEntry structure, which defines and stores specific url schemas and handler.
Of course, the so-called ServeMux also implements the ServeHTTP interface, which is also a handler, but ServeMux's ServeHTTP method is not used to deal with request and respone, but to find the route registration handler.
Server
In addition to ServeMux and Handler, there is another structure that Server needs to know. As you can see from the source code of http.ListenAndServe, it creates a server object and calls the ListenAndServe method of the server object:
Func ListenAndServe (addr string, handler Handler) error {server: = & Server {Addr: addr, Handler: handler} return server.ListenAndServe ()}
The structure of the server is as follows:
Type Server struct {Addr string Handler Handler ReadTimeout time.Duration WriteTimeout time.Duration TLSConfig * tls.Config MaxHeaderBytes int TLSNextProto map [string] func (* Server, * tls.Conn, Handler) ConnState func (net.Conn, ConnState) ErrorLog * log.Logger disableKeepAlives int32 nextProtoOnce sync.Once nextProtoErr error}
The server structure stores the fields that are common for the server to process requests. The Handler field also retains the Hander interface. If the Server interface does not provide a Handler structure object, then DefaultServeMux is used as the Multiplexer.
Create a HTTP service
To create a http service, you need to go through two processes: first, you need to register the route, that is, you need to provide a mapping between the url schema and the handler function, and the second is to instantiate a server object and turn on listening to the client.
Http.HandleFunc ("/", indexHandler) http.ListenAndServe ("127.0.0.1 http.ListenAndServe 8000", nil) or: server: = & Server {Addr: addr, Handler: handler} server.ListenAndServe () http registered route
The api of the registered route exposed by the net/http packet is simple, and http.HandleFunc chooses DefaultServeMux as the multiplexer:
Func HandleFunc (pattern string, handler func (ResponseWriter, * Request)) {DefaultServeMux.HandleFunc (pattern, handler)}
In fact, DefaultServeMux is an instance of ServeMux. Of course, the http package also provides the NewServeMux method to create an ServeMux instance. By default, create a DefaultServeMux:
/ / NewServeMux allocates and returns a new ServeMux.func NewServeMux () * ServeMux {return new (ServeMux)} / / DefaultServeMux is the defaultServeMux used by Serve.var DefaultServeMux = & defaultServeMux var defaultServeMux ServeMux
Note that go can also use pointers in the process of creating instances, that is,
Type Server struct {} server: = Server {}
You can create an instance of Server as follows
Var DefaultServer Server var server = & DefalutServer
So the HandleFunc (pattern,handler) method of DefaultServeMux is actually defined under ServeMux:
Func (mux * ServeMux) HandleFunc (pattern string, handler func (ResponseWriter, * Request)) {mux.Handle (pattern, HandlerFunc (handler))}
In the above code, HandlerFunc is a function type. At the same time, the ServeHTTP method of Handler interface is realized. The purpose of wrapping the route-defined indexHandler function with the HandlerFunc type is to make this function also implement the ServeHTTP method, which is transformed into a handler handler (function).
Type HandlerFunc func (ResponseWriter, * Request) func (f HandlerFunc) ServeHTTP (w ResponseWriter, r * Request) {f (w, r)}
Once this is done, it means that our indexHandler function also has a ServeHTTP method.
In addition, the Handle method of ServeMux will do a map mapping of the pattern and handler functions:
Func (mux * ServeMux) Handle (pattern string Handler Handler) {mux.mu.Lock () defer mux.mu.Unlock () if pattern = "" {panic ("http: invalid pattern" + pattern)} if handler = = nil {panic ("http: nil handler")} if mux.m [pattern]. Explicit {panic ("http: multiple registrations for" + pattern)} if mux.m = nil {mux. M = make (map [string] muxEntry)} mux.m [pattern] = muxEntry {explicit: true H: handler, pattern: pattern} if pattern [0]! ='/'{mux.hosts = true} n: = len (pattern) if n > 0 & & if [n-1] = ='/'& &! mux.m [pattern if pattern [0]] .explicit {path: = pattern if pattern [0]! ='/'{path = pattern [strings.Index (pattern) "/"):]} url: = & url.URL {Path: path} mux.m [n [0: n Mel 1]] = muxEntry {h: RedirectHandler (url.String (), StatusMovedPermanently), pattern: pattern}
Thus, the main purpose of the Handle function is to bind the handler and pattern schemas to the map of the map [string] muxEntry, where muxEntry holds more information about pattern and handler. The m field of Server is a map like map [string] muxEntry.
At this point, the route registration for pattern and handler is complete.
Turn on monitoring
After registering the route, you also need to turn on server listening to start the web service. In the ListenAndServer method of http, you can see that a Server object is created and the method of the same name of the Server object is called:
Func ListenAndServe (addr string, handler Handler) error {server: = & Server {Addr: addr, Handler: handler} return server.ListenAndServe ()} func (srv Server) ListenAndServe () error {addr: = srv.Addr if addr = = "{addr =": http "} ln, err: = net.Listen (" tcp ", addr) if err! = nil {return err} return srv.Serve (tcpKeepAliveListener {ln. (net.TCPListener)})}
In the ListenAndServer method of Server, the listening address Addr is initialized, and the Listen method is called to set listening. Finally, pass the listening TCP object into the Serve method:
Func (srv * Server) Serve (l net.Listener) error {defer l.Close ()... BaseCtx: = context.Background () ctx: = context.WithValue (baseCtx, ServerContextKey, srv) ctx = context.WithValue (ctx, LocalAddrContextKey, l.Addr ()) for {rw, e: = l.Accept ()... C: = srv.newConn (rw) c.setState (c.rwc, StateNew) / / before Serve can return go c.serve (ctx)}} process the request
After listening is enabled, once the client request reaches the end, go starts a co-program to process the request, and the main logic is in the server method.
The serve method is relatively long, and its main function is to create a context object, and then call the Accept method of Listener to get the connection data and use the newConn method to create the connection object. Finally, the goroutein protocol is used to process the connection request. Therefore, each connection opens a cooperative process, the context of the request is different, and at the same time ensures high concurrency of go. Serve is also a long way to go:
Func (c * conn) serve (ctx context.Context) {c.remoteAddr = c.rwc.RemoteAddr () .String () defer func () {if err: = recover (); err! = nil {const size = 64
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.