code
stringlengths
10
1.34M
language
stringclasses
1 value
// +build OMIT package main import ( "fmt" "time" ) // STARTMAIN1 OMIT type Ball struct{ hits int } func main() { table := make(chan *Ball) go player("ping", table) go player("pong", table) table <- new(Ball) // game on; toss the ball time.Sleep(1 * time.Second) <-table // game over; grab the ball } func ...
Go
// +build OMIT package main import ( "fmt" "math/rand" "time" ) func init() { rand.Seed(time.Now().UnixNano()) } func main() { a, b := make(chan string), make(chan string) go func() { a <- "a" }() go func() { b <- "b" }() if rand.Intn(2) == 0 { a = nil // HL fmt.Println("nil a") } else { b = nil // H...
Go
// +build OMIT package main import ( "fmt" "time" ) // STARTMAIN1 OMIT type Ball struct{ hits int } func main() { table := make(chan *Ball) go player("ping", table) go player("pong", table) table <- new(Ball) // game on; toss the ball time.Sleep(1 * time.Second) <-table // game over; grab the ball panic(...
Go
// +build OMIT package main import ( "fmt" "time" ) // STARTMAIN1 OMIT type Ball struct{ hits int } func main() { table := make(chan *Ball) go player("ping", table) go player("pong", table) // table <- new(Ball) // game on; toss the ball // HL time.Sleep(1 * time.Second) <-table // game over; grab the ball...
Go
// +build OMIT package main import ( "fmt" "time" ) // STARTMAIN1 OMIT type Ball struct{ hits int } func main() { table := make(chan *Ball) go player("ping", table) go player("pong", table) table <- new(Ball) // game on; toss the ball time.Sleep(1 * time.Second) <-table // game over; grab the ball } func ...
Go
// +build OMIT // dedupermain runs the Subscribe example with several duplicate // subscriptions to demonstrate deduping. package main import ( "fmt" "math/rand" "time" ) // STARTITEM OMIT // An Item is a stripped-down RSS item. type Item struct{ Title, Channel, GUID string } // STOPITEM OMIT // STARTFETCHER OM...
Go
// naivemain runs the Subscribe example with the naive Subscribe // implementation and a fake RSS fetcher. // +build OMIT package main import ( "fmt" "math/rand" "time" ) // STARTITEM OMIT // An Item is a stripped-down RSS item. type Item struct{ Title, Channel, GUID string } // STOPITEM OMIT // STARTFETCHER OM...
Go
// +build OMIT package main import "fmt" func fib(c chan int, n int) { a, b := 0, 1 for i := 0; i < n; i++ { a, b = b, a+b c <- a // HL } close(c) } func main() { c := make(chan int) go fib(c, 10) // HL for x := range c { // HL fmt.Println(x) } }
Go
// +build OMIT package main import ( "fmt" "net/http" ) var authURL = "" var auth = func(user string) bool { res, err := http.Get(authURL + "/" + user) return err == nil && res.StatusCode == http.StatusOK } func sayHi(user string) { if !auth(user) { fmt.Printf("unknown user %v\n", user) return } fmt.Pri...
Go
// +build OMIT package main import "fmt" // prime returns true if n is a prime number. func prime(n int) bool { for i := 2; i < n; i++ { if n%i == 0 { return false } } return true } // fib returns a channel on which the first n Fibonacci numbers are written. func fib(n int) chan int { c := make(chan int)...
Go
// +build OMIT package main import ( "fmt" "net/http" ) func authRequired(f http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if r.FormValue("user") == "" { http.Error(w, "unknown user", http.StatusForbidden) return } f(w, r) } } var hiHandler = authRequired(...
Go
// +build OMIT package main import "fmt" // prime returns true if n is a prime number. func prime(n int) bool { for i := 2; i < n; i++ { if n%i == 0 { return false } } return true } // primes returns a channel of ints on which it writes the first n prime // numbers before closing it. func primes(n int) ch...
Go
// +build OMIT package main import "fmt" func fib(n int) int { a, b := 0, 1 for i := 0; i < n; i++ { a, b = b, a+b } return b } func fibRec(n int) int { if n <= 1 { return 1 } return fibRec(n-1) + fibRec(n-2) } func main() { for i := 0; i < 10; i++ { fmt.Println(fib(i), fibRec(i)) } }
Go
// +build OMIT package main import "fmt" func fib(n int) chan int { c := make(chan int) // HL go func() { // HL a, b := 0, 1 for i := 0; i < n; i++ { a, b = b, a+b c <- a // HL } close(c) }() return c } func main() { for x := range fib(10) { fmt.Println(x) } }
Go
// +build OMIT package main import ( "bytes" "fmt" "io" "log" "net/http" ) type errorHandler func(http.ResponseWriter, *http.Request) error func handleError(f errorHandler) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { err := f(w, r) if err != nil { log.Printf("%v", err) h...
Go
// +build OMIT package main import ( "fmt" "strings" ) type Name struct { First string Middle string Last string } func (n Name) String() string { return fmt.Sprintf("%s %c. %s", n.First, n.Middle[0], strings.ToUpper(n.Last)) } type SimpleName string func (s SimpleName) String() string { return string(s)...
Go
// +build OMIT package mart import ( "bytes" "fmt" "math/rand" "net/http" "strconv" "strings" "appengine" "appengine/datastore" "appengine/mail" "appengine/user" "github.com/mjibson/appstats" ) func init() { http.HandleFunc("/", front) http.Handle("/checkout", appstats.NewHandler(checkout)) http.Hand...
Go
// +build OMIT package mart import ( "bytes" "fmt" "math/rand" "net/http" "strconv" "strings" "appengine" "appengine/datastore" "appengine/delay" "appengine/mail" "appengine/user" "github.com/mjibson/appstats" ) func init() { http.HandleFunc("/", front) http.Handle("/checkout", appstats.NewHandler(ch...
Go
// +build OMIT package mart import ( "bytes" "fmt" "math/rand" "net/http" "strconv" "strings" "appengine" "appengine/datastore" "appengine/delay" "appengine/mail" "appengine/user" "github.com/mjibson/appstats" ) func init() { http.HandleFunc("/", front) http.Handle("/checkout", appstats.NewHandler(ch...
Go
// +build OMIT package pkg // long_tail_memcache_bad func myHandler(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) // ... // regular request handling // ... go memcache.Set(c, &memcache.Item{ Key: key, Value: data, }) } // long_tail_memcache_good func myHandler(w http.ResponseWri...
Go
// +build OMIT package main import ( "encoding/binary" "io" "log" "os" ) type Gopher struct { Name string AgeYears int } type binWriter struct { w io.Writer size int64 err error } // Write writes a value to the provided writer in little endian form. func (w *binWriter) Write(v interface{}) { if w...
Go
// +build ignore,OMIT package drawer // START OMIT import "image" // Function represent a drawable mathematical function. type Function interface { Eval(float64) float64 } // Draw draws an image showing a rendering of the passed Function. func Draw(f Function) image.Image { // END OMIT return nil }
Go
// +build ignore,OMIT package drawer // START OMIT import ( "image" "code.google.com/p/go.talks/2013/bestpractices/funcdraw/parser" ) // Draw draws an image showing a rendering of the passed ParsedFunc. func DrawParsedFunc(f parser.ParsedFunc) image.Image { // END OMIT return nil }
Go
// +build ignore,OMIT package parser // START OMIT type ParsedFunc struct { text string eval func(float64) float64 } func Parse(text string) (*ParsedFunc, error) { f, err := parse(text) if err != nil { return nil, err } return &ParsedFunc{text: text, eval: f}, nil } func (f *ParsedFunc) Eval(x float64) floa...
Go
// +build ignore,OMIT package main import ( "flag" "image/png" "log" "os" ) // IMPORT OMIT import ( "code.google.com/p/go.talks/2013/bestpractices/funcdraw/drawer" "code.google.com/p/go.talks/2013/bestpractices/funcdraw/parser" ) // ENDIMPORT OMIT var ( width = flag.Int("width", 300, "image width") height...
Go
// +build ignore,OMIT package main import ( "fmt" "net" "time" ) // SEND OMIT func sendMsg(msg, addr string) error { conn, err := net.Dial("tcp", addr) if err != nil { return err } defer conn.Close() _, err = fmt.Fprint(conn, msg) return err } // BROADCAST OMIT func broadcastMsg(msg string, addrs []strin...
Go
// +build ignore,OMIT package bestpractices import ( "fmt" "log" "net/http" ) func doThis() error { return nil } func doThat() error { return nil } // HANDLER1 OMIT func init() { http.HandleFunc("/", handler) } func handler(w http.ResponseWriter, r *http.Request) { err := doThis() if err != nil { http.Erro...
Go
// +build OMIT package main import ( "bytes" "encoding/binary" "io" "log" "os" ) type Gopher struct { Name string AgeYears int } type binWriter struct { w io.Writer buf bytes.Buffer // HL err error } // Write writes a value to the provided writer in little endian form. func (w *binWriter) Write(v i...
Go
// +build OMIT package main import ( "encoding/binary" "io" "log" "os" ) type Gopher struct { Name string AgeYears int } type binWriter struct { w io.Writer size int64 err error } // Write writes a value to the provided writer in little endian form. func (w *binWriter) Write(v interface{}) { if w...
Go
// +build ignore,OMIT package main import ( "errors" "fmt" "time" ) // START OMIT func do(job string) error { fmt.Println("doing job", job) time.Sleep(1 * time.Second) return errors.New("something went wrong!") } func main() { jobs := []string{"one", "two", "three"} errc := make(chan error) for _, job := ...
Go
// +build ignore,OMIT package main import ( "fmt" "net" "time" ) // SEND OMIT func sendMsg(msg, addr string) error { conn, err := net.Dial("tcp", addr) if err != nil { return err } defer conn.Close() _, err = fmt.Fprint(conn, msg) return err } // BROADCAST OMIT func broadcastMsg(msg string, addrs []strin...
Go
// +build OMIT package main import ( "encoding/binary" "io" "log" "os" ) type Gopher struct { Name string AgeYears int } // Example of bad code, missing early return. OMIT func (g *Gopher) WriteTo(w io.Writer) (size int64, err error) { err = binary.Write(w, binary.LittleEndian, int32(len(g.Name))) if er...
Go
// +build ignore,OMIT package main import ( "errors" "fmt" "time" ) // START OMIT func doConcurrently(job string, err chan error) { go func() { fmt.Println("doing job", job) time.Sleep(1 * time.Second) err <- errors.New("something went wrong!") }() } func main() { jobs := []string{"one", "two", "three"}...
Go
// +build OMIT package main import ( "encoding/binary" "io" "log" "os" ) type Gopher struct { Name string AgeYears int } func (g *Gopher) WriteTo(w io.Writer) (size int64, err error) { err = binary.Write(w, binary.LittleEndian, int32(len(g.Name))) if err != nil { return } size += 4 n, err := w.Writ...
Go
// +build ignore,OMIT package main import ( "fmt" "net" "time" ) // SEND OMIT func sendMsg(msg, addr string) error { conn, err := net.Dial("tcp", addr) if err != nil { return err } defer conn.Close() _, err = fmt.Fprint(conn, msg) return err } // BROADCAST OMIT func broadcastMsg(msg string, addrs []strin...
Go
// +build ignore,OMIT package main import ( "fmt" "time" ) // START OMIT type Server struct{ quit chan bool } func NewServer() *Server { s := &Server{make(chan bool)} go s.run() return s } func (s *Server) run() { for { select { case <-s.quit: fmt.Println("finishing task") time.Sleep(time.Second) ...
Go
// +build OMIT package main import ( "encoding/binary" "io" "log" "os" ) type Gopher struct { Name string AgeYears int } type binWriter struct { w io.Writer size int64 err error } // Write writes a value to the provided writer in little endian form. func (w *binWriter) Write(v interface{}) { if w...
Go
// +build OMIT package main import ( "fmt" "reflect" ) func sendSlice(slice interface{}) (channel interface{}) { sliceValue := reflect.ValueOf(slice) chanType := reflect.ChanOf(reflect.BothDir, sliceValue.Type().Elem()) chanValue := reflect.MakeChan(chanType, 0) go func() { for i := 0; i < sliceValue.Len(); ...
Go
// +build OMIT package main import "os" func main() { var w func([]byte) (int, error) w = os.Stdout.Write w([]byte("hello!\n")) }
Go
// +build OMIT package main import ( "fmt" "reflect" ) func makeSwap(fptr interface{}) { swap := func(in []reflect.Value) []reflect.Value { return []reflect.Value{in[1], in[0]} } fn := reflect.ValueOf(fptr).Elem() v := reflect.MakeFunc(fn.Type(), swap) fn.Set(v) } func main() { var fn func(int, int) (int,...
Go
// +build OMIT package main func main() { var a int go func() { for { if a == 0 { a = 1 } } }() for { if a == 1 { a = 0 } } }
Go
// +build OMIT package main import ( "bufio" "fmt" "log" "strings" ) func main() { // START OMIT const input = "Now is the winter of our discontent..." scanner := bufio.NewScanner(strings.NewReader(input)) scanner.Split(bufio.ScanWords) // HL count := 0 for scanner.Scan() { count++ } if err := scanner....
Go
// +build OMIT package main import ( "fmt" "math/rand" "time" ) func init() { rand.Seed(10) } func sendMessages() chan string { ch := make(chan string) go func() { for i := 0; ; i++ { time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond) ch <- fmt.Sprintf("message %v", i) } }() return ch } ...
Go
// +build OMIT package main import ( "bufio" "fmt" "io" "log" "strings" ) const blob = `Hey there, fellow gophers! Have a good day. ` func old() { // STARTold OMIT r := bufio.NewReader(strings.NewReader(blob)) for { s, err := r.ReadString('\n') if err != nil { if err == io.EOF { break } log...
Go
// +build OMIT package main import ( "io" "os" ) func min(a, b int) int { if a < b { return a } else { return b } } func slurp(r io.Reader) error { b := make([]byte, 1024) for { _, err := r.Read(b) if err != nil { if err == io.EOF { return nil } return err } } } func main() { printl...
Go
// +build OMIT package main import "os" func main() { var w func([]byte) (int, error) w = func(b []byte) (int, error) { return os.Stdout.Write(b) } w([]byte("hello!\n")) }
Go
// +build OMIT package main func f(x int) int { return x / 0 } func main() { f(1) }
Go
// +build OMIT package main import ( "fmt" "time" ) func main() { fmt.Println("Today is day", time.Now().YearDay()) }
Go
// +build OMIT package main import ( "io" "os" ) func min(a, b int) int { if a < b { return a } return b } func slurp(r io.Reader) error { b := make([]byte, 1024) for { _, err := r.Read(b) if err != nil { if err == io.EOF { return nil } return err } } panic("unreachable") } func main(...
Go
// +build OMIT package main import ( "flag" "fmt" ) var message = flag.String("message", "Hello, OSCON!", "what to say") func main() { flag.Parse() fmt.Println(*message) }
Go
// +build OMIT package main import ( "fmt" "time" ) // START OMIT func main() { textChannel := make(chan string) words := []string{"ho!", "hey!"} secs := []int{2, 1} // Create a goroutine per word for i, word := range words { go say(word, secs[i], textChannel) // & } // Wait for response via channel N tim...
Go
// +build OMIT package main import ( "fmt" "time" ) func main() { go say("ho!", 2*time.Second) // & go say("hey!", 1*time.Second) // & // Make main sleep for 4 seconds so goroutines can finish time.Sleep(4 * time.Second) } // say prints text after sleeping for X secs func say(text string, secs time.Duration...
Go
// +build OMIT package main import ( "bytes" "fmt" "io" "os" ) func main() { b := new(bytes.Buffer) fmt.Fprintf(b, "hello, %s\n", "world") io.Copy(os.Stdout, b) }
Go
// +build OMIT package main import ( "fmt" "math/rand" "time" ) func lookup() { for _, w := range worklist { w.addrs, w.err = LookupHost(w.host) } } func main() { rand.Seed(time.Now().UnixNano()) t0 := time.Now() lookup() fmt.Printf("\n") for _, w := range worklist { if w.err != nil { fmt.Printf(...
Go
// +build OMIT package main import ( "fmt" "math/rand" "time" ) func lookup() { done := make(chan bool, len(worklist)) for _, w := range worklist { go func(w *Work) { w.addrs, w.err = LookupHost(w.host) done <- true }(w) } for i := 0; i < len(worklist); i++ { <-done } } func main() { rand.See...
Go
// +build OMIT package main import ( "bufio" "io" "log" "net" "os" "os/exec" ) func main() { if len(os.Args) > 1 && os.Args[1] == "serve" { serve() } finger() } func finger() { c, err := net.Dial("tcp", "localhost:finger") if err != nil { log.Fatal(err) } io.WriteString(c, "rsc\n") io.Copy(os.Stdo...
Go
// +build OMIT package main import "fmt" func main() { c := make(chan string) go func() { c <- "Hello" c <- "World" }() fmt.Println(<-c, <-c) }
Go
// +build OMIT package main import ( "fmt" "math" "math/rand" "sync" "time" ) const ( F = 2 N = 5 ReadQuorum = F + 1 WriteQuorum = N - F ) var delay = false type Server struct { mu sync.Mutex data map[string]*Data } type Data struct { Key string Value string Time time.Time ...
Go
// +build OMIT package main import ( "fmt" "math/rand" "time" ) func lookup() { const max = 2 n := 0 done := make(chan bool, max) for _, w := range worklist { if n++; n > max { <-done n-- } go func(w *Work) { w.addrs, w.err = LookupHost(w.host) done <- true }(w) } for ; n > 0; n-- { ...
Go
// +build OMIT package main import ( "fmt" "math" "math/rand" "sync" "time" ) const ( F = 2 N = 5 ReadQuorum = F + 1 WriteQuorum = N - F ) var delay = false type Server struct { mu sync.Mutex data map[string]*Data } type Data struct { Key string Value string Time time.Time ...
Go
// +build OMIT package main import ( "bytes" "fmt" "io" "os" ) var _ = io.Copy func main() { b := new(bytes.Buffer) var w io.Writer w = b fmt.Fprintf(w, "hello, %s\n", "world") os.Stdout.Write(b.Bytes()) }
Go
// +build OMIT package main import ( "fmt" "math/rand" "sync" "time" ) func lookup() { var group sync.WaitGroup for _, w := range worklist { group.Add(1) go func(w *Work) { w.addrs, w.err = LookupHost(w.host) group.Done() }(w) } group.Wait() } func main() { rand.Seed(time.Now().UnixNano()) ...
Go
// +build OMIT package main import "fmt" func main() { fmt.Printf("hello, world\n") }
Go
// +build OMIT package main import ( "flag" "github.com/golang/glog" ) func main() { flag.Set("logtostderr", "true") glog.Infof("hello, world") }
Go
// +build OMIT package main import ( "fmt" "math/rand" "time" ) func lookup() { const max = 2 done := make(chan bool, len(worklist)) limit := make(chan bool, max) for _, w := range worklist { go func(w *Work) { limit <- true w.addrs, w.err = LookupHost(w.host) <-limit done <- true }(w) } ...
Go
// +build OMIT package main // This Markov chain code is taken from the "Generating arbitrary text" // codewalk: http://golang.org/doc/codewalk/markov/ import ( "bytes" "fmt" "math/rand" "strings" "sync" ) // Prefix is a Markov chain prefix of one or more words. type Prefix []string // String returns the Pref...
Go
// +build OMIT package main import ( "fmt" "io" "log" "net" "net/http" "time" "code.google.com/p/go.net/websocket" ) const listenAddr = "localhost:4000" func main() { go netListen() // HL http.HandleFunc("/", rootHandler) http.Handle("/socket", websocket.Handler(socketHandler)) err := http.ListenAndServ...
Go
// +build OMIT package main import "html/template" import "net/http" func rootHandler(w http.ResponseWriter, r *http.Request) { rootTemplate.Execute(w, listenAddr) } var rootTemplate = template.Must(template.New("root").Parse(` <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <script> var input, output, web...
Go
// +build OMIT package main import ( "fmt" "io" "log" "net/http" "code.google.com/p/go.net/websocket" ) const listenAddr = "localhost:4000" func main() { http.HandleFunc("/", rootHandler) http.Handle("/socket", websocket.Handler(socketHandler)) err := http.ListenAndServe(listenAddr, nil) if err != nil { ...
Go
// +build OMIT package main import "html/template" import "net/http" func rootHandler(w http.ResponseWriter, r *http.Request) { rootTemplate.Execute(w, listenAddr) } var rootTemplate = template.Must(template.New("root").Parse(` <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <script> var input, output, web...
Go
// +build OMIT package main import ( "fmt" "io" "log" "net" ) const listenAddr = "localhost:4000" func main() { l, err := net.Listen("tcp", listenAddr) if err != nil { log.Fatal(err) } for { c, err := l.Accept() if err != nil { log.Fatal(err) } go match(c) // HL } } var partner = make(chan io...
Go
// +build OMIT package main import ( "fmt" "io" "log" "net" ) const listenAddr = "localhost:4000" func main() { l, err := net.Listen("tcp", listenAddr) if err != nil { log.Fatal(err) } for { c, err := l.Accept() if err != nil { log.Fatal(err) } go match(c) } } var partner = make(chan io.ReadW...
Go
// +build OMIT package main // This Markov chain code is taken from the "Generating arbitrary text" // codewalk: http://golang.org/doc/codewalk/markov/ import ( "bytes" "fmt" "math/rand" "strings" "sync" ) // Prefix is a Markov chain prefix of one or more words. type Prefix []string // String returns the Pref...
Go
// +build OMIT package main import ( "fmt" "io" "log" "net/http" "time" "code.google.com/p/go.net/websocket" ) const listenAddr = "localhost:4000" func main() { http.HandleFunc("/", rootHandler) http.Handle("/socket", websocket.Handler(socketHandler)) err := http.ListenAndServe(listenAddr, nil) if err !=...
Go
// +build OMIT package main import "html/template" import "net/http" func rootHandler(w http.ResponseWriter, r *http.Request) { rootTemplate.Execute(w, listenAddr) } var rootTemplate = template.Must(template.New("root").Parse(` <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <script> var input, output, web...
Go
// +build OMIT package main import ( "fmt" "io" "log" "net/http" "code.google.com/p/go.net/websocket" ) const listenAddr = "localhost:4000" func main() { http.HandleFunc("/", rootHandler) http.Handle("/socket", websocket.Handler(socketHandler)) err := http.ListenAndServe(listenAddr, nil) if err != nil { ...
Go
// +build OMIT package main import "html/template" import "net/http" func rootHandler(w http.ResponseWriter, r *http.Request) { rootTemplate.Execute(w, listenAddr) } var rootTemplate = template.Must(template.New("root").Parse(` <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <script> var input, output, web...
Go
// +build OMIT package main import "fmt" func main() { ch := make(chan int) go fibs(ch) for i := 0; i < 20; i++ { fmt.Println(<-ch) } } func fibs(ch chan int) { i, j := 0, 1 for { ch <- j i, j = j, i+j } }
Go
// +build OMIT package main import ( "fmt" "log" "net" ) const listenAddr = "localhost:4000" func main() { l, err := net.Listen("tcp", listenAddr) if err != nil { log.Fatal(err) } for { c, err := l.Accept() if err != nil { log.Fatal(err) } fmt.Fprintln(c, "Hello!") c.Close() } }
Go
// +build OMIT package main import ( "code.google.com/p/go.net/websocket" "fmt" "net/http" ) func main() { http.Handle("/", websocket.Handler(handler)) http.ListenAndServe("localhost:4000", nil) } func handler(c *websocket.Conn) { var s string fmt.Fscan(c, &s) fmt.Println("Received:", s) fmt.Fprint(c, "How...
Go
// +build OMIT package main import ( "io" "log" "net" ) const listenAddr = "localhost:4000" func main() { l, err := net.Listen("tcp", listenAddr) if err != nil { log.Fatal(err) } for { c, err := l.Accept() if err != nil { log.Fatal(err) } go io.Copy(c, c) } }
Go
// +build OMIT package main import "fmt" func main() { fmt.Println("Hello, go") }
Go
// +build OMIT package main func Fprintln(w io.Writer, a ...interface{}) (n int, err error) // Writer is the interface that wraps the basic Write method. // // Write writes len(p) bytes from p to the underlying data stream. It // returns the number of bytes written from p (0 <= n <= len(p)) and any // error encounte...
Go
// +build OMIT package main import ( "fmt" "time" ) func main() { go say("let's go!", 3) go say("ho!", 2) go say("hey!", 1) time.Sleep(4 * time.Second) } func say(text string, secs int) { time.Sleep(time.Duration(secs) * time.Second) fmt.Println(text) }
Go
// +build OMIT package main import ( "fmt" "log" "net/http" ) const listenAddr = "localhost:4000" func main() { http.HandleFunc("/", handler) err := http.ListenAndServe(listenAddr, nil) if err != nil { log.Fatal(err) } } func handler(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Hello, web") }...
Go
// +build OMIT package main import "fmt" type A struct{} func (A) Hello() { fmt.Println("Hello!") } type B struct { A } // func (b B) Hello() { b.A.Hello() } // (implicitly!) func main() { var b B b.Hello() }
Go
// +build OMIT package main import ( "fmt" "time" ) func main() { ticker := time.NewTicker(time.Millisecond * 250) boom := time.After(time.Second * 1) for { select { case <-ticker.C: fmt.Println("tick") case <-boom: fmt.Println("boom!") return } } }
Go
// +build OMIT package main import ( "io" "log" "net" ) const listenAddr = "localhost:4000" func main() { l, err := net.Listen("tcp", listenAddr) if err != nil { log.Fatal(err) } for { c, err := l.Accept() if err != nil { log.Fatal(err) } io.Copy(c, c) } }
Go
// +build OMIT package main import ( "fmt" "math/rand" "time" ) func worker(i int, ch chan Work, quit chan struct{}) { for { select { case w := <-ch: if quit == nil { // HL w.Refuse(); fmt.Println("worker", i, "refused", w) break } w.Do(); fmt.Println("worker", i, "processed", w) case <-qu...
Go
// +build OMIT package main import ( "fmt" "time" "math/rand" ) func waiter(i int, block, done chan struct{}) { time.Sleep(time.Duration(rand.Intn(3000)) * time.Millisecond) fmt.Println(i, "waiting...") <-block // HL fmt.Println(i, "done!") done <- struct{}{} } func main() { block, done := make(chan struct...
Go
// +build OMIT package main import "fmt" var battle = make(chan string) func warrior(name string, done chan struct{}) { select { case opponent := <-battle: fmt.Printf("%s beat %s\n", name, opponent) case battle <- name: // I lost :-( } done <- struct{}{} } func main() { done := make(chan struct{}) langs...
Go
// +build OMIT package main import ( "fmt" "math/rand" "time" ) func worker(i int, ch chan Work, quit chan struct{}) { var quitting bool for { select { case w := <-ch: if quitting { w.Refuse(); fmt.Println("worker", i, "refused", w) break } w.Do(); fmt.Println("worker", i, "processed", w) ...
Go
// +build OMIT package main import ( "fmt" "github.com/nf/reddit" // HL "log" ) func main() { items, err := reddit.Get("golang") // HL if err != nil { log.Fatal(err) } for _, item := range items { fmt.Println(item) } }
Go
// +build OMIT package main import ( "io" "log" "net/http" "os" ) func main() { // HLfunc resp, err := http.Get("http://reddit.com/r/golang.json") // HLget if err != nil { // HLerr log.Fatal(err) // HLerr } // HLerr if resp.StatusCode != http.StatusOK { // HLstatus ...
Go
// Package reddit implements a basic client for the Reddit API. // +build OMIT package reddit import ( "encoding/json" "fmt" "net/http" ) // Item describes a Reddit item. type Item struct { Title string URL string Comments int `json:"num_comments"` } func (i Item) String() string { com := "" switch ...
Go
// +build OMIT package main import ( "encoding/json" "fmt" "log" "net/http" ) func main() { resp, err := http.Get("http://reddit.com/r/golang.json") if err != nil { log.Fatal(err) } if resp.StatusCode != http.StatusOK { log.Fatal(resp.Status) } r := new(Response) err = json.NewDecoder(resp.Body).Decod...
Go
// +build OMIT package main import "fmt" func main() { fmt.Println("Greetings, fellow gopher") }
Go
// +build OMIT package main import ( "encoding/json" "errors" "fmt" "log" "net/http" ) func main() { items, err := Get("golang") // HL if err != nil { log.Fatal(err) } for _, item := range items { // HL fmt.Println(item.Title) } } type Response struct { Data struct { Children []struct { Data Ite...
Go
// +build OMIT package main import ( "log" "net/http" ) func main() { b := []byte(jsonBlob) err := http.ListenAndServe(":80", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write(b) })) log.Fatal(err) } const jsonBlob = `{"data":{"after":"t3_ubvcv","before":null,"children":[{"data":{"appr...
Go
// +build OMIT package main import ( "encoding/json" "errors" "fmt" "log" "net/http" ) func main() { items, err := Get("golang") if err != nil { log.Fatal(err) } for _, item := range items { fmt.Println(item) } } type Response struct { Data struct { Children []struct { Data Item } } } type I...
Go