Created
July 30, 2013 19:52
-
-
Save gebi/6116315 to your computer and use it in GitHub Desktop.
http utils for protobuf/json
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 ( | |
"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) | |
} | |
} |
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 ( | |
"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