chore(api): cors config

This commit is contained in:
Leandro Antônio Farias Machado 2023-05-13 12:47:15 -03:00
parent 611b50476d
commit 29292fd98b
2 changed files with 33 additions and 1 deletions

View File

@ -4,6 +4,7 @@ import (
"encoding/json"
"github.com/gorilla/mux"
"github.com/leandrofars/oktopus/internal/api/auth"
"github.com/leandrofars/oktopus/internal/api/cors"
"github.com/leandrofars/oktopus/internal/api/middleware"
"github.com/leandrofars/oktopus/internal/db"
"github.com/leandrofars/oktopus/internal/mtp"
@ -49,17 +50,21 @@ func StartApi(a Api) {
//TODO: Create operation action handler
iot.HandleFunc("/device/{sn}/act", a.deviceUpdateMsg).Methods("PUT")
// Middleware for requests which requires user to be authenticated
iot.Use(func(handler http.Handler) http.Handler {
return middleware.Middleware(handler)
})
// Verifies CORS configs for requests
corsOpts := cors.GetCorsConfig()
srv := &http.Server{
Addr: "0.0.0.0:" + a.Port,
// Good practice to set timeouts to avoid Slowloris attacks.
WriteTimeout: time.Second * 15,
ReadTimeout: time.Second * 15,
IdleTimeout: time.Second * 60,
Handler: r, // Pass our instance of gorilla/mux in.
Handler: corsOpts.Handler(r), // Pass our instance of gorilla/mux in.
}
// Run our server in a goroutine so that it doesn't block.

View File

@ -0,0 +1,27 @@
package cors
import (
"github.com/rs/cors"
"net/http"
)
func GetCorsConfig() cors.Cors {
return *cors.New(cors.Options{
AllowedOrigins: []string{
"http://localhost:3000",
},
AllowedMethods: []string{
http.MethodGet,
http.MethodPost,
http.MethodPut,
http.MethodPatch,
http.MethodDelete,
http.MethodOptions,
http.MethodHead,
},
AllowedHeaders: []string{
"*", //or you can your header key values which you are using in your application
},
})
}