使用 Go 自定义 404 错误消息

Tyl*_*ler 1 http go http-status-code-404

我有这个代码,如果我去 /time/ 会给出我的自定义 404 错误消息,但如果我去 /times/ 或只是 / 或 /whatever 然后我会得到默认的 404 错误消息。我想为除 /time/ 以外的所有情况显示我的自定义 404

package main

import (
        "fmt"
        "time"
        "flag"
        "os"
        "net/http"
        )

const AppVersion = "timeserver version: 3.0"

func timeserver(w http.ResponseWriter, r *http.Request) {
    if r.URL.Path != "/time/" {
        NotFoundHandler(w, r)
        return
    }

    const layout = "3:04:05 PM"
    t := time.Now().Local()
    fmt.Fprint(w, "<html>\n")
    fmt.Fprint(w, "<head>\n")
    fmt.Fprint(w, "<style>\n")
    fmt.Fprint(w, "p {font-size: xx-large}\n")
    fmt.Fprint(w, "span.time {color: red}\n")
    fmt.Fprint(w, "</style>\n")
    fmt.Fprint(w, "</head>\n")
    fmt.Fprint(w, "<body>\n")
    //fmt.Fprint(w, "The time is now " + t.Format(layout))
    fmt.Fprint(w, "<p>The time is now <span class=\"time\">" + t.Format(layout) + "</span>.</p>\n")
    fmt.Fprint(w, "</body>\n")
    fmt.Fprint(w, "</html>\n")
}

func NotFoundHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "custom 404")
}

func main() {
    version := flag.Bool("V", false, "prints current version")
    port := flag.String("port", "8080", "sets service port number")

    flag.Parse()
    if *version {
      fmt.Println(AppVersion)
      os.Exit(0)
    }

    http.HandleFunc("/time/", timeserver)
    http.ListenAndServe("localhost:" + *port, nil)
}
Run Code Online (Sandbox Code Playgroud)

Cer*_*món 6

将此行添加到主:

http.HandleFunc("/", NotFoundHandler)
Run Code Online (Sandbox Code Playgroud)

"/" 的处理程序是 catchall 处理程序。

此外,您应该修改处理程序以返回 404 状态:

func NotFoundHandler(w http.ResponseWriter, r *http.Request) {
   w.WriteHeader(http.StatusNotFound)
   fmt.Fprint(w, "custom 404")
}
Run Code Online (Sandbox Code Playgroud)