Enable CORS

This commit is contained in:
PhatPhuckDave
2024-07-21 18:59:57 +02:00
parent 38449a7676
commit 7e12d9e939
2 changed files with 36 additions and 15 deletions

View File

@@ -21,28 +21,49 @@ func init() {
const DOWNLOAD_WORKERS = 10
var downloadQueue = make(chan *DownloadTask, 100)
func enableCORS(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", "GET, POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusOK)
return
}
next.ServeHTTP(w, r)
})
}
func handleDownload(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
return
}
var req DownloadRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
log.Printf("Error parsing JSON: %v", err)
http.Error(w, "Error parsing JSON", http.StatusBadRequest)
return
}
downloadQueue <- &DownloadTask{Url: req.Link}
w.WriteHeader(http.StatusOK)
}
func main() {
downloadQueue := make(chan *DownloadTask, 100)
for i := 0; i < DOWNLOAD_WORKERS; i++ {
worker := &DownloadWorker{id: i, input: downloadQueue}
go worker.Run()
}
http.HandleFunc("/download", func(responseWriter http.ResponseWriter, request *http.Request) {
defer request.Body.Close()
req := DownloadRequest{}
err := json.NewDecoder(request.Body).Decode(&req)
if err != nil {
log.Printf("Error parsing JSON: %v", err)
http.Error(responseWriter, "Error parsing JSON", http.StatusBadRequest)
return
}
downloadQueue <- &DownloadTask{Url: req.Link}
})
mux := http.NewServeMux()
mux.Handle("/download", enableCORS(http.HandlerFunc(handleDownload)))
log.Println("Server starting on :5000")
err := http.ListenAndServe(":5000", nil)
err := http.ListenAndServe(":5000", mux)
if err != nil {
log.Println("Error starting server:", err)
}