I have an input of type strings.Reader
. Given the input, I am extracting the id
from it and printing it out. I then pass the original input to a generic function that perform other tasks on it. The only way I can think of reusing the original is to read the content and pass it to a bytes.Reader
twice.
Is the following the only way to achieve that in Go?
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"strings"
)
type Food struct {
Id int `json:"id"`
Name string `json:"name"`
}
func genericFunction(body io.Reader) {
content, err := ioutil.ReadAll(body)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(content))
}
func main() {
// Original input
reader := strings.NewReader("{\"id\": 10, \"name\": \"Pie\"}")
original, err := ioutil.ReadAll(reader)
if err != nil {
log.Fatal(err)
}
foodReader := bytes.NewReader(original)
decoder := json.NewDecoder(foodReader)
var food Food
decoder.Decode(&food)
fmt.Println("About to eat food", food.Id)
foodReader = bytes.NewReader(original)
genericFunction(foodReader)
}