Golang serve static files from memory

前端 未结 4 2010
忘了有多久
忘了有多久 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:16

    It is not very difficult to do what you request. You don't have to base64 encode it or anything (it will just make it harder for you to edit.).

    Below is an example of how to output a javascript file with correct mime type:

    package main
    
    import (
        "fmt"
        "log"
        "net/http"
    )
    
    const jsFile = `alert('Hello World!');`
    
    func main() {
        http.HandleFunc("/file.js", JsHandler)
    
        log.Fatal(http.ListenAndServe(":8080", nil))
    }
    
    func JsHandler(w http.ResponseWriter, r *http.Request) {
        // Getting the headers so we can set the correct mime type
        headers := w.Header()
        headers["Content-Type"] = []string{"application/javascript"}
        fmt.Fprint(w, jsFile)
    }
    

提交回复
热议问题