Go语言 如何覆盖默认的404 not found处理程序?

xuo3flqw  于 2024-01-04  发布在  Go
关注(0)|答案(2)|浏览(102)

给定此示例代码

package main

import "net/http"

func main() {
    api := http.NewServeMux()

    api.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusOK)
    })

    // other routes go here

    err := http.ListenAndServe(":8080", api)

    // handle err here
}

字符串
当调用一个不存在的路由时,我会收到一条404消息
404 page not found
我想自定义它,所以我在**调用ListenAndServe之前添加了以下内容

api.HandleFunc("*", func(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusNotFound)
    w.Write([]byte("error message goes here"))
})


不幸的是,这不起作用,行为和以前一样。如果消费者调用一个不存在的路由,我如何用一个定制的not found处理程序响应?

bejyjqdl

bejyjqdl1#

您需要添加一个中间件来检查已注册的路由,如果路由未注册,它可以从那里返回。

package main

import (
    "net/http"
)

func routeExistMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // Check if the route exists
        if !routeExists(r.URL.Path) {
            http.NotFound(w, r)
            return
        }

        // Call the next handler in the chain
        next.ServeHTTP(w, r)
    })
}

// Dummy function to check if the route exists
func routeExists(path string) bool {
    // Implement your logic here to check if the route exists
    // For simplicity, this example always returns true
    return true
}

func main() {
    // Create a new mux (router)
    mux := http.NewServeMux()

    // Use the routeExistMiddleware for all routes
    mux.Handle("/", routeExistMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Hello, World!"))
    })))

    // Start the server
    http.ListenAndServe(":8080", mux)
}

字符串
此外,我更喜欢使用gofr,它默认情况下会完成所有这些任务。

eulz3vhy

eulz3vhy2#

"/"下注册你的404处理程序。"/"是可能的最不特定的模式,也匹配每个请求,所以当且仅当没有其他处理程序匹配该请求时才调用它。

package main

import (
        "log"
        "net/http"
)

func main() {
        api := http.NewServeMux()

        api.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
                w.WriteHeader(http.StatusOK)
        })

        // other routes go here

        // catch all
        api.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
                w.WriteHeader(http.StatusNotFound)
                w.Write([]byte("error message goes here"))
        })

        err := http.ListenAndServe(":8080", api)
        log.Fatal(err)
}

个字符

相关问题