V
V
Void Vasher2021-01-21 14:45:27
API
Void Vasher, 2021-01-21 14:45:27

How to implement CORS dynamic update?

Good afternoon.

There is a service that has an endpoint for adding callback URLs, they are written to the database, and after that, the client (for example, JS) uses any of the URLs stored there for callbacks.

The question is: is it possible in Golang to dynamically update CORS settings? I 'm currently using the github.com/rs/cors package . In my example, this is necessary, when adding callback URLs, the scheme and host will be taken from each URL, and added to the CORS settings ( AllowedOrigins)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Tsvetkov, 2021-01-21
@AlgollY

Set up a global variable var origins = make(map[string]struct{}) . After writing the endpoint to the database, calculate the origin of the given URL and add it to the global variable origins . The settings of the object with KORS will look something like this

c := cors.New(cors.Options{
  AllowCredentials: true,
  AllowOriginRequestFunc: func(r *http.Request, origin string) bool {
    if _, ok := origins[r.Header.Get("Origin")]; !ok {
      return false
    }
    return true
  },
})

For good, it would be necessary to close reading / writing with mutexes, but I think they should cope with this

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question