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

后端 未结 2 1977
南旧
南旧 2021-01-22 15:08

When I use

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

It will

相关标签:
2条回答
  • 2021-01-22 15:37

    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.

    0 讨论(0)
  • 2021-01-22 15:47

    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.

    0 讨论(0)
提交回复
热议问题