code
stringlengths
10
1.34M
language
stringclasses
1 value
// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /* Package html implements an HTML5-compliant tokenizer and parser. Tokenization is done by creating a Tokenizer for an io.Reader r. It is the caller's respons...
Go
// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package atom provides integer codes (also known as atoms) for a fixed set of // frequently occurring HTML strings: tag names and attribute keys such as "p" /...
Go
// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore package main // This program generates table.go and table_test.go. // Invoke as // // go run gen.go |gofmt >table.go // go run gen.go -test |...
Go
package main import ( "flag" "fmt" "io" "io/ioutil" "os" "path/filepath" "strconv" "strings" ) const example = `"father's birthday": 1959.01.01 "mother's birthday": 1963.-4.01 ` var usage = func() { fmt.Fprintf(os.Stderr, "Usage:\n %s birthdays.txt\nThen a import.csv will be created\n",...
Go
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2012 The Go Authors. All rights reserved. // http://code.google.com/p/goprotobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // m...
Go
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2011 The Go Authors. All rights reserved. // http://code.google.com/p/goprotobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // m...
Go
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // http://code.google.com/p/goprotobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // m...
Go
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // http://code.google.com/p/goprotobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // m...
Go
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2012 The Go Authors. All rights reserved. // http://code.google.com/p/goprotobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // m...
Go
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // http://code.google.com/p/goprotobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // m...
Go
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // http://code.google.com/p/goprotobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // m...
Go
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2011 The Go Authors. All rights reserved. // http://code.google.com/p/goprotobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // m...
Go
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // http://code.google.com/p/goprotobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // m...
Go
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // http://code.google.com/p/goprotobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // m...
Go
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // http://code.google.com/p/goprotobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // m...
Go
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // http://code.google.com/p/goprotobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // m...
Go
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // http://code.google.com/p/goprotobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // m...
Go
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // http://code.google.com/p/goprotobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // m...
Go
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // http://code.google.com/p/goprotobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // m...
Go
// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build OMIT // This code differs from the slides in that it handles errors. package main import ( "compress/gzip" "crypto/aes" "crypto/cipher" "io" ...
Go
// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build OMIT // This code differs from the slides in that it handles errors. package main import ( "compress/gzip" "crypto/aes" "crypto/cipher" "io" ...
Go
// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build OMIT package main import ( "container/heap" "flag" "fmt" "math/rand" "time" ) const nRequester = 100 const nWorker = 10 var roundRobin = fla...
Go
// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build OMIT package main import ( "bufio" "fmt" "os" "strconv" "strings" ) // Generic expression parser/evaluator type Value interface { String() ...
Go
// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build OMIT package main import ( "bufio" "fmt" "os" "strconv" "strings" ) // Generic expression parser/evaluator type Value interface { String() ...
Go
// +build ignore,OMIT package main import ( "log" "net/http" "os" "path/filepath" ) func main() { log.Printf("Running...") log.Fatal(http.ListenAndServe( "127.0.0.1:8080", http.FileServer(http.Dir( filepath.Join(os.Getenv("HOME"), "go", "doc"))))) }
Go
// +build ignore,OMIT package main import ( "io" "log" "net/http" "sort" "strings" "time" ) var modTime = time.Unix(1374708739, 0) // START OMIT func part(s string) SizeReaderAt { return io.NewSectionReader(strings.NewReader(s), 0, int64(len(s))) } func handler(w http.ResponseWriter, r *http.Request) { sra...
Go
// +build ignore,OMIT package sizereaderat import ( "io" "sort" ) // START_1 OMIT // A SizeReaderAt is a ReaderAt with a Size method. // // An io.SectionReader implements SizeReaderAt. type SizeReaderAt interface { Size() int64 io.ReaderAt } // NewMultiReaderAt is like io.MultiReader but produces a ReaderAt // ...
Go
// +build ignore,OMIT package main import "net/http" func main() { http.ListenAndServe(":8080", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.ServeContent(w, r, "foo.txt", time.Now(), strings.NewReader("I am some content.\n")) })) }
Go
// +build ignore,OMIT package main import ( "fmt" "log" "net/http" "os" ) func handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(os.Stdout, "%s details: %+v\n", r.URL.Path, r) fmt.Fprintf(w, "Hello, world! at %s\n", r.URL.Path) } func main() { log.Printf("Running...") log.Fatal(http.ListenAndSer...
Go
// +build ignore,OMIT package download func (s *Server) handleDownload(w http.ResponseWriter, r *http.Request) { s.addActiveDownloadTotal(1) defer s.addActiveDownloadTotal(-1) if !isGetOrHead(w, r) { return } uctx, err := s.newUserContext(r) // ... pl, cacheable, err := s.chooseValidPayloadToDownload(uctx) ...
Go
// +build ignore,OMIT package main import ( "io" ) func main() { var dst io.Writer var src io.Reader // START OMIT n, err := io.Copy(dst, src) // END OMIT _ = n _ = err }
Go
// +build ignore,OMIT package main import ( "bytes" "net/http" "time" "github.com/golang/groupcache" ) func main() { // STARTINIT OMIT me := "http://10.0.0.1" peers := groupcache.NewHTTPPool(me) // Whenever peers change: peers.Set("http://10.0.0.1", "http://10.0.0.2", "http://10.0.0.3") // ENDINIT OMIT ...
Go
// +build ignore,OMIT package main import "io" type SizeReaderAt interface { io.ReaderAt Size() int64 } // START_DOC OMIT // NewChunkAlignedReaderAt returns a ReaderAt wrapper that is backed // by a ReaderAt r of size totalSize where the wrapper guarantees that // all ReadAt calls are aligned to chunkSize boundar...
Go
// +build ignore,OMIT package main import ( "log" "net/http" "strings" "time" ) func main() { log.Printf("Running...") err := http.ListenAndServe("127.0.0.1:8080", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.ServeContent(w, r, "foo.txt", time.Now(), strings.NewReader("I am some co...
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 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 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 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 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 ( "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 } // 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 ( "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" "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 } 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 ( "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 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 ( "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 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 } 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 ( "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 ( "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 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 ( "flag" "github.com/golang/glog" ) func main() { flag.Set("logtostderr", "true") glog.Infof("hello, world") }
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" "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 ( "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" "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" "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() { 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() { 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" func main() { c := make(chan string) go func() { c <- "Hello" c <- "World" }() fmt.Println(<-c, <-c) }
Go
// +build OMIT package main import "fmt" func main() { fmt.Printf("hello, world\n") }
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" "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 ( "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 ( "flag" "fmt" ) var message = flag.String("message", "Hello, OSCON!", "what to say") func main() { flag.Parse() fmt.Println(*message) }
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 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 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 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" "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 "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 import "os" func main() { var w func([]byte) (int, error) w = os.Stdout.Write w([]byte("hello!\n")) }
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 ( "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 ( "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 ( "fmt" "time" ) func main() { fmt.Println("Today is day", time.Now().YearDay()) }
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 func f(x int) int { return x / 0 } func main() { f(1) }
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 ( "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
// 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 main() { in, out := make(chan int), make(chan int) go buffer(in, out) for i := 0; i < 10; i++ { in <- i } close(in) for i := range out { fmt.Println(i) } } // buffer provides an unbounded buffer between in and out. buffer // exits when in is closed and ...
Go
// +build OMIT // realmain runs the Subscribe example with a real RSS fetcher. package main import ( "fmt" "math/rand" "time" rss "github.com/jteeuwen/go-pkg-rss" ) // STARTITEM OMIT // An Item is a stripped-down RSS item. type Item struct{ Title, Channel, GUID string } // STOPITEM OMIT // STARTFETCHER OMIT /...
Go
// +build OMIT // fakemain runs the Subscribe example with a fake RSS fetcher. 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 OMIT // A Fetcher fetches Items and returns t...
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 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 // 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
// +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 } func ...
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" "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" 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(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" 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 "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