-
-
Save luojiyin1987/8edbefdb5969f644c4f06bbd122e3601 to your computer and use it in GitHub Desktop.
golang serve media dir
This file contains hidden or 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 ( | |
| "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