Created
March 22, 2022 07:24
-
-
Save arbinish/81cde08dd77f356994e4b75218c4f9cc to your computer and use it in GitHub Desktop.
golang embed fs example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"embed" | |
"io/fs" | |
"log" | |
"net/http" | |
"os" | |
"strconv" | |
"time" | |
) | |
//go:embed build/* | |
var content embed.FS | |
var infoLog = log.New(os.Stdout, "[INFO] ", log.LstdFlags) | |
var errorLog = log.New(os.Stderr, "[ERROR] ", log.LstdFlags) | |
func withLogging(h http.Handler) http.Handler { | |
var size int | |
var err error | |
logger := func(w http.ResponseWriter, r *http.Request) { | |
now := time.Now() | |
h.ServeHTTP(w, r) | |
cLength := w.Header().Get("content-length") | |
if cLength == "" { | |
size = 0 | |
} else { | |
size, err = strconv.Atoi(cLength) | |
if err != nil { | |
errorLog.Printf("got error parsing content length for %s\n [%s]", r.RequestURI, err) | |
} | |
} | |
duration := time.Since(now) | |
infoLog.Printf("uri=%s response_size=%d duration=%dms\n", r.RequestURI, size, duration.Milliseconds()) | |
} | |
return http.HandlerFunc(logger) | |
} | |
func main() { | |
mux := http.NewServeMux() | |
mux.Handle("/admin", withLogging( | |
http.HandlerFunc( | |
func(w http.ResponseWriter, r *http.Request) { | |
w.Write([]byte("OK\n")) | |
}), | |
)) | |
root, _ := fs.Sub(content, "build") | |
mux.Handle("/", withLogging(http.FileServer(http.FS(root)))) | |
servicePort := ":9191" | |
if p, ok := os.LookupEnv("PORT"); ok { | |
servicePort = ":" + p | |
} | |
infoLog.Println("Listening on", servicePort) | |
errorLog.Println(http.ListenAndServe(servicePort, mux)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment