Skip to content

Instantly share code, notes, and snippets.

@TwistingTwists
Created March 10, 2023 11:05
Show Gist options
  • Save TwistingTwists/975e5c53335dc1ff9ad43b9b7856c657 to your computer and use it in GitHub Desktop.
Save TwistingTwists/975e5c53335dc1ff9ad43b9b7856c657 to your computer and use it in GitHub Desktop.
golang CORS allowed http server with static file serve

run it via

go run main.go from the directory you want to server static files from .

package main
import (
"net/http"
)
func corsMiddleware(next http.Handler) http.Handler {
headers := "*"
methods := "*"
origins := "*"
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", origins)
w.Header().Set("Access-Control-Allow-Methods", methods)
w.Header().Set("Access-Control-Allow-Headers", headers)
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
next.ServeHTTP(w, r)
})
}
func main() {
// Create a new ServeMux
mux := http.NewServeMux()
// Serve static files in the current directory
fs := http.FileServer(http.Dir("."))
mux.Handle("/", corsMiddleware(fs))
// Start the server
err := http.ListenAndServe(":8000", mux)
if err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment