Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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")
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading