diff --git a/src/029-concurrent-goroutines/concurrent-goroutines.go b/src/029-concurrent-goroutines/concurrent-goroutines.go index 28d05a5..9b3d264 100644 --- a/src/029-concurrent-goroutines/concurrent-goroutines.go +++ b/src/029-concurrent-goroutines/concurrent-goroutines.go @@ -9,7 +9,9 @@ import "fmt" func f(n int) { for i := 0; i < 10; i++ { fmt.Println(n, ":", i) - time.Sleep(time.Millisecond * time.Duration(rand.Intn(150))) + breakTime := time.Duration(rand.Intn(150))) + time.Sleep(time.Millisecond * breakTime) + } } diff --git a/src/036-scatter-gather/081-scatter-gather.go b/src/036-scatter-gather/081-scatter-gather.go index 6b814d8..af00b49 100644 --- a/src/036-scatter-gather/081-scatter-gather.go +++ b/src/036-scatter-gather/081-scatter-gather.go @@ -14,8 +14,8 @@ func main() { n := i wait.Add(1) go func() { - opTime := rand.Intn(2000) - time.Sleep(time.Duration(opTime) * time.Millisecond) + opTime := time.Duration(rand.Intn(2000)) + time.Sleep(opTime * time.Millisecond) fmt.Println(n) times[n] = opTime wait.Done() diff --git a/src/043-state-goroutine/state-goroutine.go b/src/043-state-goroutine/state-goroutine.go index 1069873..39c1ade 100644 --- a/src/043-state-goroutine/state-goroutine.go +++ b/src/043-state-goroutine/state-goroutine.go @@ -31,13 +31,13 @@ func randVal() int { return rand.Intn(100) } -func manageState(reads chan *readOp, writes chan *writeOp) { +func manageState(rs chan *readOp, ws chan *writeOp) { data := make(map[int]int) for { select { - case read := <-reads: + case read := <-rs: read.resp <- data[read.key] - case write := <-writes: + case write := <-ws: data[write.key] = write.val write.resp <- true } @@ -63,7 +63,9 @@ func generateWrites(writes chan *writeOp) { for { key := randKey() val := randVal() - write := &writeOp{key: key, val: val, resp: make(chan bool)} + write := &writeOp{key: key, + val: val, + resp: make(chan bool)} writes <- write <-write.resp atomic.AddInt64(&opCount, 1) diff --git a/src/050-regexs/regexs.go b/src/050-regexs/regexs.go index 29c014b..5204f40 100644 --- a/src/050-regexs/regexs.go +++ b/src/050-regexs/regexs.go @@ -1,4 +1,4 @@ -// Regexs +// ## Regexs package main @@ -18,3 +18,4 @@ func main() { // todo: more // todo: gsub with regexp +// todo: rename to "Regular Expressions" diff --git a/src/051-bytes/bytes.go b/src/051-bytes/bytes.go index 5e337e9..bac0bd4 100644 --- a/src/051-bytes/bytes.go +++ b/src/051-bytes/bytes.go @@ -6,7 +6,7 @@ import "fmt" func main() { arr := []byte("some bytes") - str := string([]byte{'a', ' ', 's', 't', 'r', 'i', 'n', 'g'}) + str := string([]byte{'a',' ','s','t','r','i','n','g'}) fmt.Println(arr) fmt.Println(str) } diff --git a/src/052-json/json.go b/src/052-json/json.go index 1cdf6d7..d085067 100644 --- a/src/052-json/json.go +++ b/src/052-json/json.go @@ -1,4 +1,4 @@ -// JSON +// ## JSON package main @@ -7,23 +7,25 @@ import "fmt" func main() { // data to bytes/string - bol, _ := json.Marshal(true) - fmt.Println(string(bol)) + bolB, _ := json.Marshal(true) + fmt.Println(string(bolB)) - num, _ := json.Marshal(1) - fmt.Println(string(num)) + numB, _ := json.Marshal(1) + fmt.Println(string(numB)) - str, _ := json.Marshal("gopher") - fmt.Println(string(str)) + strB, _ := json.Marshal("gopher") + fmt.Println(string(strB)) - arr, _ := json.Marshal([]string{"apple", "peach", "pear"}) - fmt.Println(string(arr)) + arrD := []string{"apple", "peach", "pear"} + arrB, _ := json.Marshal(arrD) + fmt.Println(string(arrB)) - hsh, _ := json.Marshal(map[string]int{"apple": 5, "lettuce": 7}) - fmt.Println(string(hsh)) + hshD := map[string]int{"apple": 5, "lettuce": 7} + hshB, _ := json.Marshal(hshD) + fmt.Println(string(hshB)) // string to data - byt := []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`) + byt := []byte(`{"num":6.0,"strs":["a","b"]}`) var dat map[string]interface{} err := json.Unmarshal(byt, &dat) if err != nil { @@ -31,9 +33,9 @@ func main() { } fmt.Println(dat) - name := dat["Name"].(string) - fmt.Println(name) + num := dat["num"].(float64) + fmt.Println(num) - parents := dat["Parents"].([]interface{}) - fmt.Println(parents) + strs := dat["strs"].([]interface{}) + fmt.Println(strs) } diff --git a/src/053-time/time.go b/src/053-time/time.go index 095d80c..ad52d34 100644 --- a/src/053-time/time.go +++ b/src/053-time/time.go @@ -9,7 +9,8 @@ func main() { now := time.Now() fmt.Println(now) - then := time.Date(2009, 11, 17, 20, 34, 58, 651387237, time.UTC) + then := time.Date( + 2009, 11, 17, 20, 34, 58, 651387237, time.UTC) fmt.Println(then) diff := now.Sub(then) diff --git a/src/058-urls/urls.go b/src/058-urls/urls.go index 813b541..6fde08c 100644 --- a/src/058-urls/urls.go +++ b/src/058-urls/urls.go @@ -7,7 +7,8 @@ import "net/url" import "strings" func main() { - u, err := url.Parse("postgres://user:pass@host.com:5432/path?k=v#frag") + s := "postgres://user:pass@host.com:5432/path?k=v#frag" + u, err := url.Parse(s) if err != nil { panic(err) } diff --git a/src/060-base64-encoding/base64-encoding.go b/src/060-base64-encoding/base64-encoding.go index 0ce3396..f7f7679 100644 --- a/src/060-base64-encoding/base64-encoding.go +++ b/src/060-base64-encoding/base64-encoding.go @@ -10,15 +10,15 @@ func main() { fmt.Println() // Standard base64 encoding/decoding. - stdEnc := base64.StdEncoding.EncodeToString([]byte(data)) - fmt.Println(stdEnc) - stdDec, _ := base64.StdEncoding.DecodeString(stdEnc) - fmt.Println(string(stdDec)) + sEnc := base64.StdEncoding.EncodeToString([]byte(data)) + fmt.Println(sEnc) + sDec, _ := base64.StdEncoding.DecodeString(sEnc) + fmt.Println(string(sDec)) fmt.Println() // URL base64 encoding/decoding. - urlEnc := base64.URLEncoding.EncodeToString([]byte(data)) - fmt.Println(urlEnc) - urlDec, _ := base64.URLEncoding.DecodeString(urlEnc) - fmt.Println(string(urlDec)) + uEnc := base64.URLEncoding.EncodeToString([]byte(data)) + fmt.Println(uEnc) + uDec, _ := base64.URLEncoding.DecodeString(uEnc) + fmt.Println(string(uDec)) } diff --git a/src/067-spawning-processes/spawning-processes.sh b/src/067-spawning-processes/spawning-processes.sh index e0ca5ba..62df9ce 100644 --- a/src/067-spawning-processes/spawning-processes.sh +++ b/src/067-spawning-processes/spawning-processes.sh @@ -1,6 +1 @@ $ go run spawning-processes.go -Files: -total 8 -drwxr-xr-x 3 mmcgrana staff 102 Sep 23 11:35 . -drwxr-xr-x 101 mmcgrana staff 3434 Sep 23 11:25 .. --rw-r--r--@ 1 mmcgrana staff 241 Sep 23 11:37 spawning-processes.go diff --git a/src/068-execing-processes/execing-processes.go b/src/068-execing-processes/execing-processes.go index 1603b31..461d502 100644 --- a/src/068-execing-processes/execing-processes.go +++ b/src/068-execing-processes/execing-processes.go @@ -11,7 +11,9 @@ func main() { if lookErr != nil { panic(lookErr) } - execErr := syscall.Exec(binary, []string{"-a", "-l", "-h"}, os.Environ()) + args := []string{"-a", "-l", "-h"} + env := os.Environ() + execErr := syscall.Exec(binary, args, env) if execErr != nil { panic(execErr) } diff --git a/src/072-https-client/https-client.go b/src/072-https-client/https-client.go index 7b58a24..98dbdf2 100644 --- a/src/072-https-client/https-client.go +++ b/src/072-https-client/https-client.go @@ -8,10 +8,9 @@ import "io/ioutil" import "fmt" func main() { - tr := &http.Transport{ - TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, - } - client := &http.Client{Transport: tr} + conf := &tls.Config{InsecureSkipVerify: true} + trans := &http.Transport{TLSClientConfig: conf} + client := &http.Client{Transport: trans} resp, err := client.Get("https://127.0.0.1:5000/") if err != nil { panic(err) diff --git a/src/073-redis/redis.go b/src/073-redis/redis.go index da15664..498bd51 100644 --- a/src/073-redis/redis.go +++ b/src/073-redis/redis.go @@ -35,26 +35,26 @@ func main() { fmt.Println(mgetRep) // multi calls - mcallRep := client.MultiCall(func(mc *redis.MultiCall) { + mcRep := client.MultiCall(func(mc *redis.MultiCall) { mc.Set("k1", "v1") mc.Get("k1") }) - if mcallRep.Err != nil { - panic(mcallRep.Err) + if mcrep.Err != nil { + panic(mcRep.Err) } - mcallVal, _ := mcallRep.Elems[1].Str() - fmt.Println(mcallVal) + mcVal, _ := mcRep.Elems[1].Str() + fmt.Println(mcVal) // transactional calls - tranRep := client.Transaction(func(mc *redis.MultiCall) { + tRep := client.Transaction(func(mc *redis.MultiCall) { mc.Set("k2", "v2") mc.Get("k2") }) - if tranRep.Err != nil { - panic(tranRep.Err) + if tRep.Err != nil { + panic(tRep.Err) } - tranStr, _ := tranRep.Elems[1].Str() - fmt.Println(tranStr) + tStr, _ := tRep.Elems[1].Str() + fmt.Println(tStr) // pubsub msgHdlr := func(msg *redis.Message) { diff --git a/src/074-postgres/postgres.go b/src/074-postgres/postgres.go index 54a09f3..c69128c 100644 --- a/src/074-postgres/postgres.go +++ b/src/074-postgres/postgres.go @@ -8,28 +8,39 @@ import "time" import "fmt" func main() { - db, openErr := sql.Open("postgres", "dbname=gobyexample sslmode=disable") + conf := "dbname=gobyexample sslmode=disable" + db, openErr := sql.Open("postgres", conf) if openErr != nil { panic(openErr) } defer db.Close() fmt.Println(db) - createRep, createErr := db.Exec("CREATE TABLE items (a int, b float, c boolean, d text, e timestamp with time zone)") + createRep, createErr := db.Exec( + `CREATE TABLE items + (a int, b float, c boolean, + d text, e timestamp with time zone)`) if createErr != nil { panic(createErr) } fmt.Println(createRep) - insertRep, insertErr := db.Exec("INSERT INTO items VALUES (1, 2.0, false, 'string', '2000-01-01T01:02:03Z')") + insertRep, insertErr := db.Exec( + `INSERT INTO items VALUES + (1, 2.0, false, + 'string', '2000-01-01T01:02:03Z')`) if insertErr != nil { panic(insertErr) } fmt.Println(insertRep) - t1, _ := time.Parse(time.RFC3339, "2000-04-08T03:02:01Z") - t2, _ := time.Parse(time.RFC3339, "2007-03-02T10:15:45Z") - minsertRep, minsertErr := db.Exec("Insert INTO items VALUES ($1, $2, $3, $4, $5), ($6, $7, $8, $9, $10)", + timeFmt := time.RFC3339 + t1, _ := time.Parse(timeFmt, "2000-04-08T03:02:01Z") + t2, _ := time.Parse(timeFmt, "2007-03-02T10:15:45Z") + minsertRep, minsertErr := db.Exec( + `Insert INTO items VALUES + ($1, $2, $3, $4, $5), + ($6, $7, $8, $9, $10)`, 3, 7.0, true, "more", t1, 5, 1.0, false, "less", t2) if minsertErr != nil { diff --git a/src/079-request-logging/request-logging.go b/src/079-request-logging/request-logging.go index eacb10e..812db1e 100644 --- a/src/079-request-logging/request-logging.go +++ b/src/079-request-logging/request-logging.go @@ -15,20 +15,21 @@ func runLogging(logs chan string) { func wrapLogging(f http.HandlerFunc) http.HandlerFunc { logs := make(chan string, 10000) go runLogging(logs) - return func(res http.ResponseWriter, req *http.Request) { + return func(rs http.ResponseWriter, rq *http.Request) { start := time.Now() - f(res, req) + f(rs, rq) method := req.Method path := req.URL.Path elapsed := float64(time.Since(start)) / 1000000.0 - logs <- fmt.Sprintf("method=%s path=%s elapsed=%f", method, path, elapsed) + logs <- fmt.Sprintf("method=%s path=%s elapsed=%f", + method, path, elapsed) } } -func hello(res http.ResponseWriter, req *http.Request) { - res.Header().Set("Content-Type", "text/plain") +func hello(rs http.ResponseWriter, rq *http.Request) { + rs.Header().Set("Content-Type", "text/plain") time.Sleep(time.Millisecond * 50) - fmt.Fprintln(res, "Hello logged world") + fmt.Fprintln(rs, "Hello logged world") } func main() { diff --git a/src/081-basic-authentication/basic-authentication.go b/src/081-basic-authentication/basic-authentication.go index fb31752..5a5dde9 100644 --- a/src/081-basic-authentication/basic-authentication.go +++ b/src/081-basic-authentication/basic-authentication.go @@ -9,10 +9,11 @@ import ( "strings" ) -type Authenticator func(string, string) bool +type Auth func(string, string) bool -func testAuth(r *http.Request, auth Authenticator) bool { - s := strings.SplitN(r.Header.Get("Authorization"), " ", 2) +func testAuth(r *http.Request, auth Auth) bool { + header := r.Header.Get("Authorization") + s := strings.SplitN(header, " ", 2) if len(s) != 2 || s[0] != "Basic" { return false } @@ -28,12 +29,13 @@ func testAuth(r *http.Request, auth Authenticator) bool { } func requireAuth(w http.ResponseWriter, r *http.Request) { - w.Header().Set("WWW-Authenticate", `Basic realm="private"`) + w.Header().Set("WWW-Authenticate", + "Basic realm=\"private\"") w.WriteHeader(401) w.Write([]byte("401 Unauthorized\n")) } -func wrapAuth(h http.HandlerFunc, a Authenticator) http.HandlerFunc { +func wrapAuth(h http.HandlerFunc, a Auth) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if testAuth(r, a) { h(w, r) diff --git a/src/082-canonical-hosts/canonical-hosts.go b/src/082-canonical-hosts/canonical-hosts.go index 56e7897..bd9c5ac 100644 --- a/src/082-canonical-hosts/canonical-hosts.go +++ b/src/082-canonical-hosts/canonical-hosts.go @@ -11,7 +11,7 @@ func hello(res http.ResponseWriter, req *http.Request) { fmt.Fprintln(res, "Hello canonical world") } -func wrapCanonicalHost(f http.HandlerFunc, canonicalHost string) http.HandlerFunc { +func wrapCanonicalHost(f http.HandlerFunc, host string) http.HandlerFunc { return func(res http.ResponseWriter, req *http.Request) { hostPort := strings.Split(req.Host, ":") host := hostPort[0] diff --git a/style/book.css b/style/book.css index 2081256..17d75d1 100644 --- a/style/book.css +++ b/style/book.css @@ -21,6 +21,9 @@ p { h1, h2, h3, h4, h5, h6 { margin: 30px 0 15px 0; } +h2 { + page-break-before: always; +} hr { border: 0 none; border-top: 1px solid #e5e5ee; diff --git a/tool/build-html b/tool/build-html new file mode 100755 index 0000000..9748440 --- /dev/null +++ b/tool/build-html @@ -0,0 +1,3 @@ +#!/bin/bash + +ls src/0*/*.{go,sh} | xargs tool/generate > build/go-by-example.html diff --git a/tool/build-pdf b/tool/build-pdf new file mode 100755 index 0000000..4e19766 --- /dev/null +++ b/tool/build-pdf @@ -0,0 +1,4 @@ +#!/bin/bash + +prince build/go-by-example.html -o build/go-by-example.pdf +