与JulienSchmidt的httprouter一起提供favicon.ico

时间:2018-03-29 15:18:44

标签: go

我可以使用标准的net/http软件包获取favicon.icon,但我遇到了julienschmidt/httprouter的问题。这就是我正在尝试并收到favicon.ico文件的404错误。

import (
    "github.com/julienschmidt/httprouter"
    "net/http"
    "log"
)

func main(){
    router := httprouter.New()
    router.GET("/", index)
    router.POST("/", login)
    router.GET("/logout", logout)
    router.GET("/favicon.ico", faviconHandler)
    router.ServeFiles("/stuff/*filepath", http.Dir("stuff"))
    log.Fatal(http.ListenAndServe(":8080", router))
}

func faviconHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
     http.ServeFile(w, r, "/stuff/images/favicon.ico")
}

1 个答案:

答案 0 :(得分:0)

我能够通过从stuff/images/favicon.ico删除前导斜杠来解决问题。谢谢@Peter。

import (
    "github.com/julienschmidt/httprouter"
    "net/http"
    "log"
)

func main(){
    router := httprouter.New()
    router.GET("/", index)
    router.POST("/", login)
    router.GET("/logout", logout)
    router.GET("/favicon.ico", faviconHandler)
    router.ServeFiles("/stuff/*filepath", http.Dir("stuff"))
    log.Fatal(http.ListenAndServe(":8080", router))
}

func faviconHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
     http.ServeFile(w, r, "stuff/images/favicon.ico")
}