some source updates, toolchain helpers

This commit is contained in:
Mark McGranaghan 2012-10-01 16:15:39 -07:00
parent 3af7544a0f
commit 5242d9c677
20 changed files with 102 additions and 73 deletions

View File

@ -9,7 +9,9 @@ import "fmt"
func f(n int) { func f(n int) {
for i := 0; i < 10; i++ { for i := 0; i < 10; i++ {
fmt.Println(n, ":", 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)
} }
} }

View File

@ -14,8 +14,8 @@ func main() {
n := i n := i
wait.Add(1) wait.Add(1)
go func() { go func() {
opTime := rand.Intn(2000) opTime := time.Duration(rand.Intn(2000))
time.Sleep(time.Duration(opTime) * time.Millisecond) time.Sleep(opTime * time.Millisecond)
fmt.Println(n) fmt.Println(n)
times[n] = opTime times[n] = opTime
wait.Done() wait.Done()

View File

@ -31,13 +31,13 @@ func randVal() int {
return rand.Intn(100) 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) data := make(map[int]int)
for { for {
select { select {
case read := <-reads: case read := <-rs:
read.resp <- data[read.key] read.resp <- data[read.key]
case write := <-writes: case write := <-ws:
data[write.key] = write.val data[write.key] = write.val
write.resp <- true write.resp <- true
} }
@ -63,7 +63,9 @@ func generateWrites(writes chan *writeOp) {
for { for {
key := randKey() key := randKey()
val := randVal() val := randVal()
write := &writeOp{key: key, val: val, resp: make(chan bool)} write := &writeOp{key: key,
val: val,
resp: make(chan bool)}
writes <- write writes <- write
<-write.resp <-write.resp
atomic.AddInt64(&opCount, 1) atomic.AddInt64(&opCount, 1)

View File

@ -1,4 +1,4 @@
// Regexs // ## Regexs
package main package main
@ -18,3 +18,4 @@ func main() {
// todo: more // todo: more
// todo: gsub with regexp // todo: gsub with regexp
// todo: rename to "Regular Expressions"

View File

@ -1,4 +1,4 @@
// JSON // ## JSON
package main package main
@ -7,23 +7,25 @@ import "fmt"
func main() { func main() {
// data to bytes/string // data to bytes/string
bol, _ := json.Marshal(true) bolB, _ := json.Marshal(true)
fmt.Println(string(bol)) fmt.Println(string(bolB))
num, _ := json.Marshal(1) numB, _ := json.Marshal(1)
fmt.Println(string(num)) fmt.Println(string(numB))
str, _ := json.Marshal("gopher") strB, _ := json.Marshal("gopher")
fmt.Println(string(str)) fmt.Println(string(strB))
arr, _ := json.Marshal([]string{"apple", "peach", "pear"}) arrD := []string{"apple", "peach", "pear"}
fmt.Println(string(arr)) arrB, _ := json.Marshal(arrD)
fmt.Println(string(arrB))
hsh, _ := json.Marshal(map[string]int{"apple": 5, "lettuce": 7}) hshD := map[string]int{"apple": 5, "lettuce": 7}
fmt.Println(string(hsh)) hshB, _ := json.Marshal(hshD)
fmt.Println(string(hshB))
// string to data // 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{} var dat map[string]interface{}
err := json.Unmarshal(byt, &dat) err := json.Unmarshal(byt, &dat)
if err != nil { if err != nil {
@ -31,9 +33,9 @@ func main() {
} }
fmt.Println(dat) fmt.Println(dat)
name := dat["Name"].(string) num := dat["num"].(float64)
fmt.Println(name) fmt.Println(num)
parents := dat["Parents"].([]interface{}) strs := dat["strs"].([]interface{})
fmt.Println(parents) fmt.Println(strs)
} }

View File

@ -9,7 +9,8 @@ func main() {
now := time.Now() now := time.Now()
fmt.Println(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) fmt.Println(then)
diff := now.Sub(then) diff := now.Sub(then)

View File

@ -7,7 +7,8 @@ import "net/url"
import "strings" import "strings"
func main() { 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 { if err != nil {
panic(err) panic(err)
} }

View File

@ -10,15 +10,15 @@ func main() {
fmt.Println() fmt.Println()
// Standard base64 encoding/decoding. // Standard base64 encoding/decoding.
stdEnc := base64.StdEncoding.EncodeToString([]byte(data)) sEnc := base64.StdEncoding.EncodeToString([]byte(data))
fmt.Println(stdEnc) fmt.Println(sEnc)
stdDec, _ := base64.StdEncoding.DecodeString(stdEnc) sDec, _ := base64.StdEncoding.DecodeString(sEnc)
fmt.Println(string(stdDec)) fmt.Println(string(sDec))
fmt.Println() fmt.Println()
// URL base64 encoding/decoding. // URL base64 encoding/decoding.
urlEnc := base64.URLEncoding.EncodeToString([]byte(data)) uEnc := base64.URLEncoding.EncodeToString([]byte(data))
fmt.Println(urlEnc) fmt.Println(uEnc)
urlDec, _ := base64.URLEncoding.DecodeString(urlEnc) uDec, _ := base64.URLEncoding.DecodeString(uEnc)
fmt.Println(string(urlDec)) fmt.Println(string(uDec))
} }

View File

@ -1,6 +1 @@
$ go run spawning-processes.go $ 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

View File

@ -11,7 +11,9 @@ func main() {
if lookErr != nil { if lookErr != nil {
panic(lookErr) 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 { if execErr != nil {
panic(execErr) panic(execErr)
} }

View File

@ -8,10 +8,9 @@ import "io/ioutil"
import "fmt" import "fmt"
func main() { func main() {
tr := &http.Transport{ conf := &tls.Config{InsecureSkipVerify: true}
TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, trans := &http.Transport{TLSClientConfig: conf}
} client := &http.Client{Transport: trans}
client := &http.Client{Transport: tr}
resp, err := client.Get("https://127.0.0.1:5000/") resp, err := client.Get("https://127.0.0.1:5000/")
if err != nil { if err != nil {
panic(err) panic(err)

View File

@ -35,26 +35,26 @@ func main() {
fmt.Println(mgetRep) fmt.Println(mgetRep)
// multi calls // multi calls
mcallRep := client.MultiCall(func(mc *redis.MultiCall) { mcRep := client.MultiCall(func(mc *redis.MultiCall) {
mc.Set("k1", "v1") mc.Set("k1", "v1")
mc.Get("k1") mc.Get("k1")
}) })
if mcallRep.Err != nil { if mcrep.Err != nil {
panic(mcallRep.Err) panic(mcRep.Err)
} }
mcallVal, _ := mcallRep.Elems[1].Str() mcVal, _ := mcRep.Elems[1].Str()
fmt.Println(mcallVal) fmt.Println(mcVal)
// transactional calls // transactional calls
tranRep := client.Transaction(func(mc *redis.MultiCall) { tRep := client.Transaction(func(mc *redis.MultiCall) {
mc.Set("k2", "v2") mc.Set("k2", "v2")
mc.Get("k2") mc.Get("k2")
}) })
if tranRep.Err != nil { if tRep.Err != nil {
panic(tranRep.Err) panic(tRep.Err)
} }
tranStr, _ := tranRep.Elems[1].Str() tStr, _ := tRep.Elems[1].Str()
fmt.Println(tranStr) fmt.Println(tStr)
// pubsub // pubsub
msgHdlr := func(msg *redis.Message) { msgHdlr := func(msg *redis.Message) {

View File

@ -8,28 +8,39 @@ import "time"
import "fmt" import "fmt"
func main() { 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 { if openErr != nil {
panic(openErr) panic(openErr)
} }
defer db.Close() defer db.Close()
fmt.Println(db) 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 { if createErr != nil {
panic(createErr) panic(createErr)
} }
fmt.Println(createRep) 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 { if insertErr != nil {
panic(insertErr) panic(insertErr)
} }
fmt.Println(insertRep) fmt.Println(insertRep)
t1, _ := time.Parse(time.RFC3339, "2000-04-08T03:02:01Z") timeFmt := time.RFC3339
t2, _ := time.Parse(time.RFC3339, "2007-03-02T10:15:45Z") t1, _ := time.Parse(timeFmt, "2000-04-08T03:02:01Z")
minsertRep, minsertErr := db.Exec("Insert INTO items VALUES ($1, $2, $3, $4, $5), ($6, $7, $8, $9, $10)", 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, 3, 7.0, true, "more", t1,
5, 1.0, false, "less", t2) 5, 1.0, false, "less", t2)
if minsertErr != nil { if minsertErr != nil {

View File

@ -15,20 +15,21 @@ func runLogging(logs chan string) {
func wrapLogging(f http.HandlerFunc) http.HandlerFunc { func wrapLogging(f http.HandlerFunc) http.HandlerFunc {
logs := make(chan string, 10000) logs := make(chan string, 10000)
go runLogging(logs) go runLogging(logs)
return func(res http.ResponseWriter, req *http.Request) { return func(rs http.ResponseWriter, rq *http.Request) {
start := time.Now() start := time.Now()
f(res, req) f(rs, rq)
method := req.Method method := req.Method
path := req.URL.Path path := req.URL.Path
elapsed := float64(time.Since(start)) / 1000000.0 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) { func hello(rs http.ResponseWriter, rq *http.Request) {
res.Header().Set("Content-Type", "text/plain") rs.Header().Set("Content-Type", "text/plain")
time.Sleep(time.Millisecond * 50) time.Sleep(time.Millisecond * 50)
fmt.Fprintln(res, "Hello logged world") fmt.Fprintln(rs, "Hello logged world")
} }
func main() { func main() {

View File

@ -9,10 +9,11 @@ import (
"strings" "strings"
) )
type Authenticator func(string, string) bool type Auth func(string, string) bool
func testAuth(r *http.Request, auth Authenticator) bool { func testAuth(r *http.Request, auth Auth) bool {
s := strings.SplitN(r.Header.Get("Authorization"), " ", 2) header := r.Header.Get("Authorization")
s := strings.SplitN(header, " ", 2)
if len(s) != 2 || s[0] != "Basic" { if len(s) != 2 || s[0] != "Basic" {
return false return false
} }
@ -28,12 +29,13 @@ func testAuth(r *http.Request, auth Authenticator) bool {
} }
func requireAuth(w http.ResponseWriter, r *http.Request) { 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.WriteHeader(401)
w.Write([]byte("401 Unauthorized\n")) 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) { return func(w http.ResponseWriter, r *http.Request) {
if testAuth(r, a) { if testAuth(r, a) {
h(w, r) h(w, r)

View File

@ -11,7 +11,7 @@ func hello(res http.ResponseWriter, req *http.Request) {
fmt.Fprintln(res, "Hello canonical world") 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) { return func(res http.ResponseWriter, req *http.Request) {
hostPort := strings.Split(req.Host, ":") hostPort := strings.Split(req.Host, ":")
host := hostPort[0] host := hostPort[0]

View File

@ -21,6 +21,9 @@ p {
h1, h2, h3, h4, h5, h6 { h1, h2, h3, h4, h5, h6 {
margin: 30px 0 15px 0; margin: 30px 0 15px 0;
} }
h2 {
page-break-before: always;
}
hr { hr {
border: 0 none; border: 0 none;
border-top: 1px solid #e5e5ee; border-top: 1px solid #e5e5ee;

3
tool/build-html Executable file
View File

@ -0,0 +1,3 @@
#!/bin/bash
ls src/0*/*.{go,sh} | xargs tool/generate > build/go-by-example.html

4
tool/build-pdf Executable file
View File

@ -0,0 +1,4 @@
#!/bin/bash
prince build/go-by-example.html -o build/go-by-example.pdf