Skip to content

Instantly share code, notes, and snippets.

@hylarucoder
Created November 27, 2024 03:33
Show Gist options
  • Save hylarucoder/46d703ec750bec2035e750eb0d3b10e8 to your computer and use it in GitHub Desktop.
Save hylarucoder/46d703ec750bec2035e750eb0d3b10e8 to your computer and use it in GitHub Desktop.
golang serve media dir
package main
import (
"log"
"net/http"
)
func main() {
// Create file server handler
fs := http.FileServer(http.Dir("./media"))
// Wrap with CORS middleware
handler := corsMiddleware(fs)
// Strip /media/ prefix and serve files
http.Handle("/media/", http.StripPrefix("/media/", handler))
log.Printf("Starting server on :8888")
if err := http.ListenAndServe(":8888", nil); err != nil {
log.Fatal(err)
}
}
func corsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Set CORS headers
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "*")
// Handle preflight requests
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
// Serve files
next.ServeHTTP(w, r)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment