Skip to content

Instantly share code, notes, and snippets.

@gebi
Created July 30, 2013 19: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 gebi/6116315 to your computer and use it in GitHub Desktop.
Save gebi/6116315 to your computer and use it in GitHub Desktop.
http utils for protobuf/json
package main
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
"strconv"
)
func readJson(r *http.Request, v interface{}) bool {
defer r.Body.Close()
var (
body []byte
err error
)
body, err = ioutil.ReadAll(r.Body)
if err != nil {
log.Printf("ReadJson couldn't read request body %v", err)
return false
}
if err = json.Unmarshal(body, v); err != nil {
log.Printf("ReadJson couldn't parse request body %v", err)
return false
}
return true
}
func writeJson(w 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 {
w.Header().Set("Content-Length", strconv.Itoa(len(data)))
w.Header().Set("Content-Type", "application/json")
w.Write(data)
}
}
package main
import (
"code.google.com/p/goprotobuf/proto"
"io/ioutil"
"log"
"net/http"
"strconv"
)
func readProto(r *http.Request, v proto.Message) bool {
defer r.Body.Close()
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Printf("Couldn't read request body %v", err)
return false
}
if err = proto.Unmarshal(body, v); err != nil {
log.Printf("Couldn't parse request body %v", err)
return false
}
return true
}
func writeProto(w http.ResponseWriter, v proto.Message) {
if data, err := proto.Marshal(v); err != nil {
log.Printf("Error marshalling proto: %v", err)
} else {
w.Header().Set("Content-Length", strconv.Itoa(len(data)))
w.Header().Set("Content-Type", "application/protobuf")
w.Write(data)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment