2

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
Faizal Ahamed
  • 118
  • 1
  • 4
  • 7

1 Answers1

2

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")
}
Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242