Skip to content

Commit a45d916

Browse files
authored
feat: adds configurable cors (#87)
* feat: adds configurable cors to it * feat: add missing config changes
1 parent ba7977b commit a45d916

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

gateway/config/config.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,12 @@ type Config struct {
1717
UserNameClaim string `envconfig:"default=email,optional"`
1818

1919
ShouldImpersonate bool `envconfig:"default=true,optional"`
20+
21+
Cors struct {
22+
Enabled bool `envconfig:"default=false,optional"`
23+
AllowedOrigins []string `envconfig:"default=*,optional"`
24+
AllowedHeaders []string `envconfig:"default=*,optional"`
25+
}
2026
}
2127

2228
type HandlerConfig struct {

gateway/manager/manager.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,19 @@ func (s *Service) createHandler(schema *graphql.Schema) *graphqlHandler {
187187
}
188188

189189
func (s *Service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
190+
191+
if (*r).Method == "OPTIONS" && s.appCfg.Cors.Enabled {
192+
allowedOrigins := strings.Join(s.appCfg.Cors.AllowedOrigins, ",")
193+
allowedHeaders := strings.Join(s.appCfg.Cors.AllowedHeaders, ",")
194+
w.Header().Set("Access-Control-Allow-Origin", allowedOrigins)
195+
w.Header().Set("Access-Control-Allow-Headers", allowedHeaders)
196+
// setting cors allowed methods is not needed for this service,
197+
// as all graphql methods are part of the cors safelisted methods
198+
// https://fetch.spec.whatwg.org/#cors-safelisted-method
199+
w.WriteHeader(http.StatusOK)
200+
return
201+
}
202+
190203
workspace, err := s.parsePath(r.URL.Path)
191204
if err != nil {
192205
s.log.Error().Err(err).Str("path", r.URL.Path).Msg("Error parsing path")

0 commit comments

Comments
 (0)