github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/talks/2015/go4cpp/mock.go (about)

     1  // +build OMIT
     2  
     3  package main
     4  
     5  import (
     6  	"fmt"
     7  	"io"
     8  	"log"
     9  	"net"
    10  	"strings"
    11  )
    12  
    13  func CheckPassword(c net.Conn) error {
    14  	// read a password from the connection
    15  	buf := make([]byte, 256)
    16  	n, err := c.Read(buf)
    17  	if err != nil {
    18  		return fmt.Errorf("read: %v", err)
    19  	}
    20  
    21  	// check it's correct
    22  	got := string(buf[:n])
    23  	if got != "password" {
    24  		return fmt.Errorf("wrong password")
    25  	}
    26  	return nil
    27  }
    28  
    29  type fakeConn struct {
    30  	net.Conn
    31  	r io.Reader
    32  }
    33  
    34  func (c fakeConn) Read(b []byte) (int, error) {
    35  	return c.r.Read(b)
    36  }
    37  
    38  // end_fake OMIT
    39  
    40  func main() {
    41  	c := fakeConn{
    42  		r: strings.NewReader("foo"),
    43  	}
    44  	err := CheckPassword(c)
    45  	if err == nil {
    46  		log.Println("expected error using wrong password")
    47  	} else {
    48  		log.Println("OK")
    49  	}
    50  }