...

Source file src/sync/example_pool_test.go

Documentation: sync

		 1  // Copyright 2016 The Go Authors. All rights reserved.
		 2  // Use of this source code is governed by a BSD-style
		 3  // license that can be found in the LICENSE file.
		 4  
		 5  package sync_test
		 6  
		 7  import (
		 8  	"bytes"
		 9  	"io"
		10  	"os"
		11  	"sync"
		12  	"time"
		13  )
		14  
		15  var bufPool = sync.Pool{
		16  	New: func() interface{} {
		17  		// The Pool's New function should generally only return pointer
		18  		// types, since a pointer can be put into the return interface
		19  		// value without an allocation:
		20  		return new(bytes.Buffer)
		21  	},
		22  }
		23  
		24  // timeNow is a fake version of time.Now for tests.
		25  func timeNow() time.Time {
		26  	return time.Unix(1136214245, 0)
		27  }
		28  
		29  func Log(w io.Writer, key, val string) {
		30  	b := bufPool.Get().(*bytes.Buffer)
		31  	b.Reset()
		32  	// Replace this with time.Now() in a real logger.
		33  	b.WriteString(timeNow().UTC().Format(time.RFC3339))
		34  	b.WriteByte(' ')
		35  	b.WriteString(key)
		36  	b.WriteByte('=')
		37  	b.WriteString(val)
		38  	w.Write(b.Bytes())
		39  	bufPool.Put(b)
		40  }
		41  
		42  func ExamplePool() {
		43  	Log(os.Stdout, "path", "/search?q=flowers")
		44  	// Output: 2006-01-02T15:04:05Z path=/search?q=flowers
		45  }
		46  

View as plain text