Enable CORS
This commit is contained in:
@@ -21,28 +21,49 @@ func init() {
|
|||||||
|
|
||||||
const DOWNLOAD_WORKERS = 10
|
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() {
|
func main() {
|
||||||
downloadQueue := make(chan *DownloadTask, 100)
|
|
||||||
for i := 0; i < DOWNLOAD_WORKERS; i++ {
|
for i := 0; i < DOWNLOAD_WORKERS; i++ {
|
||||||
worker := &DownloadWorker{id: i, input: downloadQueue}
|
worker := &DownloadWorker{id: i, input: downloadQueue}
|
||||||
go worker.Run()
|
go worker.Run()
|
||||||
}
|
}
|
||||||
|
|
||||||
http.HandleFunc("/download", func(responseWriter http.ResponseWriter, request *http.Request) {
|
mux := http.NewServeMux()
|
||||||
defer request.Body.Close()
|
mux.Handle("/download", enableCORS(http.HandlerFunc(handleDownload)))
|
||||||
|
|
||||||
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}
|
|
||||||
})
|
|
||||||
log.Println("Server starting on :5000")
|
log.Println("Server starting on :5000")
|
||||||
err := http.ListenAndServe(":5000", nil)
|
err := http.ListenAndServe(":5000", mux)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println("Error starting server:", err)
|
log.Println("Error starting server:", err)
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user