Skip to content

Instantly share code, notes, and snippets.

@ianunruh
Created July 20, 2014 03:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ianunruh/e4034018057d196cdbb0 to your computer and use it in GitHub Desktop.
Save ianunruh/e4034018057d196cdbb0 to your computer and use it in GitHub Desktop.
package main
import (
"net/http"
"github.com/go-martini/martini"
"github.com/martini-contrib/encoder"
"github.com/martini-contrib/strict"
)
func configureEncoder(c martini.Context, w http.ResponseWriter) {
c.MapTo(encoder.JsonEncoder{}, (*encoder.Encoder)(nil))
w.Header().Set("Content-Type", "application/json; charset=utf-8")
}
func injectCorsHeaders(resp http.ResponseWriter, req *http.Request) {
if len(req.Header.Get("Origin")) > 0 {
resp.Header().Set("Access-Control-Allow-Origin", "*")
resp.Header().Set("Access-Control-Allow-Method", "GET, POST, PATCH, PUT, DELETE")
resp.Header().Set("Access-Control-Allow-Credentials", "true")
resp.Header().Set("Access-Control-Allow-Headers", req.Header.Get("Access-Control-Request-Headers"))
resp.Header().Set("Access-Control-Max-Age", "86400")
if req.Method == "OPTIONS" {
resp.WriteHeader(200)
}
}
}
func main() {
m := martini.Classic()
m.Use(configureEncoder)
m.Use(injectCorsHeaders)
m.Get("/", handleIndex)
m.Post("/users", handleCreateUser)
m.NotFound(strict.MethodNotAllowed)
m.NotFound(strict.NotFound)
m.Run()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment