github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/talks/2014/research2/addr1.go (about)

     1  // +build OMIT
     2  
     3  package main
     4  
     5  import (
     6  	"fmt"
     7  	"math/rand"
     8  	"time"
     9  )
    10  
    11  func lookup() {
    12  	for _, w := range worklist {
    13  		w.addrs, w.err = LookupHost(w.host)
    14  	}
    15  }
    16  
    17  func main() {
    18  	rand.Seed(time.Now().UnixNano())
    19  
    20  	t0 := time.Now()
    21  	lookup()
    22  
    23  	fmt.Printf("\n")
    24  	for _, w := range worklist {
    25  		if w.err != nil {
    26  			fmt.Printf("%s: error: %v\n", w.host, w.err)
    27  			continue
    28  		}
    29  		fmt.Printf("%s: %v\n", w.host, w.addrs)
    30  	}
    31  	fmt.Printf("total lookup time: %.3f seconds\n", time.Since(t0).Seconds())
    32  }
    33  
    34  var worklist = []*Work{
    35  	{host: "fast.com"},
    36  	{host: "slow.com"},
    37  	{host: "fast.missing.com"},
    38  	{host: "slow.missing.com"},
    39  }
    40  
    41  type Work struct {
    42  	host  string
    43  	addrs []string
    44  	err   error
    45  }
    46  
    47  func LookupHost(name string) (addrs []string, err error) {
    48  	t0 := time.Now()
    49  	defer func() {
    50  		fmt.Printf("lookup %s: %.3f seconds\n", name, time.Since(t0).Seconds())
    51  	}()
    52  	h := hosts[name]
    53  	if h == nil {
    54  		h = failure
    55  	}
    56  	return h(name)
    57  }
    58  
    59  type resolver func(string) ([]string, error)
    60  
    61  var hosts = map[string]resolver{
    62  	"fast.com":         delay(10*time.Millisecond, fixedAddrs("10.0.0.1")),
    63  	"slow.com":         delay(2*time.Second, fixedAddrs("10.0.0.4")),
    64  	"fast.missing.com": delay(10*time.Millisecond, failure),
    65  	"slow.missing.com": delay(2*time.Second, failure),
    66  }
    67  
    68  func fixedAddrs(addrs ...string) resolver {
    69  	return func(string) ([]string, error) {
    70  		return addrs, nil
    71  	}
    72  }
    73  
    74  func delay(d time.Duration, f resolver) resolver {
    75  	return func(name string) ([]string, error) {
    76  		time.Sleep(d/2 + time.Duration(rand.Int63n(int64(d/2))))
    77  		return f(name)
    78  	}
    79  }
    80  
    81  func failure(name string) ([]string, error) {
    82  	return nil, fmt.Errorf("unknown host %v", name)
    83  }