I have a server implemented in net/http with a single POST endpoint, whenever I am trying to hit it from my react code I get a 405 on my pre-flight request, what am I missing?
Here is the implementation of my router package
package router
import (
"net/http"
"time"
"github.com/onlinejudge95/Dicehub/backend/internal/config"
"github.com/onlinejudge95/Dicehub/backend/internal/handler"
"github.com/onlinejudge95/Dicehub/backend/internal/middleware"
)
func NewHTTPRouter(conf config.ServerConfig) *http.Server {
router := http.NewServeMux()
router.HandleFunc("POST /api/profile", middleware.EnableCors(handler.CreateProfile))
return &http.Server{
Addr: conf.BindAddress,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
Handler: router,
}
}
Here is the implementation of my EnableCors middleware
package middleware
import (
"log/slog"
"net/http"
)
func EnableCors(next http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
slog.Info("Inside Cors handler")
if r.Method == http.MethodOptions {
slog.Info("Received a preflight request")
w.WriteHeader(http.StatusOK)
return
}
next.ServeHTTP(w, r)
})
}