带有静态文件的http.HandleFunc

I am building a webpage. The page should be able to handle the different http methods (GET, POST...). My page technically works and handles each type of request, but in the case of GET requests (serving index.html at the root "/" path), my page is not displaying properly. None of the images or css are displaying correctly, presumably because those files cannot be found.

Ugly page

I have noticed that http.Handle provides better results than http.HandleFunc when substituted into my server.go code below, in that the images and css do display correctly using:

http.FileServer(http.Dir("static"))
http.Handle("/", http.StripPrefix("/", fs))

The following is my web server with images and css not being displayed correctly. In general, my intent is to use static files for everything, including html (ex. index.html) and to implement some solution using nothing but standard go.

server.go code

package main

import (
  "net/http"
  "fmt"
)

func indexHandler(w http.ResponseWriter, r *http.Request) {
  w.Header().Add("Content Type", "text/html")
  switch r.Method {
    case "GET":
      http.ServeFile(w, r, "./static/index.html")
    case "POST":
      fmt.Pprintf(w, "POST!")
    case "PUT":
      fmt.Pprintf(w, "PUT!")
    case "DELETE":
      fmt.Pprintf(w, "DELETE!")
    default:
      fmt.Pprintf(w, "Default!")
  }
}

func main() {
  http.HandleFunc("/", indexHandler)
  http.ListenAndServe(":3000", nil)
}

You've hard-coded your server to always return index.html for any GET request, no matter what is being requested. So if your index.html includes a reference to style.css, the browser is going to make a second request for style.css and you'll return index.html again.

I assume what you're trying to do is have all GET requests return static files, while other verbs will do something else. You just need to pass those along to the file server:

root := "static"
...
case "GET":
    if r.URL.Path == "" || r.URL.Path == "/" {
        http.ServeFile(w, r, path.Join(root, "index.html"))
    } else {
        http.ServeFile(w, r, path.Join(root, r.URL.Path))
    }

Note that by the time your handler is called, all ".." references in the URL have been removed, attackers can't use this to escape your static tree. But ServeFile() will return directory listings, so you'll need to check for that if that's a problem.