How can I make my own reader

79 views
Skip to first unread message

suco...@gmail.com

unread,
Jun 25, 2017, 2:39:58 PM6/25/17
to golang-nuts
package main

import (
   "io"
   "log"
   "os"
)

type test struct {
   name string
}

func (a *test) Read(p []byte) (int, error) {

    var size int
   for {
       // I want to  put large data to response the read ; some data whatever I want ...

        size = size + 102400
       // condition  to break
       break
   }

    return size, nil
}

func main() {
   r := &test{name: "test"}
   if _, err := io.Copy(os.Stdout, r); err != nil {
       log.Fatal(err)
   }
}


How Read method get its data , I do not know where my data should be put , the method just return int 

Nathan Kerr

unread,
Jun 25, 2017, 5:26:25 PM6/25/17
to golang-nuts
From the docs:

Read reads up to len(p) bytes into p.

This lets the caller of Read manage the allocation and re-use of p. It also means your Read method has to work within the confines of whatever p you are given. If the data being read is larger than p, then the Read implementation must keep track of how much of the data has been read so far, and put the next part into p. 
Reply all
Reply to author
Forward
0 new messages