Clean out examples not used on the site

This commit is contained in:
Mark McGranaghan 2016-12-27 12:51:36 -08:00
parent a3b3bff8cb
commit b36fbd2a0e
23 changed files with 0 additions and 578 deletions

View File

@ -1,58 +0,0 @@
package main
import (
"encoding/base64"
"fmt"
"net/http"
"strings"
)
type Auth func(string, string) bool
type handler http.HandlerFunc
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
}
b, err := base64.StdEncoding.DecodeString(s[1])
if err != nil {
return false
}
pair := strings.SplitN(string(b), ":", 2)
if len(pair) != 2 {
return false
}
return auth(pair[0], pair[1])
}
func requireAuth(w http.ResponseWriter, r *http.Request) {
w.Header().Set("WWW-Authenticate",
"Basic realm=\"private\"")
w.WriteHeader(401)
w.Write([]byte("401 Unauthorized\n"))
}
func wrapAuth(h handler, a Auth) handler {
return func(w http.ResponseWriter, r *http.Request) {
if testAuth(r, a) {
h(w, r)
} else {
requireAuth(w, r)
}
}
}
func hello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello secret world!")
}
func main() {
checkPassword := func(_, password string) bool {
return password == "supersecret"
}
handler1 := http.HanderFunc(hello)
handler2 := wrapAuth(handler1, checkPassword)
http.ListenAndServe(":5000", handler2)
}

View File

@ -1,37 +0,0 @@
package main
import "net/http"
import "strings"
import "fmt"
type handler http.HandlerFunc
func hello(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
fmt.Fprintln(w, "Hello canonical world")
}
func wrapCanonicalHost(f handler, chost string) handler {
return func(w http.ResponseWriter, r *http.Request) {
hostPort := strings.Split(r.Host, ":")
host := hostPort[0]
if host != chost {
fmt.Println("redirect to", chost)
hostPort[0] = chost
url := "http://" +
strings.Join(hostPort, ":") +
r.URL.String()
http.Redirect(w, r, url, 301)
return
}
f(w, r)
}
}
func main() {
handler := wrapCanonicalHost(hello, "localhost")
http.HandleFunc("/", handler)
http.ListenAndServe(":5000", nil)
}
// todo: comment about https canonicalization

View File

@ -1,4 +0,0 @@
$ go run canonical-hosts.go
$ curl -i -L http://127.0.0.1:5000/go
$ curl -i -L http://127.0.0.1:5000/go

View File

@ -1,98 +0,0 @@
package main
import (
"fmt"
"net"
"net/http"
"os"
"os/signal"
"sync/atomic"
"syscall"
"time"
)
func slow(res http.ResponseWriter, req *http.Request) {
fmt.Println("respond at=start")
time.Sleep(time.Second * 5)
res.Header().Set("Content-Type", "text/plain")
fmt.Fprintln(res, "Finally.")
fmt.Println("respond at=finish")
}
var connCount int64 = 0
type watchedConn struct {
net.Conn
}
func (w *watchedConn) Close() error {
atomic.AddInt64(&connCount, -1)
return w.Conn.Close()
}
type watchedListener struct {
net.Listener
}
func (l *watchedListener) Accept() (net.Conn, error) {
conn, err := l.Listener.Accept()
if err != nil {
return nil, err
}
atomic.AddInt64(&connCount, 1)
return &watchedConn{Conn: conn}, nil
}
func main() {
stop := make(chan bool, 1)
sig := make(chan os.Signal, 1)
handler := http.HandlerFunc(slow)
server := &http.Server{Handler: handler}
fmt.Println("listen at=start")
listener, listenErr := net.Listen("tcp", ":5000")
if listenErr != nil {
panic(listenErr)
}
wListener := &watchedListener{Listener: listener}
fmt.Println("listen at=finish")
go func() {
<-stop
fmt.Println("close at=start")
closeErr := wListener.Close()
if closeErr != nil {
panic(closeErr)
}
fmt.Println("close at=finish")
}()
go func() {
signal.Notify(
sig, syscall.SIGINT,
syscall.SIGTERM)
fmt.Println("trap at=start")
<-sig
stop <- true
fmt.Println("trap at=finish")
}()
fmt.Println("serve at=start")
server.Serve(wListener)
fmt.Println("serve at=finish")
for {
connCountCurrent := atomic.LoadInt64(&connCount)
if connCountCurrent > 0 {
fmt.Println("wait at=pending remaining=",
connCountCurrent)
time.Sleep(time.Second)
} else {
fmt.Println("wait at=finish remaining=",
connCountCurrent)
return
}
}
}
// todo: pull in work from gobyexample-server
// todo: factor out to cut-and-pastable against normal app

