How to restrict web server written in golang to allow a particular address instead of a pattern?

廉价感情. 提交于 2019-12-20 03:17:38

问题


When I use

http.HandleFunc("/", serveRest)  //serveRest is the method to handle request
http.ListenAndServe("localhost:4000", nil)

It will accept all request starting with "/". How do I restrict it to serve only "localhost:4000" instead of every address like "localhost:4000/*"?

And can you guys suggest me a good tutorial for Go?


回答1:


The URL pattern to which you register your handlers is documented in the http.ServeMux type:

Patterns name fixed, rooted paths, like "/favicon.ico", or rooted subtrees, like "/images/" (note the trailing slash). Longer patterns take precedence over shorter ones, so that if there are handlers registered for both "/images/" and "/images/thumbnails/", the latter handler will be called for paths beginning "/images/thumbnails/" and the former will receive requests for any other paths in the "/images/" subtree.

Note that since a pattern ending in a slash names a rooted subtree, the pattern "/" matches all paths not matched by other registered patterns, not just the URL with Path == "/".

So unfortunately there is no pattern which matches only the root ("/").

But you can easily check this in your handler, and do whatever you want to if the request path is not the root:

func serveRest(w http.ResponseWriter, r *http.Request) {
    if r.URL.Path != "/" {
        w.Write([]byte("Not root!"))
        return
    }

    w.Write([]byte("Hi, this is the root!"))
}

If you want to return HTTP 404 Not found error for non-roots:

func serveRest(w http.ResponseWriter, r *http.Request) {
    if r.URL.Path != "/" {
        http.NotFound(w, r)
        return
    }

    w.Write([]byte("Hi!"))
}

And Go tutorial: https://tour.golang.org/

Also check out the Go tag info here on SO, it has a section Go Tutorials.




回答2:


You could check out https://github.com/julienschmidt/httprouter

Per its readme:

Only explicit matches: With other routers, like http.ServeMux, a requested URL path could match multiple patterns. Therefore they have some awkward pattern priority rules, like longest match or first registered, first matched. By design of this router, a request can only match exactly one or no route. As a result, there are also no unintended matches, which makes it great for SEO and improves the user experience.

Here is some good video content to get started in Go.



来源:https://stackoverflow.com/questions/31877296/how-to-restrict-web-server-written-in-golang-to-allow-a-particular-address-inste

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!