doujia5863
2017-04-25 14:20
浏览 217
已采纳

使用golang和mux制作自定义404

Here is my code about a little example webserver with golang and mux :

package main

import (
"fmt"
"net/http"
    "github.com/gorilla/mux"
)

func handler(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
fmt.Fprintf(w, "Hi there, I love %s!", vars["username"])
}

func homeHandler(w http.ResponseWriter, r *http.Request) {
    if r.URL.Path != "/" {
        errorHandler(w, r, http.StatusNotFound)
        return
    }
    vars := mux.Vars(r)
    fmt.Fprintf(w, "Hi there, I love %s!", vars["username"])
}

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/help/{username}/", handler)
    http.Handle("/", r)
    http.ListenAndServe(":8080", nil)
}

But I don't find a way on how to do a custom 404 page, i would like to make a custom 404.

But I can't make a r.HandleFunc("/",...) but it will be too greedy.

If anyone have any idea.

图片转代码服务由CSDN问答提供 功能建议

这是我的有关带golang和mux的小示例网络服务器的代码:

 包main 
 
import(
“ fmt” 
“ net / http” 
“ github.com/gorilla/mux"
)

func处理程序(带有http.ResponseWriter,r *  http.Request){
 vars:= mux.Vars(r)
fmt.Fprintf(w,“嗨,我爱%s!”,vars [“ username”])
} 
 
func homeHandler(  w http.ResponseWriter,r * http.Request){
,如果r.URL.Path!=“ /” {
 errorHandler(w,r,http.StatusNotFound)
 return 
} 
 vars:= mux  .vars(r)
 fmt.Fprintf(w,“嗨,我爱%s!”,vars [“ username”])
} 
 
func main(){
r:= mux.NewRouter(  )
 r.HandleFunc(“ / help / {username} /”,handler)
 http.Handle(“ /”,r)
 http.ListenAndServe(“:8080”,nil)
} 
 <  / code>  
 
 

但是我找不到如何做自定义404页面的方法,我想制作一个自定义404。

但是我无法创建r.HandleFunc(“ /”,...),但是它太贪婪了。

如果有人有任何想法。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongpian2559 2017-04-25 14:26
    已采纳

    The Router exports a NotFoundHandler field which you can set to your custom handler.

    r := mux.NewRouter()
    r.NotFoundHandler = MyCustom404Handler
    
    打赏 评论
  • doucheng1884 2017-04-25 14:25

    Set the NotFoundHandler to a handler method that returns your custom 404 page.

    打赏 评论
  • doudui9516 2019-07-08 14:54

    Sometimes, you spend a lot of time building a stack of middleware that does many things like logging, sending metrics and so... And the default 404 handler just skips all the middlewares.

    I was able to solve this issue by re-setting the default 404 handler like this:

    router := mux.NewRouter()
    router.Use(someMiddleware())
    // Re-define the default NotFound handler
    router.NotFoundHandler = router.NewRoute().HandlerFunc(http.NotFound).GetHandler()
    

    Now, the 404 default handler is also going thru all the middlewares.

    打赏 评论

相关推荐 更多相似问题