SPAs really need CORS properly implemented to work properly from the browser. In Node this is super easy, this time I need to figure out the golang way of doing it. The Gorilla Web Toolkit definitely has a set of handlers which will help. I am not familiar enough with golang to actually figure out how to use these by themselves yet.

However StackOverflow comes to the rescue showing how to use the functions.

The resulting code looked a bit like:

import (
	"os"

	//"encoding/json"
	"log"
	"net/http"

	handlers "github.com/gorilla/handlers"
	"github.com/gorilla/mux"
)

func envOrDefault( key string, defaultValue string ) string {
	value := os.Getenv(key)
	if len(value) == 0 {
		return defaultValue
	}
	return value
}


func main() {
	core :=  Service{
		storage:storage,
	}

	service := hanlder

	coreMiddleware := core.Middleware(core)

	port := resolveBinding()

	router := mux.NewRouter().StrictSlash(false)

	// CORS configuration
	headersOk := handlers.AllowedHeaders([]string{"X-Requested-With","Content-Type","Authorization"})
	originsOk := handlers.AllowedOrigins([]string{envOrDefault("CORS_ORIGINS","*")}) //TODO: Extract
	methodsOk := handlers.AllowedMethods([]string{ "POST", "OPTIONS"})

	corsWrapper := handlers.CORS(originsOk, headersOk, methodsOk, handlers.AllowCredentials())

	router.Handle("/graphql", handlers.LoggingHandler(os.Stdout, corsWrapper(jwtMiddleware.Handler(coreMiddleware))))
	router.Handle("/graphiql", http.HandlerFunc(ServeGQLI))

	fmt.Printf("Listening on port %s\n", port)
	log.Fatal(http.ListenAndServe(port, router))
}