Posted on

[Golang] Goを始めたらまずはioパッケージを知るべし

Goを書いているとio.writerio.readerを扱うケースが頻繁に出てきますが、これはioパッケージが多くの他のパッケージのインターフェースになっているからなのでioパッケージを知っておくことで開発が楽になります。

参考書籍

本書はGoio.Writerio.Readerからはじまりシステムの深いところまで丁寧に説明されているのでとてもおすすめです。ioパッケージから始まっているのも納得です。Webで無料で見れますし書籍版、PDF版で購入も可能です。

Web版

https://ascii.jp/elem/000/001/235/1235262/

書籍版

ioパッケージのインターフェース一覧

ioパッケージのインターフェース一覧です。Goのインターフェースの実装は、明示的にインターフェースを明示的にimplementsせず、インターフェースを満たしていたらimplementsしていることになります。

  • Reader(インターフェース)
  • Writer(インターフェース)
  • Seeker(インターフェース)
  • Closer(インターフェース)
  • ReadWriter(複合インターフェース)
  • ReadCloser(複合インターフェース)
  • WriteCloser(複合インターフェース)
  • ReadSeeker(複合インターフェース)
  • WriteSeeker(複合インターフェース)
  • ReadWriteCloser(複合インターフェース)
  • ReadWriteSeeker(複合インターフェース)
  • ReaderFrom(インターフェース)
  • WriterTo(インターフェース)
  • ReaderAt(インターフェース)
  • WriterAt(インターフェース)
  • ByteReader(インターフェース)
  • ByteScanner(インターフェース)
  • ByteWriter(インターフェース)
  • RuneScanner(インターフェース)
  • StringWriter(インターフェース)

複合インターフェース表

Goではインターフェースにインターフェースを食わせることができ、ioパッケージで作られている複合インターフェースは以下となります。

インターフェースio.Readerio.Writerio.Seekerio.Closer
io.ReadWriter  
io.ReadSeeker  
io.ReadCloser  
io.WriteSeeker  
io.WriteCloser  
io.ReadWriteSeeker 
io.ReadWriteCloser 

インターフェースを満たしている一覧を確認する方法

以下のコマンドを叩くと対象のインターフェースを満たしているものの一覧が確認できます。

$ GOPATH=/ godoc -http ":6060" -analysis type
## 実行後以下のURLにアクセスすると`io`パッケージが確認できる
http://localhost:6060/pkg/io/

Readerのimplements一覧

