-
-
Save smallnest/c50c4bd11d576f3c49d16b482a6993c9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
{ | |
"Name": "Elvis", | |
"Location": "Memphis" | |
} |
This file contains hidden or 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
// Run in one window: | |
// | |
// $ go run readtwice.go | |
// | |
// An in another: | |
// | |
// $ curl -d @payload.json localhost:8080/ | |
// | |
// You should see something like: | |
// | |
// 2015/08/07 20:57:01 entering readFirst | |
// 2015/08/07 20:57:01 deserialized payload from body: {Elvis Memphis} | |
// 2015/08/07 20:57:01 entering readSecond | |
// 2015/08/07 20:57:01 request body: { "Name": "Elvis", "Location": "Memphis"} | |
// | |
package main | |
import ( | |
"bytes" | |
"encoding/json" | |
"io" | |
"io/ioutil" | |
"log" | |
"net/http" | |
) | |
type Payload struct { | |
Name string | |
Location string | |
} | |
func readSecond(w http.ResponseWriter, r *http.Request) { | |
log.Println("entering readSecond") | |
// r.Body is a io.ReadCloser, that's all we know | |
b, err := ioutil.ReadAll(r.Body) | |
if err != nil { | |
log.Fatal(err) | |
} | |
// closing a NopCloser won't hurt anybody | |
defer r.Body.Close() | |
log.Printf("request body: %s", string(b)) | |
} | |
func readFirst(w http.ResponseWriter, r *http.Request) { | |
log.Println("entering readFirst") | |
// temporary buffer | |
b := bytes.NewBuffer(make([]byte, 0)) | |
// TeeReader returns a Reader that writes to b what it reads from r.Body. | |
reader := io.TeeReader(r.Body, b) | |
// some business logic | |
var payload Payload | |
if err := json.NewDecoder(reader).Decode(&payload); err != nil { | |
log.Fatal(err) | |
} | |
// we are done with body | |
defer r.Body.Close() | |
log.Printf("deserialized payload from body: %v", payload) | |
// NopCloser returns a ReadCloser with a no-op Close method wrapping the provided Reader r. | |
r.Body = ioutil.NopCloser(b) | |
} | |
func handler(w http.ResponseWriter, r *http.Request) { | |
readFirst(w, r) | |
readSecond(w, r) | |
} | |
func main() { | |
http.HandleFunc("/", handler) | |
log.Fatal(http.ListenAndServe(":8080", nil)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment