Last active
December 21, 2015 10:58
-
-
Save mrvdot/6295179 to your computer and use it in GitHub Desktop.
If you've ever wanted to handle JSONP callbacks within a Go powered API, here's a simple wrapper that you can use to intercept the callback query variable and properly wrap the response. It's designed to take an entire http.Handler, so works particularly well when using a router such as mux from gorilla, however can work with any handler.
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
import ( | |
"io" | |
"net/http" | |
) | |
//With HandlerFunc | |
func main () { | |
http.Handle("/", JsonpHandler(http.HandlerFunc(func (w http.ResponseWriter, r *http.Request) { | |
w.Write("Hello World") | |
}))) | |
} | |
func JsonpHandler(h http.Handler) http.Handler { | |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
callback := r.FormValue("callback") | |
if callback != "" { | |
w.Header().Add("Content-Type", "text/javascript") | |
io.WriteString(w, callback+"(") | |
defer func() { | |
io.WriteString(w, ");") | |
}() | |
} | |
h.ServeHTTP(w, r) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment