douweiluo0600 2018-03-29 15:18
浏览 62
已采纳

使用JulienSchmidt httprouter服务favicon.ico

I can get favicon.icon with the standard net/http package but am having trouble with julienschmidt/httprouter. This is what I'm trying and am receiving a 404 error for the favicon.ico file.

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条回答 默认 最新

  • dsjklb0205 2018-03-29 16:56
    关注

    I was able to solve the problem by removing the leading slash from stuff/images/favicon.ico. Thanks @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")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

    报告相同问题?

    悬赏问题

    • ¥15 grafna发送告警信息
    • ¥15 51单片机,LCD屏幕内容修改
    • ¥20 Ida Pro动态调试
    • ¥15 TensorFlow深度学习拓展项目
    • ¥20 springboot博客系统
    • ¥15 MICE包多重插补后数据集汇总导出
    • ¥15 一道算法分析问题(关于3-MSAT)
    • ¥15 C++ FLUENT 化学反应速率 编写困难
    • ¥15 Python嵌套交叉验证
    • ¥15 linuxkit+elasticsearch