doucheng7808 2014-09-10 21:14
浏览 39
已采纳

为什么在每个URL请求上都提供此服务?

package main

import "fmt"
import "net/http"

func home(w http.ResponseWriter, r *http.Request) {
  fmt.Fprintf(w, "What!")
}

func bar(w http.ResponseWriter, r *http.Request) {
  fmt.Fprintf(w, "Bar!")
}

func main() {
  http.HandleFunc("/", home)
  http.HandleFunc("/foo", bar)
  http.ListenAndServe(":5678", nil)
}

If I visit /foo, bar will run.

If I visit / or /any/other/path, home will run.

Any idea why this happens? How can I handle 404's?

  • 写回答

2条回答 默认 最新

  • dousonghs58612 2014-09-10 21:23
    关注

    This is a behaviour by design - handler defined for path ending with / will also handle any subpath.

    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 == "/".

    http://golang.org/pkg/net/http/#ServeMux

    You have to implement you own logic for 404. Consider the following example from the golang doc:

    mux := http.NewServeMux()
    mux.Handle("/api/", apiHandler{})
    mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
            // The "/" pattern matches everything, so we need to 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!")
    })
    

    http://golang.org/pkg/net/http/#ServeMux.Handle

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 如何将下列的“无限压缩存储器”设计出来
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口