Created
July 20, 2014 03:52
-
-
Save ianunruh/e4034018057d196cdbb0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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