How to concatenate HTTP handlers in Go

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed. Hello, today I would like to share, in the ' Go ' language in series HTTP processor. Before using go, I used Nodejs + [EXPRESSJS] (http://expressjs.com/en/4x/api.html) to write an HTTP server application. This framework provides a very simple way to use middleware and concatenate many routing nodes, so you do not have to specify a full routing path to add handlers for it. [Figure 1] (https://raw.githubusercontent.com/studygolang/gctt-images/master/chain-http-hanlders/1.png) The idea is to split your route and process each part, concatenation to the processor, and each handler is only responsible for a portion. It's very simple to understand and very easy to use and maintain, so first I try to do something similar in Go. Out of the box, Go provides a great [http] (HTTPS://GOLANG.ORG/PKG/NET/HTTP) package that contains many different tools and, of course, [' Listenandserve '] (https://golang.org /pkg/net/http/#ListenAndServe) method, which initiates an HTTP server on a given port and passes the [' Handler '] (https://golang.org/pkg/net/http/#Handler To deal with it, what is this [' Handler '] (https://golang.org/pkg/net/http/#Handler)? "' Gotype Handler Interface {servehttp (responsewriter,*request)} ' [' Handler '] (https://golang.org/pkg/net/http/# Handler) is an interface that has a method-servehttp to process incoming requests and output responses. But what if we want to define a handler for each root route, such as/api/,/home,/about, and so on? [' Servemux '] (https://golang.org/pkg/net/http/#ServeMux)-An HTTP request multiplexer that can help you deal with this point. Use [' Servemux '] (https://golang.org/pkg/net/http/#ServeMux), we can specify the processor method to service any given route, but the problem is that we cannot do any nested [' Servemux '] (https://golang.org/pkg/net/ http/#ServeMux). The example in the document: "' Gomux: = http. Newservemux () Mux. Handle ("/api/", apihandler{}) mux. Handlefunc ("/", Func (w http.) Responsewriter, req *http. Request) {//the '/' pattern matches everything, so we need-check//that we ' re at the root here.if req. Url. Path! = "/" {http. NotFound (W, req) return}fmt. fprintf (W, "Welcome to the Home page!")}) "We can see that in this example a processor was customized for the '/api/' route and a processing method was defined for the root route. Therefore any route that begins with '/api/* ' will use the Apihandler processor method. But if we need to concatenate a usershandler to Apihandler, without any brainstorming or coding, we can't do that. For this I wrote a small library-[Gosplitter] (Https://github.com/goncharovnikita/gosplitter), which only provides a common method of ' Match (URL string, Mux *http. Servemux, http. Handler|http. handlerfunc|interface{}) '-he matches the given route part and processor, processing method or any structure you given! Let's take a look at an example: "go/** * defines a processor type */type apiv1handler struct {mux *http. Servemux}type colorshandler struct {mux *http. servemux}/** * Start-bind parent to Child */func (a *apiv1handler) Start () {var ColorshandlER = colorshandler{mux:a.mux,}gosplitter. Match ("/ping", A.mux, A.handleping ()) Gosplitter. Match ("/colors", A.mux, Colorshandler) Colorshandler.start ()}func (c *colorshandler) Start () {gosplitter. Match ("/black", C.mux, C.handleblack ())}/** * Simple HTTP Processor Method */func (a *apiv1handler) handleping () func (w http). Responsewriter, R *http. Request) {return func (w http. Responsewriter, R *http. Request) {W.write ([]byte ("Pong"))}}func (c *colorshandler) Handleblack () func (w http. Responsewriter, R *http. Request) {return func (w http. Responsewriter, R *http. Request) {W.write ([]byte ("#000000"))}}func main () {var mux = http. Newservemux () var apiV1 = Apiv1handler{mux:mux,}/** * Binds the API processor to the root directory */Gosplitter. Match ("/api/v1", Mux, apiV1)/** * Start API Processing */Apiv1.start ()} "" For example: "go/** * defines processor type */type apiv1handler struct {mux *h Ttp. Servemux}type colorshandler struct {mux *http. Servemux} ' ' Here we define a processor, it is a struct ' go/** * Start-Bind API processor to root directory */func (a *apiv1handler) Start () {var colorshandler = C Olorshandler{Mux:a.mux,}gosplitter. Match ("/ping", A.mux, A.handleping ()) Gosplitter. Match ("/colors", A.mux, Colorshandler) Colorshandler.start ()}func (c *colorshandler) Start () {gosplitter. Match ("/black", C.mux, C.handleblack ())} ' Add a ' Start ' method to our processor program, go to activate processing method ' go/** * Simple HTTP Processor Method */func (A * Apiv1handler) handleping () func (w http. Responsewriter, R *http. Request) {return func (w http. Responsewriter, R *http. Request) {W.write ([]byte ("Pong"))}}func (c *colorshandler) Handleblack () func (w http. Responsewriter, R *http. Request) {return func (w http. Responsewriter, R *http. Request) {W.write ([]byte ("#000000")}} "" Adds ' handleping ' and ' handleblack ' to our ' apiv1handler ', which responds to ' Pong ' and ' #000000 ' Gofunc Main () {var mux = http. Newservemux () var apiV1 = apiv1handler{mux:mux,}/** * Binds the API processor to the root route */gosplitter. Match ("/api/v1", Mux, apiV1)/** * Start API Processor */apiv1.start ()} "" We created a new ' Servemux ' in the ' main ' method and then created an instance of ' Apiv1handler ' , bind it to the '/api/v1 ' route, and then start it. So after all these simple operations we have two routes in work: '/api/v1/ping ' and '/api/v1/cOlors/black ', will respond to ' pong ' and ' #000000 '. Isn't it easy to use? I think so, now use this library in my project for easy routing and concatenation of processors:) <!--Thanks for reading! Any suggestions and critiques is welcome! -Thank you for reading, and you are welcome to make any suggestions and criticisms!

via:https://medium.com/@cashalot/how-to-chain-http-handlers-in-go-33c96396b397

Author: Nikita Translator: Marlonfan proofreading: Rxcai

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

503 Reads
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.