2

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")
}
Sebastian
  • 1,623
  • 19
  • 23
  • Related / possible duplicate of [Serve static content on root and rest on /api](https://stackoverflow.com/questions/48259630/serve-static-content-on-root-and-rest-on-api/48260135#48260135). – icza Mar 29 '18 at 15:20
  • Does the order matter? What happens when you add the root path handler last? Does /logout work as expected? – Peter Mar 29 '18 at 16:39
  • 1
    Ah. I highly doubt that you have a file called "/stuff/images/favicon.ico" in your filesystem. You probably want to remove the leading slash to make the name relative. – Peter Mar 29 '18 at 16:44

1 Answers1

1

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")
}
Sebastian
  • 1,623
  • 19
  • 23