テストも含んでいますが沢山あります

  • pointer type *archive/tar.Reader implements Reader
  • pointer type *archive/tar.regFileReader implements Reader
  • pointer type *archive/tar.sparseFileReader implements Reader
  • pointer type *archive/tar.testFile implements Reader
  • pointer type *archive/zip.checksumReader implements Reader
  • pointer type *archive/zip.pooledFlateReader implements Reader
  • pointer type *bufio.Reader implements Reader
  • pointer type *bufio_test.StringReader implements Reader
  • pointer type *bufio_test.emptyThenNonEmptyReader implements Reader
  • pointer type *bufio_test.errorThenGoodReader implements Reader
  • pointer type *bufio_test.negativeReader implements Reader
  • pointer type *bufio_test.rot13Reader implements Reader
  • pointer type *bufio_test.scriptedReader implements Reader
  • pointer type *bufio_test.slowReader implements Reader
  • pointer type *bufio_test.testReader implements Reader
  • pointer type *bytes.Buffer implements Reader
  • pointer type *bytes.Reader implements Reader
  • pointer type *bytes_test.negativeReader implements Reader
  • pointer type *cmd/compile/internal/gc.importReader implements Reader
  • pointer type *cmd/compile/internal/gc.intWriter implements Reader
  • pointer type *cmd/go/internal/modfile.printer implements Reader
  • pointer type *cmd/pack.FakeFile implements Reader
  • pointer type *cmd/vendor/golang.org/x/crypto/ssh/terminal.MockTerminal implements Reader
  • pointer type *compress/bzip2.reader implements Reader
  • pointer type *compress/flate.decompressor implements Reader
  • pointer type *compress/flate.sparseReader implements Reader
  • pointer type *compress/flate.syncBuffer implements Reader
  • pointer type *compress/gzip.Reader implements Reader
  • pointer type *compress/lzw.decoder implements Reader
  • pointer type *compress/zlib.reader implements Reader
  • pointer type *crypto/ecdsa.zr implements Reader
  • pointer type *crypto/rand.devReader implements Reader
  • pointer type *crypto/rand.reader implements Reader
  • pointer type *crypto/rand_test.countingReader implements Reader
  • pointer type *crypto/tls.Conn implements Reader
  • pointer type *crypto/tls.atLeastReader implements Reader
  • pointer type *crypto/tls.recordingConn implements Reader
  • pointer type *debug/elf.readSeekerFromReader implements Reader
  • pointer type *encoding/ascii85.decoder implements Reader
  • pointer type *encoding/base32.badReader implements Reader
  • pointer type *encoding/base32.decoder implements Reader
  • pointer type *encoding/base32.newlineFilteringReader implements Reader
  • pointer type *encoding/base64.decoder implements Reader
  • pointer type *encoding/base64.faultInjectReader implements Reader
  • pointer type *encoding/base64.newlineFilteringReader implements Reader
  • pointer type *encoding/binary.byteSliceReader implements Reader
  • pointer type *encoding/csv.nTimes implements Reader
  • pointer type *encoding/gob.benchmarkBuf implements Reader
  • pointer type *encoding/gob.decBuffer implements Reader
  • pointer type *encoding/hex.decoder implements Reader
  • pointer type *encoding/json.encodeState implements Reader
  • pointer type *encoding/xml.downCaser implements Reader
  • pointer type *fmt.ss implements Reader
  • pointer type *fmt.stringReader implements Reader
  • pointer type *fmt_test.eofCounter implements Reader
  • pointer type *go/types_test.gen implements Reader
  • pointer type *image/gif.blockReader implements Reader
  • pointer type *image/jpeg.eofReader implements Reader
  • pointer type *image/png.decoder implements Reader
  • pointer type *internal/poll.FD implements Reader
  • pointer type *internal/trace.Writer implements Reader
  • pointer type *internal/x/crypto/hkdf.hkdf implements Reader
  • pointer type *internal/x/text/transform.Reader implements Reader
  • pointer type *internal/x/text/unicode/norm.normReader implements Reader
  • pointer type *LimitedReader implements Reader
  • pointer type *PipeReader implements Reader
  • pointer type *SectionReader implements Reader
  • pointer type *multiReader implements Reader
  • pointer type *pipe implements Reader
  • pointer type *teeReader implements Reader
  • pointer type *io_test.Buffer implements Reader
  • pointer type *io_test.dataAndErrorBuffer implements Reader
  • pointer type *io_test.writeToChecker implements Reader
  • pointer type *math/rand.Rand implements Reader
  • pointer type *mime/multipart.Part implements Reader
  • pointer type *mime/multipart.failOnReadAfterErrorReader implements Reader
  • pointer type *mime/multipart.maliciousReader implements Reader
  • pointer type *mime/multipart.sentinelReader implements Reader
  • pointer type *mime/multipart.slowReader implements Reader
  • pointer type *mime/multipart.stickyErrorReader implements Reader
  • pointer type *mime/quotedprintable.Reader implements Reader
  • pointer type *net.Buffers implements Reader
  • pointer type *net.IPConn implements Reader
  • pointer type *net.TCPConn implements Reader
  • pointer type *net.UDPConn implements Reader
  • pointer type *net.UnixConn implements Reader
  • pointer type *net.conn implements Reader
  • pointer type *net.fakeDNSConn implements Reader
  • pointer type *net.fakeDNSPacketConn implements Reader
  • pointer type *net.netFD implements Reader
  • pointer type *net.pipe implements Reader
  • pointer type *net/http.body implements Reader
  • pointer type *net/http.bodyEOFSignal implements Reader
  • pointer type *net/http.byteReader implements Reader
  • pointer type *net/http.cancelTimerBody implements Reader
  • pointer type *net/http.connReader implements Reader
  • pointer type *net/http.delegateReader implements Reader
  • pointer type *net/http.expectContinueReader implements Reader
  • pointer type *net/http.gzipReader implements Reader
  • pointer type *net/http.http2dataBuffer implements Reader
  • pointer type *net/http.http2gzipReader implements Reader
  • pointer type *net/http.http2pipe implements Reader
  • pointer type *net/http.http2requestBody implements Reader
  • pointer type *net/http.loggingConn implements Reader
  • pointer type *net/http.maxBytesReader implements Reader
  • pointer type *net/http.persistConn implements Reader
  • pointer type *net/http.readWriteCloserBody implements Reader
  • pointer type *net/http/fcgi.writeOnlyConn implements Reader
  • pointer type *net/http/httputil.checkCloser implements Reader
  • pointer type *net/http/httputil.delegateReader implements Reader
  • pointer type *net/http/internal.chunkedReader implements Reader
  • pointer type *net/http_test.infiniteReader implements Reader
  • pointer type *net/http_test.lockedBytesBuffer implements Reader
  • pointer type *net/http_test.logWritesConn implements Reader
  • pointer type *net/http_test.repeatReader implements Reader
  • pointer type *net/http_test.slowTestConn implements Reader
  • pointer type *net/http_test.testConn implements Reader
  • pointer type *net/rpc.writeCrasher implements Reader
  • pointer type *net/textproto.dotReader implements Reader
  • pointer type *os.File implements Reader
  • pointer type *strings.Reader implements Reader
  • pointer type *testing/iotest.dataErrReader implements Reader
  • pointer type *testing/iotest.halfReader implements Reader
  • pointer type *testing/iotest.oneByteReader implements Reader
  • pointer type *testing/iotest.readLogger implements Reader
  • pointer type *testing/iotest.timeoutReader implements Reader
  • pointer type *text/scanner.StringReader implements Reader
  • pointer type *text/scanner.countReader implements Reader
  • struct type archive/tar.readBadSeeker implements Reader
  • struct type archive/tar.readSeeker implements Reader
  • struct type archive/tar.reader implements Reader
  • struct type archive/tar.testNonEmptyReader implements Reader
  • struct type archive/tar.zeroReader implements Reader
  • struct type archive/zip.zeros implements Reader
  • struct type bufio.ReadWriter implements Reader
  • struct type bufio_test.alwaysError implements Reader
  • basic type bufio_test.dataAndEOFReader implements Reader
  • struct type bufio_test.endlessZeros implements Reader
  • struct type bufio_test.errorReaderFromTest implements Reader
  • struct type bufio_test.errorWriterToTest implements Reader
  • struct type bufio_test.onlyReader implements Reader
  • struct type bufio_test.zeroReader implements Reader
  • struct type bytes_test.justReader implements Reader
  • struct type bytes_test.panicReader implements Reader
  • struct type cmd/compile/internal/gc.intReader implements Reader
  • struct type cmd/go/internal/lockedfile.File implements Reader
  • struct type cmd/go/internal/lockedfile.osFile implements Reader
  • struct type cmd/go/internal/modfetch/codehost.deleteCloser implements Reader
  • struct type cmd/internal/bio.Reader implements Reader
  • struct type cmd/link/internal/loadpe.peBiobuf implements Reader
  • struct type cmd/link/internal/loadxcoff.xcoffBiobuf implements Reader
  • basic type cmd/vendor/golang.org/x/crypto/ssh/terminal.passwordReader implements Reader
  • struct type compress/lzw.devZero implements Reader
  • struct type crypto/cipher.StreamReader implements Reader
  • struct type crypto/rand.hideAgainReader implements Reader
  • struct type crypto/tls.brokenConn implements Reader
  • struct type crypto/tls.changeImplConn implements Reader
  • struct type crypto/tls.hairpinConn implements Reader
  • chan type crypto/tls.opensslInput implements Reader
  • struct type crypto/tls.slowConn implements Reader
  • struct type crypto/tls.writeCountingConn implements Reader
  • struct type crypto/tls.zeroSource implements Reader
  • struct type crypto/tls_test.zeroSource implements Reader
  • struct type debug/elf.errorReader implements Reader
  • struct type go/build.readNopCloser implements Reader
  • struct type go/internal/gcimporter.intReader implements Reader
  • struct type eofReader implements Reader
  • struct type io/ioutil.nopCloser implements Reader
  • basic type io_test.byteAndEOFReader implements Reader
  • signature type io_test.readerFunc implements Reader
  • struct type io_test.wantedAndErrReader implements Reader
  • struct type io_test.zeroErrReader implements Reader
  • struct type math/big.byteReader implements Reader
  • struct type mime/multipart.partReader implements Reader
  • struct type mime/multipart.sectionReadCloser implements Reader
  • struct type net.dialResult implements Reader
  • basic type net.neverEnding implements Reader
  • struct type net/http.bodyLocked implements Reader
  • struct type net/http.closeChecker implements Reader
  • struct type net/http.connCloseListener implements Reader
  • struct type net/http.dumpConn implements Reader
  • struct type net/http.errorReader implements Reader
  • struct type net/http.finishAsyncByteRead implements Reader
  • struct type net/http.http2errorReader implements Reader
  • struct type net/http.http2transportResponseBody implements Reader
  • struct type net/http.noBody implements Reader
  • struct type net/http.readerAndCloser implements Reader
  • struct type net/http.socksConn implements Reader
  • struct type net/http.transferBodyReader implements Reader
  • basic type net/http/cgi.neverEnding implements Reader
  • struct type net/http/fcgi.nilCloser implements Reader
  • struct type net/http/fcgi.nopWriteCloser implements Reader
  • struct type net/http/fcgi.rwNopCloser implements Reader
  • struct type net/http/httputil.dumpConn implements Reader
  • struct type net/http/httputil.failureToReadBody implements Reader
  • basic type net/http/httputil.neverEnding implements Reader
  • struct type net/http_test.blockingRemoteAddrConn implements Reader
  • chan type net/http_test.byteFromChanReader implements Reader
  • struct type net/http_test.closeWriteTestConn implements Reader
  • struct type net/http_test.countCloseReader implements Reader
  • struct type net/http_test.countReader implements Reader
  • struct type net/http_test.delayedEOFReader implements Reader
  • struct type net/http_test.dotFileHidingFile implements Reader
  • signature type net/http_test.eofReaderFunc implements Reader
  • struct type net/http_test.errorReader implements Reader
  • struct type net/http_test.fakeFile implements Reader
  • struct type net/http_test.funcConn implements Reader
  • struct type net/http_test.issue12991File implements Reader
  • struct type net/http_test.issue18239Body implements Reader
  • basic type net/http_test.neverEnding implements Reader
  • struct type net/http_test.noteCloseConn implements Reader
  • struct type net/http_test.panicOnSeek implements Reader
  • struct type net/http_test.rwTestConn implements Reader
  • struct type net/http_test.slurpResult implements Reader
  • struct type net/http_test.testCloseConn implements Reader
  • struct type net/http_test.testErrorReader implements Reader
  • struct type net/http_test.writeCountingConn implements Reader
  • struct type net/http_test.writerFuncConn implements Reader
  • struct type net/rpc/jsonrpc.pipe implements Reader
  • struct type net/smtp.faker implements Reader
  • struct type os/exec.closeOnce implements Reader
  • struct type os/exec_test.delayedInfiniteReader implements Reader
  • basic type os_test.neverEnding implements Reader
  • struct type text/scanner.errReader implements Reader
  • interface type archive/tar.fileReader implements Reader
  • interface type cmd/pack.FileLike implements Reader
  • interface type compress/flate.Reader implements Reader
  • interface type fmt.ScanState implements Reader
  • interface type image.reader implements Reader
  • interface type image/gif.reader implements Reader
  • interface type image/jpeg.Reader implements Reader
  • interface type ReadCloser implements Reader
  • interface type ReadSeeker implements Reader
  • interface type ReadWriteCloser implements Reader
  • interface type ReadWriteSeeker implements Reader
  • interface type ReadWriter implements Reader
  • interface type mime/multipart.File implements Reader
  • interface type net.Conn implements Reader
  • interface type net/http.File implements Reader
  • interface type net/http.http2pipeBuffer implements Reader

Writerのimplements一覧

WriterはReaderに比べると少ないです。

  • pointer type *archive/tar.Writer implements Writer
  • pointer type *archive/tar.failOnceWriter implements Writer
  • pointer type *archive/tar.regFileWriter implements Writer
  • pointer type *archive/tar.sparseFileWriter implements Writer
  • pointer type *archive/tar.testFile implements Writer
  • pointer type *archive/zip.countWriter implements Writer
  • pointer type *archive/zip.fileWriter implements Writer
  • pointer type *archive/zip.pooledFlateWriter implements Writer
  • pointer type *archive/zip.rleBuffer implements Writer
  • pointer type *archive/zip.suffixSaver implements Writer
  • pointer type *bufio.Writer implements Writer
  • pointer type *bufio_test.writeCountingDiscard implements Writer
  • pointer type *bytes.Buffer implements Writer
  • pointer type *cmd/compile/internal/gc.dumper implements Writer
  • pointer type *cmd/compile/internal/gc.intWriter implements Writer
  • pointer type *cmd/compile/internal/syntax.dumper implements Writer
  • pointer type *cmd/go/internal/cache.Hash implements Writer
  • pointer type *cmd/go/internal/help.commentWriter implements Writer
  • pointer type *cmd/go/internal/help.errWriter implements Writer
  • pointer type *cmd/go/internal/list.TrackingWriter implements Writer
  • pointer type *cmd/go/internal/modfile.printer implements Writer
  • pointer type *cmd/internal/test2json.converter implements Writer
  • pointer type *cmd/link/internal/ld.OutBuf implements Writer
  • pointer type *cmd/test2json.countWriter implements Writer
  • pointer type *cmd/trace.countingWriter implements Writer
  • pointer type *cmd/vendor/golang.org/x/crypto/ssh/terminal.MockTerminal implements Writer
  • pointer type *cmd/vendor/golang.org/x/crypto/ssh/terminal.Terminal implements Writer
  • pointer type *compress/flate.Writer implements Writer
  • pointer type *compress/flate.dictWriter implements Writer
  • pointer type *compress/flate.errorWriter implements Writer
  • pointer type *compress/flate.failWriter implements Writer
  • pointer type *compress/flate.syncBuffer implements Writer
  • pointer type *compress/gzip.Writer implements Writer
  • pointer type *compress/gzip.limitedWriter implements Writer
  • pointer type *compress/lzw.encoder implements Writer
  • pointer type *compress/lzw.errWriteCloser implements Writer
  • pointer type *compress/zlib.Writer implements Writer
  • pointer type *crypto/hmac.hmac implements Writer
  • pointer type *crypto/md5.digest implements Writer
  • pointer type *crypto/sha1.digest implements Writer
  • pointer type *crypto/sha256.digest implements Writer
  • pointer type *crypto/sha512.digest implements Writer
  • pointer type *crypto/tls.Conn implements Writer
  • pointer type *crypto/tls.brokenConn implements Writer
  • pointer type *crypto/tls.changeImplConn implements Writer
  • pointer type *crypto/tls.cthWrapper implements Writer
  • pointer type *crypto/tls.finishedHash implements Writer
  • pointer type *crypto/tls.opensslOutputSink implements Writer
  • pointer type *crypto/tls.recordingConn implements Writer
  • pointer type *crypto/tls.slowConn implements Writer
  • pointer type *crypto/tls.writeCountingConn implements Writer
  • pointer type *encoding/ascii85.encoder implements Writer
  • pointer type *encoding/base32.encoder implements Writer
  • pointer type *encoding/base64.encoder implements Writer
  • pointer type *encoding/gob.encBuffer implements Writer
  • pointer type *encoding/hex.dumper implements Writer
  • pointer type *encoding/hex.encoder implements Writer
  • pointer type *encoding/json.encodeState implements Writer
  • pointer type *encoding/pem.lineBreaker implements Writer
  • pointer type *encoding/xml.limitedBytesWriter implements Writer
  • pointer type *fmt.pp implements Writer
  • pointer type *go/ast.printer implements Writer
  • pointer type *go/printer.limitWriter implements Writer
  • pointer type *go/printer.trimmer implements Writer
  • pointer type *go/types_test.gen implements Writer
  • pointer type *hash/adler32.digest implements Writer
  • pointer type *hash/crc32.digest implements Writer
  • pointer type *hash/crc64.digest implements Writer
  • pointer type *hash/fnv.sum128 implements Writer
  • pointer type *hash/fnv.sum128a implements Writer
  • pointer type *hash/fnv.sum32 implements Writer
  • pointer type *hash/fnv.sum32a implements Writer
  • pointer type *hash/fnv.sum64 implements Writer
  • pointer type *hash/fnv.sum64a implements Writer
  • pointer type *image/png.encoder implements Writer
  • pointer type *internal/poll.FD implements Writer
  • pointer type *internal/trace.Writer implements Writer
  • pointer type *internal/x/net/http2/hpack.Decoder implements Writer
  • pointer type *internal/x/text/transform.Writer implements Writer
  • pointer type *internal/x/text/unicode/norm.normWriter implements Writer
  • pointer type *PipeWriter implements Writer
  • pointer type *multiWriter implements Writer
  • pointer type *pipe implements Writer
  • pointer type *io_test.Buffer implements Writer
  • pointer type *io_test.dataAndErrorBuffer implements Writer
  • pointer type *io_test.noReadFrom implements Writer
  • pointer type *io_test.writeStringChecker implements Writer
  • pointer type *io_test.writeToChecker implements Writer
  • pointer type *log/syslog.Writer implements Writer
  • pointer type *mime/multipart.part implements Writer
  • pointer type *mime/quotedprintable.Writer implements Writer
  • pointer type *net.IPConn implements Writer
  • pointer type *net.TCPConn implements Writer
  • pointer type *net.UDPConn implements Writer
  • pointer type *net.UnixConn implements Writer
  • pointer type *net.conn implements Writer
  • pointer type *net.fakeDNSConn implements Writer
  • pointer type *net.fakeDNSPacketConn implements Writer
  • pointer type *net.netFD implements Writer
  • pointer type *net.pipe implements Writer
  • pointer type *net/http.chunkWriter implements Writer
  • pointer type *net/http.countingWriter implements Writer
  • pointer type *net/http.http2bufferedWriter implements Writer
  • pointer type *net/http.http2dataBuffer implements Writer
  • pointer type *net/http.http2pipe implements Writer
  • pointer type *net/http.http2responseWriter implements Writer
  • pointer type *net/http.loggingConn implements Writer
  • pointer type *net/http.populateResponse implements Writer
  • pointer type *net/http.response implements Writer
  • pointer type *net/http.timeoutWriter implements Writer
  • pointer type *net/http/cgi.customWriterRecorder implements Writer
  • pointer type *net/http/cgi.limitWriter implements Writer
  • pointer type *net/http/cgi.response implements Writer
  • pointer type *net/http/fcgi.response implements Writer
  • pointer type *net/http/fcgi.streamWriter implements Writer
  • pointer type *net/http/fcgi.writeOnlyConn implements Writer
  • pointer type *net/http/httptest.ResponseRecorder implements Writer
  • pointer type *net/http/httputil.maxLatencyWriter implements Writer
  • pointer type *net/http/internal.chunkedWriter implements Writer
  • pointer type *net/http_test.lockedBytesBuffer implements Writer
  • pointer type *net/http_test.logWritesConn implements Writer
  • pointer type *net/http_test.slowTestConn implements Writer
  • pointer type *net/http_test.testConn implements Writer
  • pointer type *net/http_test.writeCountingConn implements Writer
  • pointer type *net/textproto.dotWriter implements Writer
  • pointer type *os.File implements Writer
  • pointer type *os/exec.prefixSuffixSaver implements Writer
  • pointer type *os/exec_test.badWriter implements Writer
  • pointer type *strings.Builder implements Writer
  • pointer type *strings.appendSliceWriter implements Writer
  • pointer type *testing/iotest.truncateWriter implements Writer
  • pointer type *testing/iotest.writeLogger implements Writer
  • pointer type *text/tabwriter.Writer implements Writer
  • pointer type *text/tabwriter_test.buffer implements Writer
  • struct type archive/tar.testNonEmptyWriter implements Writer
  • struct type archive/tar.zeroWriter implements Writer
  • struct type archive/zip.dirWriter implements Writer
  • struct type archive/zip.fakeHash32 implements Writer
  • struct type archive/zip.nopCloser implements Writer
  • struct type bufio.ReadWriter implements Writer
  • struct type bufio_test.errorReaderFromTest implements Writer
  • struct type bufio_test.errorWriterTest implements Writer
  • struct type bufio_test.errorWriterToTest implements Writer
  • struct type bufio_test.onlyWriter implements Writer
  • struct type bytes_test.justWriter implements Writer
  • struct type cmd/go/internal/lockedfile.File implements Writer
  • struct type cmd/go/internal/lockedfile.osFile implements Writer
  • struct type cmd/go/internal/modfetch/codehost.deleteCloser implements Writer
  • struct type cmd/go/internal/test.lockedStdout implements Writer
  • struct type cmd/internal/bio.Writer implements Writer
  • struct type cmd/internal/bio.mustWriter implements Writer
  • struct type cmd/vendor/github.com/google/pprof/internal/graph.builder implements Writer
  • struct type crypto/cipher.StreamWriter implements Writer
  • struct type crypto/tls.hairpinConn implements Writer
  • struct type encoding/csv.errorWriter implements Writer
  • struct type encoding/xml.errWriter implements Writer
  • struct type encoding/xml.printer implements Writer
  • struct type image/gif.blockWriter implements Writer
  • basic type io/ioutil.devNull implements Writer
  • struct type io_test.errWriter implements Writer
  • struct type io_test.simpleWriter implements Writer
  • signature type io_test.writerFunc implements Writer
  • struct type net.dialResult implements Writer
  • struct type net.writerOnly implements Writer
  • struct type net/http.bufioFlushWriter implements Writer
  • struct type net/http.checkConnErrorWriter implements Writer
  • struct type net/http.connCloseListener implements Writer
  • struct type net/http.dumpConn implements Writer
  • map type net/http.headerOnlyResponseWriter implements Writer
  • struct type net/http.http2chunkWriter implements Writer
  • struct type net/http.http2stickyErrWriter implements Writer
  • struct type net/http.persistConnWriter implements Writer
  • struct type net/http.readWriteCloserBody implements Writer
  • struct type net/http.socksConn implements Writer
  • signature type net/http.writerFunc implements Writer
  • struct type net/http.writerOnly implements Writer
  • struct type net/http/fcgi.bufWriter implements Writer
  • struct type net/http/fcgi.nilCloser implements Writer
  • struct type net/http/fcgi.nopWriteCloser implements Writer
  • struct type net/http/fcgi.rwNopCloser implements Writer
  • struct type net/http/httputil.dumpConn implements Writer
  • struct type net/http/internal.FlushAfterChunkWriter implements Writer
  • struct type net/http_test.blockingRemoteAddrConn implements Writer
  • chan type net/http_test.chanWriter implements Writer
  • struct type net/http_test.closeWriteTestConn implements Writer
  • struct type net/http_test.funcConn implements Writer
  • signature type net/http_test.funcWriter implements Writer
  • struct type net/http_test.http09Writer implements Writer
  • struct type net/http_test.logWrites implements Writer
  • struct type net/http_test.noteCloseConn implements Writer
  • struct type net/http_test.responseWriterJustWriter implements Writer
  • struct type net/http_test.rwTestConn implements Writer
  • struct type net/http_test.terrorWriter implements Writer
  • struct type net/http_test.testCloseConn implements Writer
  • struct type net/http_test.writerFuncConn implements Writer
  • struct type net/rpc.writeCrasher implements Writer
  • struct type net/rpc/jsonrpc.pipe implements Writer
  • struct type net/smtp.dataCloser implements Writer
  • struct type net/smtp.faker implements Writer
  • struct type os/exec.closeOnce implements Writer
  • struct type strings_test.errWriter implements Writer
  • struct type testing.discard implements Writer
  • signature type testing.funcWriter implements Writer
  • struct type testing.indenter implements Writer
  • struct type text/tabwriter_test.panicWriter implements Writer
  • basic type text/template.ErrorWriter implements Writer
  • interface type archive/tar.fileWriter implements Writer
  • interface type cmd/compile/internal/ssa.writeSyncer implements Writer
  • interface type cmd/link/internal/wasm.nameWriter implements Writer
  • interface type crypto/tls.constantTimeHash implements Writer
  • interface type fmt.State implements Writer
  • interface type hash.Hash implements Writer
  • interface type hash.Hash32 implements Writer
  • interface type hash.Hash64 implements Writer
  • interface type image/gif.writer implements Writer
  • interface type image/jpeg.writer implements Writer
  • interface type ReadWriteCloser implements Writer
  • interface type ReadWriteSeeker implements Writer
  • interface type ReadWriter implements Writer
  • interface type WriteCloser implements Writer
  • interface type WriteSeeker implements Writer
  • interface type net.Conn implements Writer
  • interface type net/http.ResponseWriter implements Writer
  • interface type net/http.http2pipeBuffer implements Writer
  • interface type net/http/httputil.writeFlusher implements Writer

ioパッケージのパブリックメソッドを叩いてみる

ioパッケージにはインターフェース以外に実装されている関数があるので叩いてみました。

WriteString

writerに文字列を書き込む

func WriteString() string {
    file, _ := os.Create("testdata/src.txt")
    _, _ = io.WriteString(file, "0123456789")
    b, _ := ioutil.ReadFile("testdata/src.txt")
    return string(b)
}
WriteStringのテスト
func TestWriteString(t *testing.T) {
    str := WriteString()
    if str != "0123456789" {
        t.Errorf("WriteString Error %s", str)
    }
}

ReadAtLeast

指定した値は最低限読み込みバッファー分すべて読み込む(パッケージ内部では使われていますが結構ニッチな機能)

func ReadAtLeast(b int, min int) (string, error) {
    file, _ := os.Open("testdata/src.txt")
    buf := make([]byte, b)
    n, err := io.ReadAtLeast(file, buf, min)
    return string(buf[:n]), err
}
ReadAtLeastのテスト
func TestReadAtLeast(t *testing.T) {
    str, _ := ReadAtLeast(5, 2)
    if str != "01234" {
        t.Errorf("TestReadAtLeast Error %s", str)
    }
}

確保するバッファーよりも最低限読み込むバッファーの方が大きい場合はshort bufferエラーとなる

