From 563bde429e91c495b9be36c6be013e9b6fc333ba Mon Sep 17 00:00:00 2001 From: Dumindu Madunuwan Date: Mon, 24 Aug 2026 14:16:38 +0800 Subject: [PATCH] CORS --- .env | 4 ++++ app/router/router.go | 16 +++++++++++++++- cmd/app/main.go | 4 ++-- config/config.go | 7 +++++++ go.mod | 1 + go.sum | 2 ++ 6 files changed, 31 insertions(+), 3 deletions(-) diff --git a/.env b/.env index 4a32095..fcadf39 100644 --- a/.env +++ b/.env @@ -6,6 +6,10 @@ SERVER_TIMEOUT_WRITE=5s SERVER_TIMEOUT_IDLE=5s SERVER_DEBUG=true +CORS_ALLOWED_ORIGINS="http://localhost:8080,http://127.0.0.1:8080" +CORS_ALLOWED_HEADERS="Accept,Authorization,Content-Type,X-CSRF-Token" +CORS_MAX_AGE=300 + DB_HOST=db DB_PORT=5432 DB_USER=myapp_user diff --git a/app/router/router.go b/app/router/router.go index a0108a3..f180921 100644 --- a/app/router/router.go +++ b/app/router/router.go @@ -2,29 +2,43 @@ package router import ( "net/http" + "strings" "github.com/go-chi/chi/v5" + "github.com/go-chi/cors" "github.com/go-playground/validator/v10" "github.com/rs/zerolog" "github.com/rs/zerolog/hlog" "gorm.io/gorm" "myapp/app/book" + "myapp/config" m "myapp/pkg/middleware" mrl "myapp/pkg/middleware/requestlog" ) -func New(l *zerolog.Logger, v *validator.Validate, db *gorm.DB) *chi.Mux { +func New(c *config.ConfCORS, l *zerolog.Logger, v *validator.Validate, db *gorm.DB) *chi.Mux { r := chi.NewRouter() r.Get("/livez", func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte(".")) }) + cors := cors.New(cors.Options{ + AllowedOrigins: strings.Split(c.AllowedOrigins, ","), + AllowedMethods: []string{http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete, http.MethodOptions}, + AllowedHeaders: strings.Split(c.AllowedHeaders, ","), + AllowCredentials: true, + ExposedHeaders: []string{""}, + MaxAge: c.MaxAge, + }) + r.Route("/v1", func(r chi.Router) { + r.Use(cors.Handler) r.Use(hlog.NewHandler(*l)) r.Use(hlog.RequestIDHandler("request_id", "X-Request-ID")) r.Use(mrl.NewHandler) r.Use(m.ContentTypeJSON) + r.Route("/books", book.New(v, db).Register) }) diff --git a/cmd/app/main.go b/cmd/app/main.go index 7ca4424..278fa9c 100644 --- a/cmd/app/main.go +++ b/cmd/app/main.go @@ -62,11 +62,11 @@ func main() { return } - r := router.New(&l, v, db) + mux := router.New(&c.CORS, &l, v, db) s := &http.Server{ Addr: fmt.Sprintf(":%d", c.Server.Port), - Handler: r, + Handler: mux, ReadTimeout: c.Server.TimeoutRead, WriteTimeout: c.Server.TimeoutWrite, IdleTimeout: c.Server.TimeoutIdle, diff --git a/config/config.go b/config/config.go index 737efc3..caa2a5e 100644 --- a/config/config.go +++ b/config/config.go @@ -10,6 +10,7 @@ import ( type Conf struct { TZ string `env:"TZ,required"` Server ConfServer + CORS ConfCORS DB ConfDB } @@ -21,6 +22,12 @@ type ConfServer struct { Debug bool `env:"SERVER_DEBUG,required"` } +type ConfCORS struct { + AllowedOrigins string `env:"CORS_ALLOWED_ORIGINS,required"` + AllowedHeaders string `env:"CORS_ALLOWED_HEADERS,required"` + MaxAge int `env:"CORS_MAX_AGE,required"` +} + type ConfDB struct { Host string `env:"DB_HOST,required"` Port int `env:"DB_PORT,required"` diff --git a/go.mod b/go.mod index 8b017f2..bfd4abf 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,7 @@ go 1.27 require ( github.com/caarlos0/env/v11 v11.4.1 github.com/go-chi/chi/v5 v5.3.1 + github.com/go-chi/cors v1.2.2 github.com/go-playground/validator/v10 v10.30.3 github.com/google/go-cmp v0.7.0 github.com/google/uuid v1.6.0 diff --git a/go.sum b/go.sum index 10671c7..759c23d 100644 --- a/go.sum +++ b/go.sum @@ -16,6 +16,8 @@ github.com/gabriel-vasile/mimetype v1.4.13 h1:46nXokslUBsAJE/wMsp5gtO500a4F3Nkz9 github.com/gabriel-vasile/mimetype v1.4.13/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= github.com/go-chi/chi/v5 v5.3.1 h1:3j4HZLGZQ3JpMCrPJF/Jl3mYJfWLKBfNJ6quurUGCf8= github.com/go-chi/chi/v5 v5.3.1/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto= +github.com/go-chi/cors v1.2.2 h1:Jmey33TE+b+rB7fT8MUy1u0I4L+NARQlK6LhzKPSyQE= +github.com/go-chi/cors v1.2.2/go.mod h1:sSbTewc+6wYHBBCW7ytsFSn836hqM7JxpglAy2Vzc58= github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= github.com/go-openapi/jsonpointer v0.19.6 h1:eCs3fxoIi3Wh6vtgmLTOjdhSpiqphQ+DaPn38N2ZdrE=