Golang Web Server Custom Routing

Source: Internet
Author: User
Tags key string
This is a creation in Article, where the information may have evolved or changed.

What's wasting today is tomorrow to those who died yesterday; What's the future of hate now?

What you are wasting today is the tomorrow that the man who died yesterday expects, and what you dislike is now the future you will never go back to.

Recently, the company has a project is not large, but the flow is expected to be small, assigned to me, the demand for fast online, because I study golang two months (I dull), coupled with the obsession with Golang, consider secretly (in fact, the project director was persuaded by me) to use go to write Web services. See this I can only say, nonsense light what!!

Serving:

first, the precondition of custom routing is to implement Servehttp method of routing object.

Custom route notation One:

1. Routing Structure Body object definition

type Router struct {Route map[string]map[string]http.HandlerFunc}

The type of the route attribute is map, where a one-dimensional key string represents a request method such as post, get, and so on. Two-dimensional key string representation

The URL address to match, HTTP. Handlerfunc is of course the specific way to handle URL requests.

2. URL routing Table initialization

// 路由表初始化func (r *Router) HandleFunc(method, path string, f http.HandlerFunc) {method = strings.ToUpper(method)if r.Route == nil {r.Route = make(map[string]map[string]http.HandlerFunc)}if r.Route[method] == nil {r.Route[method] = make(map[string]http.HandlerFunc)}r.Route[method][path] = f}

Of course, first of all to initialize the map, there are a few to initialize a few, otherwise it will error OH. After initialization, the caller can use the

route.HandleFunc("GET", "/", HomeHandler)

This method initializes the routing table.

3. Implement routing Core processing Servehttp method

func (r *Router) ServeHTTP(res http.ResponseWriter, req *http.Request) {// 此处我做个很多关于http请求header的限制,一级业务版本处理,就不公布出来了    // ....// 正常路由if f, ok := r.Route[req.Method][req.URL.Path]; ok {f(res, req)//静态文件路由} else if strings.HasPrefix(req.URL.String(), staticHttpPath){staticFile := http.StripPrefix(staticHttpPath, http.FileServer(http.Dir(staticDirPath)))staticFile.ServeHTTP(res, req)// 404友好处理}else {// 由于此项目目的是提供接口和WEB HTML服务,所以此处本人做了一系列的url处理}}

In addition I also based on the business to do some of the Web server friendly call processing, such as turn off the header detection, service offline online processing and so on. If your dear "code Friends" There are other good suggestions, please enlighten. ^_^

Custom Routing Two:

This syntax is similar to MVC

1. Defining the controller structure body object

type UrlHandlerController struct {Function func(http.ResponseWriter, *http.Request)Method   stringPattern  string}

Pattern is the URL address to match.

2. Defining a Routing Object

var mux []UrlHandlerController

The caller is called to initialize the routing table in this way, using MUX = Append (Mnx, urlhandlercontroller{xxxfunc, "POST", "/index"}).

3. Defining a Routing Object

type httpHandler struct{}

4. Implementing Routing Core Logic

func (*httpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {    // 当然无法避免的Header头处理检测// t := time.Now()    // 此处有一个不好的写法就是 UrlHandlerController变量最好不要跟已存在的类型重名,否则........for _, UrlHandlerController := range mux {if m, _ := regexp.MatchString(UrlHandlerController.Pattern, r.URL.Path); m {if r.Method == UrlHandlerController.Method {UrlHandlerController.Function(w, r)// 做一些日志等的处理return}}}    // 此处做需要根据项目做一个具体的优化处理:个人建议io.WriteString(w, "")return}

In fact, the core processing is simply to find the routing address, found on the request to change the address of the processing method.

If the code friends have good suggestions, please leave your traces

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.