dpt62283 2015-01-12 23:15
浏览 88
已采纳

Go的自定义404错误消息

I have this code that will give my custom 404 error message if I go to /time/ but if I go to /times/ or just / or /whatever then I will get the default 404 error message. I want to show my custom 404 for all cases other than /time/

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>
")
    fmt.Fprint(w, "<head>
")
    fmt.Fprint(w, "<style>
")
    fmt.Fprint(w, "p {font-size: xx-large}
")
    fmt.Fprint(w, "span.time {color: red}
")
    fmt.Fprint(w, "</style>
")
    fmt.Fprint(w, "</head>
")
    fmt.Fprint(w, "<body>
")
    //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>
")
    fmt.Fprint(w, "</body>
")
    fmt.Fprint(w, "</html>
")
}

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)
}
  • 写回答

1条回答 默认 最新

  • doumisha5081 2015-01-12 23:45
    关注

    Add this line to main:

    http.HandleFunc("/", NotFoundHandler)
    

    The handler for "/" is the catchall handler.

    Also, you should modify the handler to return a 404 status:

    func NotFoundHandler(w http.ResponseWriter, r *http.Request) {
       w.WriteHeader(http.StatusNotFound)
       fmt.Fprint(w, "custom 404")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 易康econgnition精度验证
  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致