Skip to content

Instantly share code, notes, and snippets.

@xin053
Created September 5, 2019 11:54
Show Gist options
  • Save xin053/eaedbea910bedb69dd86d6545fa7b0a6 to your computer and use it in GitHub Desktop.
Save xin053/eaedbea910bedb69dd86d6545fa7b0a6 to your computer and use it in GitHub Desktop.
[go 标准库 sync] go 标准库 sync #go #标准库 #sync
package main

import (
	"bytes"
	"io"
	"os"
	"sync"
	"time"
)

var bufPool = sync.Pool{
	New: func() interface{} {
		// The Pool's New function should generally only return pointer
		// types, since a pointer can be put into the return interface
		// value without an allocation:
		return new(bytes.Buffer)
	},
}

// timeNow is a fake version of time.Now for tests.
func timeNow() time.Time {
	return time.Unix(1136214245, 0)
}

func Log(w io.Writer, key, val string) {
	b := bufPool.Get().(*bytes.Buffer)
	b.Reset()
	// Replace this with time.Now() in a real logger.
	b.WriteString(timeNow().UTC().Format(time.RFC3339))
	b.WriteByte(' ')
	b.WriteString(key)
	b.WriteByte('=')
	b.WriteString(val)
	w.Write(b.Bytes())
	bufPool.Put(b)
}

func main() {
	Log(os.Stdout, "path", "/search?q=flowers")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment