github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/talks/2013/bestpractices/shortercode6.go (about)

     1  // +build OMIT
     2  
     3  package main
     4  
     5  import (
     6  	"bytes"
     7  	"encoding/binary"
     8  	"io"
     9  	"log"
    10  	"os"
    11  )
    12  
    13  type Gopher struct {
    14  	Name     string
    15  	AgeYears int
    16  }
    17  
    18  type binWriter struct {
    19  	w   io.Writer
    20  	buf bytes.Buffer // HL
    21  	err error
    22  }
    23  
    24  // Write writes a value to the provided writer in little endian form.
    25  func (w *binWriter) Write(v interface{}) {
    26  	if w.err != nil {
    27  		return
    28  	}
    29  	switch x := v.(type) {
    30  	case string:
    31  		w.Write(int32(len(x)))
    32  		w.Write([]byte(x))
    33  	case int:
    34  		w.Write(int64(x))
    35  	default:
    36  		w.err = binary.Write(&w.buf, binary.LittleEndian, v) // HL
    37  	}
    38  }
    39  
    40  // Flush writes any pending values into the writer if no error has occurred.
    41  // If an error has occurred, earlier or with a write by Flush, the error is
    42  // returned.
    43  func (w *binWriter) Flush() (int64, error) {
    44  	if w.err != nil {
    45  		return 0, w.err
    46  	}
    47  	return w.buf.WriteTo(w.w)
    48  }
    49  
    50  func (g *Gopher) WriteTo(w io.Writer) (int64, error) {
    51  	bw := &binWriter{w: w}
    52  	bw.Write(g.Name)
    53  	bw.Write(g.AgeYears)
    54  	return bw.Flush() // HL
    55  }
    56  
    57  func main() {
    58  	g := &Gopher{
    59  		Name:     "Gophertiti",
    60  		AgeYears: 3382,
    61  	}
    62  
    63  	if _, err := g.WriteTo(os.Stdout); err != nil {
    64  		log.Printf("DumpBinary: %v\n", err)
    65  	}
    66  }