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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?