Skip to content

Instantly share code, notes, and snippets.

@clooth
Created September 10, 2013 10:41
Show Gist options
  • Select an option

  • Save clooth/6507702 to your computer and use it in GitHub Desktop.

Select an option

Save clooth/6507702 to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"log"
"net/http"
"strconv"
)
func writeJson(rw http.ResponseWriter, v interface{}) {
// avoid json vulnerabilities, always wrap v in an object literal
doc := map[string]interface{}{"d": v}
if data, err := json.Marshal(doc); err != nil {
log.Printf("Error marshalling json: %v", err)
} else {
rw.Header().Set("Content-Length", strconv.Itoa(len(data)))
rw.Header().Set("Content-Type", "application/json")
rw.Write(data)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment