为什么每个 URL 请求都会返回这个内容?

huangapple go评论81阅读模式
英文:

Why does this get served on every URL request?

问题

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)
}

如果我访问 `/foo`将会运行 `bar` 函数

如果我访问 `/` 或者 `/any/other/path`将会运行 `home` 函数

你有什么想法为什么会这样如何处理 404 错误
英文:
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?

答案1

得分: 3

这是一种设计行为 - 以“/”结尾的路径的处理程序也将处理任何子路径。

请注意,由于以斜杠结尾的模式表示根子树,模式“/”匹配所有未被其他注册模式匹配的路径,而不仅仅是路径为“/”的URL。

你需要为404错误实现自己的逻辑。考虑以下来自golang文档的示例:

mux := http.NewServeMux()
mux.Handle("/api/", apiHandler{})
mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
    // “/”模式匹配所有内容,因此我们需要在这里检查是否在根路径。
    if req.URL.Path != "/" {
        http.NotFound(w, req)
        return
    }
    fmt.Fprintf(w, "欢迎访问首页!")
})

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

英文:

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

答案2

得分: 2

你需要在 home 中处理自己的 404 错误。

英文:

You have to handle your own 404s in home.

huangapple
  • 本文由 发表于 2014年9月11日 05:14:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/25775213.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定