duanjia6959 2016-08-25 20:32
浏览 21
已采纳

如何在Go中重用原始的string.Reader?

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)
}   
  • 写回答

1条回答 默认 最新

  • matlabmann 2016-08-25 20:41
    关注

    You can seek back to the start of the string with either the strings.Reader or bytes.Reader

    reader := bytes.NewReader([]byte("{\"id\": 10, \"name\": \"Pie\"}"))
    
    decoder := json.NewDecoder(reader)
    var food Food
    decoder.Decode(&food)
    fmt.Println("About to eat food", food.Id)
    
    reader.Seek(0, 0)
    genericFunction(reader)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100