View File

@ -1,6 +0,0 @@
$ go build graceful-shutdown.go
$ ./graceful-shutdown
$ curl -i http://127.0.0.1:5000/
^C

View File

@ -1,13 +0,0 @@
package main
import "net/http"
func hello(res http.ResponseWriter, req *http.Request) {
res.Header().Set("Content-Type", "text/plain")
res.Write([]byte("Hello web\n"))
}
func main() {
http.HandleFunc("/", hello)
http.ListenAndServe(":5000", nil)
}

View File

@ -1,15 +0,0 @@
package main
import "net/http"
import "io/ioutil"
import "fmt"
func main() {
resp, err := http.Get("http://127.0.0.1:5000/")
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
fmt.Print(string(body))
}

View File

@ -1,22 +0,0 @@
package main
import "net/http"
import "fmt"
func hello(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
fmt.Fprintln(w, "Hello wrapped world")
}
func wrapMiddleware(f http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Wrapped", "true")
f(w, r)
}
}
func main() {
handler := wrapMiddleware(hello)
http.HandleFunc("/", handler)
http.ListenAndServe(":5000", nil)
}

View File

@ -1,10 +0,0 @@
$ go run middleware.go
$ curl -i http://127.0.0.1:5000/
HTTP/1.1 200 OK
Content-Type: text/plain
Date: Tue, 02 Oct 2012 00:37:18 GMT
Transfer-Encoding: chunked
X-Wrapped: true
Hello wrapped world

View File

@ -1,79 +0,0 @@
package main
import _ "github.com/bmizerany/pq"
import "database/sql"
import "time"
import "fmt"
func main() {
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)`)
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')`)
if insertErr != nil {
panic(insertErr)
}
fmt.Println(insertRep)
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 {
panic(minsertErr)
}
num, _ := minsertRep.RowsAffected()
fmt.Println(num)
rows, selectErr := db.Query("SELECT * FROM items")
if selectErr != nil {
panic(selectErr)
}
defer rows.Close()
for rows.Next() {
var r1 int
var r2 float64
var r3 bool
var r4 string
var r5 time.Time
rows.Scan(&r1, &r2, &r3, &r4, &r5)
fmt.Println(r1, r2, r3, r4, r5)
}
rowsErr := rows.Err()
if rowsErr != nil {
panic(rowsErr)
}
dropRep, dropErr := db.Exec("DROP TABLE items")
if dropErr != nil {
panic(dropErr)
}
fmt.Println(dropRep)
}
// todo: connection pooling & concurrency
// todo: re-connection
// todo: errors
// todo: database_url

View File

@ -1,10 +0,0 @@
# First, be sure that you've installed Postgres
# and have a server running locally at port 5432.
# Then create an example database.
$ createdb gobyexample
# Now install the dependencies for the postgres
# example and try running it.
$ go get github.com/bmizerany/pq
$ go run postgres.go

View File

@ -1,77 +0,0 @@
package main
import "github.com/fzzbt/radix/redis"
import "time"
import "fmt"
func main() {
// initialize
conf := redis.DefaultConfig()
client := redis.NewClient(conf)
fmt.Println(conf)
fmt.Println(client)
// set & get
setRep := client.Set("foo", "bar")
if setRep.Err != nil {
panic(setRep.Err)
}
fmt.Println(setRep)
getRep := client.Get("foo")
if getRep.Err != nil {
panic(getRep.Err)
}
getStr, _ := getRep.Str()
fmt.Println(getRep)
fmt.Println(getStr)
// variadic calls
client.Set("foo1", "bar1")
client.Set("foo2", "bar2")
client.Set("foo3", "bar3")
mgetRep := client.Mget("foo1", "foo2", "foo3")
fmt.Println(mgetRep)
// multi calls
mcRep := client.MultiCall(func(mc *redis.MultiCall) {
mc.Set("k1", "v1")
mc.Get("k1")
})
if mcRep.Err != nil {
panic(mcRep.Err)
}
mcVal, _ := mcRep.Elems[1].Str()
fmt.Println(mcVal)
// transactional calls
tRep := client.Transaction(func(mc *redis.MultiCall) {
mc.Set("k2", "v2")
mc.Get("k2")
})
if tRep.Err != nil {
panic(tRep.Err)
}
tStr, _ := tRep.Elems[1].Str()
fmt.Println(tStr)
// pubsub
msgHdlr := func(msg *redis.Message) {
fmt.Println(msg)
}
sub, subErr := client.Subscription(msgHdlr)
if subErr != nil {
panic(subErr)
}
defer sub.Close()
sub.Subscribe("chan1", "chan2")
sub.Psubscribe("chan*")
client.Publish("chan1", "foo")
sub.Unsubscribe("chan1")
client.Publish("chan2", "bar")
time.Sleep(time.Second)
}
// todo: connection pooling & concurrency?
// todo: reconnection?
// todo: errors?
// todo: redis_url