func TestReadAtLeast_shortBuffer(t *testing.T) {
    _, err := ReadAtLeast(1, 2)
    if err.Error() != "short buffer" {
        t.Errorf("TestReadAtLeast Error %s", err.Error())
    }
}

読み込む対象のバッファーより最低限読み込むバッファーの方が大きい場合はunexpected EOFエラーがとなる

func TestReadAtLeast_unexpectedEOF(t *testing.T) {
    _, err := ReadAtLeast(20, 15)
    if err.Error() != "unexpected EOF" {
        t.Errorf("TestReadAtLeast Error %s", err.Error())
    }
}

ReadFull

指定したバッファー分すべて読み込む

func ReadFull() string {
    file, _ := os.Open("testdata/src.txt")
    buf := make([]byte, 5)
    n, _ := io.ReadFull(file, buf)
    return string(buf[:n])
}
ReadFullのテスト
func TestReadFull(t *testing.T) {
    str := ReadFull()
    if str != "01234" {
        t.Errorf("TestReadFull Error %s", str)
    }
}

CopyN

writerへ指定した値をコピーする

func CopyN() string {
    srcFile, _ := os.Open("testdata/src.txt")
    dstFile, _ := os.Create("testdata/dst.txt")
    written, _ := io.CopyN(dstFile, srcFile, 5)
    file, _ := os.Open("testdata/dst.txt")
    buf := make([]byte, written)
    n, _ := file.Read(buf)
    return string(buf[:n])
}
CopyNのテスト
func TestCopyN(t *testing.T) {
    str := CopyN()
    if str != "01234" {
        t.Errorf("TestCopyN Error %s", str)
    }
}

