Skip to content

Instantly share code, notes, and snippets.

@meyt
Created May 18, 2024 11:59
Show Gist options
  • Save meyt/146c317dcff65c3e15d27e614cfd8933 to your computer and use it in GitHub Desktop.
Save meyt/146c317dcff65c3e15d27e614cfd8933 to your computer and use it in GitHub Desktop.
Serve local files on HTTP (CORS Enabled)
package main
import (
"flag"
"log"
"net/http"
)
func main() {
port := flag.String("p", "8100", "port to serve on")
directory := flag.String("d", ".", "the directory of static file to host")
flag.Parse()
fileServer := http.FileServer(http.Dir(*directory))
http.Handle("/", allowCORS(fileServer))
log.Printf("Serving %s on HTTP port: %s\n", *directory, *port)
log.Fatal(http.ListenAndServe(":"+*port, nil))
}
func allowCORS(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "*")
w.Header().Set("Access-Control-Allow-Headers", "*")
w.Header().Set("Cross-Origin-Opener-Policy", "same-origin")
w.Header().Set("Cross-Origin-Embedder-Policy", "require-corp")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusOK)
return
}
next.ServeHTTP(w, r)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment