How do you serve a static html file using a go web server?

后端 未结 4 423
难免孤独
难免孤独 2020-12-04 06:34

How do you serve index.html (or some other static HTML file) using a go web server?

I just want a basic, static HTML file (like an article, for example) which I can

4条回答
  •  温柔的废话
    2020-12-04 07:05

    I prefer using http.ServeFile for this over http.FileServer. I wanted directory browsing disabled, a proper 404 if files are missing and an easy way to special case the index file. This way, you can just drop the built binary into a folder and it will serve everything relative to that binary. Of course, you can use strings.Replace on p if you have the files stored in another directory.

    
    func main() {
        fmt.Println("Now Listening on 80")
        http.HandleFunc("/", serveFiles)
        log.Fatal(http.ListenAndServe(":80", nil))
    }
    
    func serveFiles(w http.ResponseWriter, r *http.Request) {
        fmt.Println(r.URL.Path)
        p := "." + r.URL.Path
        if p == "./" {
            p = "./static/index.html"
        }
        http.ServeFile(w, r, p)
    }
    

提交回复
热议问题