Copy

readerをwriterにコピーする

func Copy() string {
    srcFile, _ := os.Open("testdata/src.txt")
    dstFile, _ := os.Create("testdata/dst.txt")
    written, _ := io.Copy(dstFile, srcFile)
    buf := make([]byte, written)
    file, _ := os.Open("testdata/dst.txt")
    n, _ := file.Read(buf)
    return string(buf[:n])
}
Copyのテスト
func TestCopy(t *testing.T) {
    str := Copy()
    if str != "0123456789" {
        t.Errorf("TestCopy Error %s", str)
    }
}

CopyBuffer

readerをwriterに指定したバッファー分コピーする

func CopyBuffer() string {
    srcFile, _ := os.Open("testdata/src.txt")
    dstFile, _ := os.Create("testdata/dst.txt")
    written, _ := io.CopyBuffer(dstFile, srcFile, make([]byte, 5))
    buf := make([]byte, written)
    file, _ := os.Open("testdata/dst.txt")
    n, _ := file.Read(buf)
    return string(buf[:n])
}
CopyBufferのテスト
func TestCopyBuffer(t *testing.T) {
    str := CopyBuffer()
    if str != "0123456789" {
        t.Errorf("TestCopyBuffer Error %s", str)
    }
}

LimitReaderRead

値を制限したreaderを取得する

func LimitReaderRead() string {
    srcFile, _ := os.Open("testdata/src.txt")
    limitedReader := io.LimitedReader{srcFile, 5}
    buf := make([]byte, 3)
    n, _ := limitedReader.Read(buf)
    return string(buf[:n])
}

値を制限したreaderを取得し読み込む

