feat: add cors middleware

This commit is contained in:
2025-12-24 16:33:13 -03:00
parent 56209011ec
commit 6f419ece3d
2 changed files with 23 additions and 3 deletions

View File

@@ -7,6 +7,7 @@ import (
_ "gitea.gabilandia.com/gabdlr/agenda-web-go/docs"
"gitea.gabilandia.com/gabdlr/agenda-web-go/internal/database"
"gitea.gabilandia.com/gabdlr/agenda-web-go/internal/handler"
"gitea.gabilandia.com/gabdlr/agenda-web-go/internal/middleware"
"gitea.gabilandia.com/gabdlr/agenda-web-go/internal/repository"
httpSwagger "github.com/swaggo/http-swagger"
)
@@ -17,12 +18,12 @@ import (
// @termsOfService http://swagger.io/terms/
// @contact.name API Support
// @contact.email support@yourapp.com
// @contact.email gabriel.delosrios@tutamail.com
// @license.name MIT
// @license.url https://opensource.org/licenses/MIT
// @host localhost:8080
// @host agenda-web-go.gabilandia.com
// @BasePath /
func main() {
err := database.InitDB()
@@ -36,5 +37,5 @@ func main() {
handler.HandleContacts(mux, contactRepo)
handler.HandlHealthChecks(mux)
mux.HandleFunc("/swagger/", httpSwagger.WrapHandler)
log.Fatal(http.ListenAndServe(":8080", mux))
log.Fatal(http.ListenAndServe(":8080", middleware.CorsMiddleware(mux)))
}

View File

@@ -0,0 +1,19 @@
package middleware
import (
"net/http"
"os"
)
func CorsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", os.Getenv("ALLOWED_ORIGIN"))
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
next.ServeHTTP(w, r)
})
}