Skip to content

Instantly share code, notes, and snippets.

@miku
Last active June 23, 2023 14:31
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save miku/293f253b706c4de1b75c to your computer and use it in GitHub Desktop.
Save miku/293f253b706c4de1b75c to your computer and use it in GitHub Desktop.
{
"Name": "Elvis",
"Location": "Memphis"
}
// 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