func LimitReaderRead2() string {
    srcFile, _ := os.Open("testdata/src.txt")
    limitedReader := io.LimitedReader{srcFile, 5}
    buf := make([]byte, 8)
    n, _ := limitedReader.Read(buf)
    return string(buf[:n])
}
LimitReaderReadのテスト
func TestLimitReaderRead(t *testing.T) {
    str := LimitReaderRead()
    if str != "012" {
        t.Errorf("TestLimitReaderRead Error %s" , str)
    }
}
func TestLimitReaderRead2(t *testing.T) {
    str := LimitReaderRead2()
    if str != "01234" {
        t.Errorf("TestLimitReaderRead Error %s" , str)
    }
}

SectionReaderRead

指定した値でセクション分けしたreaderを取得し読み込む

func SectionReaderRead() string {
    file, _ := os.Open("testdata/src.txt")
    sectionReader := io.NewSectionReader(file, 3, 5)
    buf := make([]byte, 3)
    n, _ := sectionReader.Read(buf)
    return string(buf[:n])
}
SectionReaderReadのテスト
func TestSectionReaderRead(t *testing.T) {
    str := SectionReaderRead()
    if str != "345" {
        t.Errorf("TestSectionReaderRead Error %s", str)
    }
}

SectionReaderSeek

セクションリーダーの読み込み位置を変更する

func SectionReaderSeek() string {
    file, _ := os.Open("testdata/src.txt")
    sectionReader := io.NewSectionReader(file, 5, 10)
    buf := make([]byte, 3)
    n, _ := sectionReader.Read(buf)
    _, _ = sectionReader.Seek(0, 0)
    return string(buf[:n])
}
SectionReaderSeekのテスト
func TestSectionReaderSeek(t *testing.T) {
    str := SectionReaderSeek()
    if str != "567" {
        t.Errorf("TestSectionReaderSeek Error %s", str)
    }
}

SectionReaderReadAt

セクションリーダーを指定した位置から読み込む

func SectionReaderReadAt() string {
    file, _ := os.Open("testdata/src.txt")
    sectionReader := io.NewSectionReader(file, 5, 10)
    buf := make([]byte, 3)
    n, _ := sectionReader.ReadAt(buf, 2)
    return string(buf[:n])
}

SectionReaderReadAtのテスト

func TestSectionReaderReadAt(t *testing.T) {
    str := SectionReaderReadAt()
    if str != "789" {
        t.Errorf("TestSectionReaderReadAt Error %s", str)
    }
}

SectionReaderSize

セクションリーダーのサイズを取得する

func SectionReaderSize() int64 {
    file, _ := os.Open("testdata/src.txt")
    sectionReader := io.NewSectionReader(file, 5, 9)
    return sectionReader.Size()
}
SectionReaderSizeのテスト
func TestSectionReaderSize(t *testing.T) {
    size := SectionReaderSize()
    if size != 9 {
        t.Errorf("TestSectionReaderSize Error %d", size)
    }
}

TeeReaderRead

readerとwriterを渡しておいて読み込んだら同時にwriterにも書き込む

func TeeReaderRead() string {
    srcFile, _ := os.Open("testdata/src.txt")
    dstFile, _ := os.Create("testdata/dst.txt")
    teeReader := io.TeeReader(srcFile, dstFile)
    buf := make([]byte, 3)
    _, _ = teeReader.Read(buf)
    dstFile2, _ := os.Open("testdata/dst.txt")
    n, _ := dstFile2.Read(buf)
    return string(buf[:n])
}
TeeReaderReadのテスト
func TestTeeReaderRead(t *testing.T) {
    str := TeeReaderRead()
    if str != "012" {
        t.Errorf("TestTeeReaderRead Error %s", str)
    }
}

※ 他にもMultiWriterPipeもありますが省略してます

ソースコード

本記事のソースコード

taisa831/sandbox-go

You can’t perform that action at this time. You signed in with another tab or window. You signed out in another tab or window. Reload to refresh your session. Reload to refresh your session.

コピペ実行用ソース

以下をファイルにコピペすればすぐ実行できます

実装

