CORS and the SnailLife API

I will be the first to admit that I am a cross-origin resource sharing noob.

Because I want my SnailLife API to be open to the public for anyone to write ther own clients, I needed to set some CORS headers. I first hit this myself when running my server in a Docker container and then trying to use the API from the SnailLife Genome Lab. The implementation will very likely change, but I figured I’d start with recording how I did it so far. You are more than welcome to point out all the security flaws I’m doubtless exposing my poor snails to!

I added a new handler to my Gorilla mux router which will take the existing handler and take care of writing the CORS response, as well as returning early if we are getting an OPTIONS request:

func handleCORS(handler http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Method == http.MethodOptions {
		handler.ServeHTTP(w, r)
func WriteCORSResponse(w http.ResponseWriter) {
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS")
	w.Header().Set("Access-Control-Allow-Headers", "x-authentication-token, content-type, auth_provider")

Now, in my SnailLife Genome Lab, I can send a login request to the API:

        type: "POST",
        beforeSend: function(request) {
            request.setRequestHeader("content-type", "application/json");
        url: url,
        data: jsonData,
        processData: false,
        success: function(msg) {
        error: function(msg) {
© - 2021 · Liza Shulyayeva ·