Skip to content

Instantly share code, notes, and snippets.

@mrvdot
Last active December 21, 2015 10:58
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mrvdot/6295179 to your computer and use it in GitHub Desktop.
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.
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