Search code examples
gogo-http

How to set Home page and static files in same path


if I run the URL http://localhost:8080/ I want to run the Index function and If I run http://localhost:8080/robot.txt it should show static folder files

func main() {
    http.HandleFunc("/", Index)
    http.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("static"))))
    http.ListenAndServe(":8080", nil)
}

func Index(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Index")
}

How to do this.

Currently, I'm getting this error

panic: http: multiple registrations for /

This is my directory structure

main.go
static\
  | robot.txt
  | favicon.ico
  | sitemap.xml

Solution

  • Delegate to the file server from the index handler:

    func main() {
        http.HandleFunc("/", Index)
        http.ListenAndServe(":8080", nil)
    }
    
    var fserve = http.StripPrefix("/", http.FileServer(http.Dir("static"))))
    
    func Index(w http.ResponseWriter, r *http.Request) {
        if r.URL.Path != “/“ {
            fserve.ServeHTTP(w, r)
            return
        }
        fmt.Fprintln(w, "Index")
    }