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) | |
} | |
} |