View File

@ -1,6 +0,0 @@
# Start a Redis server.
$ redis-server
# In another terminal, run the redis client:
$ go get github.com/fzzbt/radix/redis
$ go run redis.go

View File

@ -1,40 +0,0 @@
package main
import "net/http"
import "time"
import "fmt"
func runLogging(logs chan string) {
for log := range logs {
fmt.Println(log)
}
}
func wrapLogging(f http.HandlerFunc) http.HandlerFunc {
logs := make(chan string, 10000)
go runLogging(logs)
return func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
f(w, r)
method := r.Method
path := r.URL.Path
elapsed := float64(time.Since(start)) / 1000000.0
logs <- fmt.Sprintf(
"method=%s path=%s elapsed=%f",
method, path, elapsed)
}
}
func hello(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
time.Sleep(time.Millisecond * 50)
fmt.Fprintln(w, "Hello logged world")
}
func main() {
handler := wrapLogging(hello)
http.HandleFunc("/", handler)
http.ListenAndServe(":5000", nil)
}
// todo: logging status code?

View File

@ -1,19 +0,0 @@
package main
import "github.com/bmizerany/pat"
import "net/http"
import "fmt"
func hello(w http.ResponseWriter, req *http.Request) {
fmt.Fprintln(w, "hello "+req.URL.Query().Get(":name"))
}
func main() {
p := pat.New()
p.Get("/hello/:name", http.HandlerFunc(hello))
http.ListenAndServe(":5000", p)
}
// todo: consider gorilla-web
// todo: defaults
// todo: fallthroughs

View File

@ -1,4 +0,0 @@
$ go get github.com/bmizerany/pat
$ go run request-routing.go
$ curl -i http://127.0.0.1:5000/hello/gopher

View File

@ -1,19 +0,0 @@
package main
import "net/http"
import "fmt"
func hello(res http.ResponseWriter, req *http.Request) {
res.Header().Set("Content-Type", "text/plain")
if req.URL.Path == "/protected" {
res.WriteHeader(401)
fmt.Fprintln(res, "Not allowed")
} else {
fmt.Fprintln(res, "Hello")
}
}
func main() {
http.HandleFunc("/", hello)
http.ListenAndServe(":5000", nil)
}

View File

@ -1,5 +0,0 @@
$ go run xx-http-server-status-code.go
$ curl -i http://127.0.0.1:5000/ | grep HTTP
$ curl -i http://127.0.0.1:5000/protected | grep HTTP

View File

@ -1,9 +0,0 @@
package main
import "fmt"
func main() {
// `x := val` is shorthand for `var x type = val`.
x := "Hello var"
fmt.Println(x)
}

View File

@ -1,2 +0,0 @@
$ go run short-declarations.go
Hello var

View File

@ -1,12 +0,0 @@
package main
import "net/http"
func main() {
handler := http.FileServer(http.Dir("./"))
http.ListenAndServe(":5000", handler)
}
// todo: index pages
// todo: disable listing
// todo: custom 404 handling

View File

@ -1,5 +0,0 @@
$ go run static-content.go
$ curl http://127.0.0.1:5000/
$ curl http://127.0.0.1:5000/http-server-static.go
$ curl http://127.0.0.1:5000/missing

View File

@ -1,28 +0,0 @@
package main
import (
"fmt"
"net/http"
"time"
)
func stream(resp http.ResponseWriter, req *http.Request) {
respf, ok := resp.(http.Flusher)
if !ok {
panic("not flushable")
}
fmt.Println("stream")
resp.WriteHeader(200)
for i := 0; i < 10; i++ {
n, err := resp.Write([]byte("tick\n"))
respf.Flush()
fmt.Println("tick", n, err)
time.Sleep(time.Second * 1)
}
}
func main() {
http.HandleFunc("/", stream)
fmt.Println("serve")
http.ListenAndServe(":5000", nil)
}