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) {
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)
}
}

View File

@ -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()

View File

@ -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)

View File

@ -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"

View File

@ -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)
}

View File

@ -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)
}

View File

@ -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)

View File

@ -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)
}

View File

@ -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))
}

View File

@ -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

View File

@ -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)
}

View File

@ -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)

View File

@ -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) {

View File

@ -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 {

View File

@ -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() {

View File

@ -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)

View File

@ -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]

View File

@ -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;

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