Golang serve static files from memory

前端 未结 4 2011
忘了有多久
忘了有多久 2020-12-08 11:54

I have a quick question about serving files in Go. There is the great timesaving FileServer handler, but for my use case, I only have 2 or 3 files (js and css) that go with

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-08 12:19

    I would store the files in variable as plain text. Something like this:

    package main
    
    import (
            "fmt"
            "log"
            "net/http"
    )
    
    var files = map[string]string{}
    
    func init() {
            files["style.css"] = `
    /* css file content */
    body { background-color: pink; }
    `
    }
    
    func init() {
            files["index.html"] = `
    
    
    
    Hello world!
    `
    }
    
    func main() {
            for fileName, content := range files {
                    contentCpy := content
                    http.HandleFunc("/"+fileName, func(w http.ResponseWriter, r *http.Request) {
                            fmt.Fprintf(w, "%s\n", contentCpy)
                    })
            }
    
            log.Fatal(http.ListenAndServe(":8080", nil))
    }
    

    That way, it is pretty easy to have your makefile or build script so something like:

    for file in index.html style.css; do echo "package main\nfunc init() { files[\"$file\"] = \`$(cat $file)\` }" | gofmt -s > $file.go; done; go build && ./httptest

提交回复
热议问题