Adding CORS to our API
Let’s imagine we have a web application that needs to access our API. To do it properly, we need to use CORS. If not, we can only have our web application in the same domain as our API, or the browser will block the requests.
For our API, we are going to use the github.com/rs/cors package.
Before we add CORS, we need to modify how we do routing in our API. Instead of registering the handlers directly using http.HandleFunc, we will use a mux variable to register the handlers.
func main() {
...
mux := http.NewServeMux()
mux.HandleFunc("GET /lists", authRequired(handleListLists))
mux.HandleFunc("POST /lists", adminRequired(handleCreateList))
mux.HandleFunc("GET /lists/{id}", authRequired(handleGetList))
mux.HandleFunc("PUT /lists/{id}", adminRequired(handleUpdateList))
mux.HandleFunc("DELETE /lists/{id}", adminRequired(handleDeleteList))
mux.HandleFunc("PATCH /lists/{id}"...