This is a creation in Article, where the information may have evolved or changed. > How to use Go to launch new WEB projects, use routing, middleware and let us encrypt authentication. Golang has a great self-service HTTP Server package, needless to say: Net/http, it's very simple, but it's very powerful. Defines the function that handles the route, and the port is 80. "' Gopackage mainimport (" io "" net/http ") func Main () {http. Handlefunc ("/", HelloWorldHandler) http. Listenandserve (":", nil)}func HelloWorldHandler (w http. Responsewriter, R *http. Request) {io. WriteString (W, "Hello world!")} "Good, but we can use a more powerful router, such as the Gorilla package: ' Gorilla/mux ' [Http://www.gorillatoolkit.org/pkg/mux] (HTTP/ WWW.GORILLATOOLKIT.ORG/PKG/MUX) It implements a request router and a scheduler. It allows you to create routes with named parameters, restrict HTTP verbs (i.e., limit to GET, POST, etc.) and host or domain management. [img] (https://raw.githubusercontent.com/studygolang/gctt-images/master/Golang-HTTP-server-for-pro/ Gorilla-routing-in-action.gif) Gorilla Routing in action! Gorilla route in Action! Simple configuration makes it easy to manage more routes in the previous example using Gorilla, allowing us to easily manage multiple routes with simple configuration: ' Gofunc main () {r: = Mux. Newrouter () R.handlefunc ("/products/{key}", Producthandler) R.handlefunc ("/articles/{category}/", Articlescategoryhandler) R.handlefunc ("/articles/{category}/{id:[0-9]+}", ArticlehandLER) http. Handle ("/", R)} ' # # # use ' Alice ' to manage our middleware if you use a Web server package, [middleware mode] (Https://en.wikipedia.org/wiki/Middleware) is very common. If you haven't seen it yet, you should watch the Mat Ryer video on the 201 5 Golang UK Conference to learn about the power of the middleware. ([Full blog post here] (https://medium.com/@matryer/ writing-middleware-in-golang-and-how-go-makes-it-so-much-fun-4375c1246e81)) video link: https://youtu.be/ Tim8uksf6ra another article about the middleware model [Http://www.alexedwards.net/blog/making-and-using-middleware] (HTTP/ Www.alexedwards.net/blog/making-and-using-middleware) as described by the author ([Github] (https://github.com/justinas/alice)):> ' Alice ' provides a convenient way to link your HTTP middleware features and application handlers. Simply put, it converts ' GoMiddleware1 (Middleware2 (App)) ' to ' Goalice '. New (Middleware1, Middleware2, Middleware3). Then (APP) "Our first example, plus ' Alice ' after:" ' Gofunc main () {errorchain: = Alice. New (Loggerhandler, recoverhandler) r: = Mux. Newrouter () R.handlefunc ("/products/{key}", Producthandler) R.handlefunc ("/articles/{category}/", Articlescategoryhandler) R.handlefunc ("/articles/{category}/{id:[0-9]+}", Articlehandler) http. Handle ("/", Errorchain.then (R)}" you can concatenate many ' handler ', as described below two: "' Gofunc loggerhandler (H http. Handler) http. Handler {return HTTP. Handlerfunc (Func (w http. Responsewriter, R *http. Request) {Start: = time. Now () H.servehttp (W, R) log. Printf ("<<%s%s%v", R.method, R.url. Path, time. Since (Start)})} ' ' Loggerhandler ' and ' recoverhandler ': ' Gofunc recoverhandler (next http. Handler) http. Handler {fn: = func (w http). Responsewriter, R *http. Request) {defer func () {if err: = Recover (); Err! = nil {log. Printf ("Panic:%+v", err) http. Error (W, http. StatusText (+)}} () next. Servehttp (W, R)}return http. Handlerfunc (FN)} ' Now we have an HTTP server with a powerful routing packet. You can also easily manage your middleware to quickly extend the functionality of your application. [img] (https://raw.githubusercontent.com/studygolang/gctt-images/master/Golang-HTTP-server-for-pro/ Midlleware-everywhere-with-alice.gif) Alice makes middleware everywhere! # # HTTP Server good, but HTTPS server better! Use the ' Let's Encrypt ' service to create a secure HTTP server simply and quickly. ' Let's Encrypt ' uses [Acme Protocol] (Https://en.wikipedia.org/wiki/Automated_Certificate_Management_Environment) To verify whether you control theThe domain name and issue a certificate to you. This is called certification, yes, there is an automatic authentication package: [Acme/autocert] (Https://godoc.org/golang.org/x/crypto/acme/autocert) ' Gom: = Autocert. Manager{prompt:autocert. Accepttos,hostpolicy:autocert. Hostwhitelist ("Www.checknu.de"), Cache:autocert. Dircache ("/home/letsencrypt/"),} ' ' uses ' TLS ' to create ' http.server ': ' Goserver: = &http. SERVER{ADDR: ": 443", Tlsconfig: &tls. Config{getcertificate:m.getcertificate,},}err: = Server. Listenandservetls ("", "") if err! = Nil {log. Fatal ("Listenandserve:", err)} '! [img] (https://raw.githubusercontent.com/studygolang/gctt-images/master/Golang-HTTP-server-for-pro/And-now-its-done.png) finished!
via:https://medium.com/@ScullWM/golang-http-server-for-pro-69034c276355
Author: Thomas P Translator: Wentingrohwer proofreading: polaris1119
This article by GCTT original compilation, go language Chinese network honor launches
This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove
348 Reads