doukeng7426 2015-08-07 12:03
浏览 40

如何限制用golang编写的Web服务器允许使用特定地址而不是模式?

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?

  • 写回答

2条回答 默认 最新

  • douzhang3898 2015-08-07 12:14
    关注

    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 <kbd>Go</kbd> tag info here on SO, it has a section Go Tutorials.

    评论

报告相同问题?

悬赏问题

  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思