package io
import (
    "io"
    "io/ioutil"
    "os"
)
// writerに文字列を書き込む
func WriteString() string {
    file, _ := os.Create("testdata/src.txt")
    _, _ = io.WriteString(file, "0123456789")
    b, _ := ioutil.ReadFile("testdata/src.txt")
    return string(b)
}
// 指定した値は最低限読み込みバッファー分すべて読み込む
func ReadAtLeast(b int, min int) (string, error) {
    file, _ := os.Open("testdata/src.txt")
    buf := make([]byte, b)
    n, err := io.ReadAtLeast(file, buf, min)
    return string(buf[:n]), err
}
// 指定したバッファー分すべて読み込む
func ReadFull() string {
    file, _ := os.Open("testdata/src.txt")
    buf := make([]byte, 5)
    n, _ := io.ReadFull(file, buf)
    return string(buf[:n])
}
// writerへ指定した値をコピーする
func CopyN() string {
    srcFile, _ := os.Open("testdata/src.txt")
    dstFile, _ := os.Create("testdata/dst.txt")
    written, _ := io.CopyN(dstFile, srcFile, 5)
    file, _ := os.Open("testdata/dst.txt")
    buf := make([]byte, written)
    n, _ := file.Read(buf)
    return string(buf[:n])
}
// readerをwriterにコピーする
func Copy() string {
    srcFile, _ := os.Open("testdata/src.txt")
    dstFile, _ := os.Create("testdata/dst.txt")
    written, _ := io.Copy(dstFile, srcFile)
    buf := make([]byte, written)
    file, _ := os.Open("testdata/dst.txt")
    n, _ := file.Read(buf)
    return string(buf[:n])
}
// readerをwriterに指定したバッファー分コピーする
func CopyBuffer() string {
    srcFile, _ := os.Open("testdata/src.txt")
    dstFile, _ := os.Create("testdata/dst.txt")
    written, _ := io.CopyBuffer(dstFile, srcFile, make([]byte, 5))
    buf := make([]byte, written)
    file, _ := os.Open("testdata/dst.txt")
    n, _ := file.Read(buf)
    return string(buf[:n])
}
// 値を制限したreaderを取得する
func LimitReaderRead() string {
    srcFile, _ := os.Open("testdata/src.txt")
    limitedReader := io.LimitedReader{srcFile, 5}
    buf := make([]byte, 3)
    n, _ := limitedReader.Read(buf)
    return string(buf[:n])
}
// 値を制限したreaderを取得し読み込む
func LimitReaderRead2() string {
    srcFile, _ := os.Open("testdata/src.txt")
    limitedReader := io.LimitedReader{srcFile, 5}
    buf := make([]byte, 8)
    n, _ := limitedReader.Read(buf)
    return string(buf[:n])
}
// 指定した値でセクション分けしたreaderを取得し読み込む
func SectionReaderRead() string {
    file, _ := os.Open("testdata/src.txt")
    sectionReader := io.NewSectionReader(file, 3, 5)
    buf := make([]byte, 3)
    n, _ := sectionReader.Read(buf)
    return string(buf[:n])
}
// セクションリーダーの読み込み位置を変更する
func SectionReaderSeek() string {
    file, _ := os.Open("testdata/src.txt")
    sectionReader := io.NewSectionReader(file, 5, 10)
    buf := make([]byte, 3)
    n, _ := sectionReader.Read(buf)
    _, _ = sectionReader.Seek(0, 0)
    return string(buf[:n])
}
// セクションリーダーを指定した位置から読み込む
func SectionReaderReadAt() string {
    file, _ := os.Open("testdata/src.txt")
    sectionReader := io.NewSectionReader(file, 5, 10)
    buf := make([]byte, 3)
    n, _ := sectionReader.ReadAt(buf, 2)
    return string(buf[:n])
}
// セクションリーダーのサイズを取得する
func SectionReaderSize() int64 {
    file, _ := os.Open("testdata/src.txt")
    sectionReader := io.NewSectionReader(file, 5, 9)
    return sectionReader.Size()
}
// readerとwriterを渡しておいて読み込んだら同時にwriterにも書き込む
func TeeReaderRead() string {
    srcFile, _ := os.Open("testdata/src.txt")
    dstFile, _ := os.Create("testdata/dst.txt")
    teeReader := io.TeeReader(srcFile, dstFile)
    buf := make([]byte, 3)
    _, _ = teeReader.Read(buf)
    dstFile2, _ := os.Open("testdata/dst.txt")
    n, _ := dstFile2.Read(buf)
    return string(buf[:n])
}

テスト

package io
import (
    "testing"
)
func TestWriteString(t *testing.T) {
    str := WriteString()
    if str != "0123456789" {
        t.Errorf("WriteString Error %s", str)
    }
}
func TestReadAtLeast(t *testing.T) {
    str, _ := ReadAtLeast(5, 2)
    if str != "01234" {
        t.Errorf("TestReadAtLeast Error %s", str)
    }
}
func TestReadAtLeast_shortBuffer(t *testing.T) {
    _, err := ReadAtLeast(1, 2)
    if err.Error() != "short buffer" {
        t.Errorf("TestReadAtLeast Error %s", err.Error())
    }
}
func TestReadAtLeast_unexpectedEOF(t *testing.T) {
    _, err := ReadAtLeast(20, 15)
    if err.Error() != "unexpected EOF" {
        t.Errorf("TestReadAtLeast Error %s", err.Error())
    }
}
func TestReadFull(t *testing.T) {
    str := ReadFull()
    if str != "01234" {
        t.Errorf("TestReadFull Error %s", str)
    }
}
func TestCopyN(t *testing.T) {
    str := CopyN()
    if str != "01234" {
        t.Errorf("TestCopyN Error %s", str)
    }
}
func TestCopy(t *testing.T) {
    str := Copy()
    if str != "0123456789" {
        t.Errorf("TestCopy Error %s", str)
    }
}
func TestCopyBuffer(t *testing.T) {
    str := CopyBuffer()
    if str != "0123456789" {
        t.Errorf("TestCopyBuffer Error %s", str)
    }
}
func TestLimitReaderRead(t *testing.T) {
    str := LimitReaderRead()
    if str != "012" {
        t.Errorf("TestLimitReaderRead Error %s" , str)
    }
}
func TestLimitReaderRead2(t *testing.T) {
    str := LimitReaderRead2()
    if str != "01234" {
        t.Errorf("TestLimitReaderRead Error %s" , str)
    }
}
func TestSectionReaderRead(t *testing.T) {
    str := SectionReaderRead()
    if str != "345" {
        t.Errorf("TestSectionReaderRead Error %s", str)
    }
}
func TestSectionReaderSeek(t *testing.T) {
    str := SectionReaderSeek()
    if str != "567" {
        t.Errorf("TestSectionReaderSeek Error %s", str)
    }
}
func TestSectionReaderReadAt(t *testing.T) {
    str := SectionReaderReadAt()
    if str != "789" {
        t.Errorf("TestSectionReaderReadAt Error %s", str)
    }
}
func TestSectionReaderSize(t *testing.T) {
    size := SectionReaderSize()
    if size != 9 {
        t.Errorf("TestSectionReaderSize Error %d", size)
    }
}
func TestTeeReaderRead(t *testing.T) {
    str := TeeReaderRead()
    if str != "012" {
        t.Errorf("TestTeeReaderRead Error %s", str)
    }
}