├── go-web-master ├── README.md ├── chapter-4 │ ├── staticweb │ │ ├── public │ │ │ ├── readme.txt │ │ │ ├── img │ │ │ │ └── iconshiju.jpg │ │ │ └── about.html │ │ └── main.go │ ├── defaultservemux │ │ └── main.go │ ├── handlefunc │ │ └── main.go │ ├── handlerfunc │ │ └── main.go │ ├── handle │ │ └── main.go │ ├── server │ │ └── main.go │ ├── customhandler │ │ └── main.go │ └── mux │ │ └── main.go ├── taskmanager │ ├── Godeps │ │ ├── _workspace │ │ │ ├── .gitignore │ │ │ └── src │ │ │ │ ├── github.com │ │ │ │ ├── dgrijalva │ │ │ │ │ └── jwt-go │ │ │ │ │ │ ├── .gitignore │ │ │ │ │ │ ├── test │ │ │ │ │ │ ├── hmacTestKey │ │ │ │ │ │ ├── sample_key.pub │ │ │ │ │ │ └── sample_key │ │ │ │ │ │ ├── doc.go │ │ │ │ │ │ ├── signing_method.go │ │ │ │ │ │ ├── LICENSE │ │ │ │ │ │ ├── errors.go │ │ │ │ │ │ ├── rsa_utils.go │ │ │ │ │ │ ├── hmac.go │ │ │ │ │ │ ├── VERSION_HISTORY.md │ │ │ │ │ │ ├── rsa.go │ │ │ │ │ │ └── README.md │ │ │ │ ├── gorilla │ │ │ │ │ ├── mux │ │ │ │ │ │ ├── .travis.yml │ │ │ │ │ │ ├── README.md │ │ │ │ │ │ └── LICENSE │ │ │ │ │ └── context │ │ │ │ │ │ ├── .travis.yml │ │ │ │ │ │ ├── README.md │ │ │ │ │ │ ├── LICENSE │ │ │ │ │ │ ├── doc.go │ │ │ │ │ │ └── context.go │ │ │ │ └── codegangsta │ │ │ │ │ └── negroni │ │ │ │ │ ├── doc.go │ │ │ │ │ ├── logger.go │ │ │ │ │ ├── recovery.go │ │ │ │ │ ├── LICENSE │ │ │ │ │ ├── static.go │ │ │ │ │ └── response_writer.go │ │ │ │ ├── gopkg.in │ │ │ │ └── mgo.v2 │ │ │ │ │ ├── raceon.go │ │ │ │ │ ├── raceoff.go │ │ │ │ │ ├── Makefile │ │ │ │ │ ├── README.md │ │ │ │ │ ├── saslstub.go │ │ │ │ │ ├── saslimpl.go │ │ │ │ │ ├── internal │ │ │ │ │ └── sasl │ │ │ │ │ │ ├── sasl_windows.h │ │ │ │ │ │ ├── sasl.c │ │ │ │ │ │ ├── sspi_windows.h │ │ │ │ │ │ ├── sspi_windows.c │ │ │ │ │ │ ├── sasl.go │ │ │ │ │ │ ├── sasl_windows.go │ │ │ │ │ │ └── sasl_windows.c │ │ │ │ │ ├── bson │ │ │ │ │ ├── specdata │ │ │ │ │ │ └── update.sh │ │ │ │ │ └── LICENSE │ │ │ │ │ ├── doc.go │ │ │ │ │ ├── LICENSE │ │ │ │ │ ├── testdb │ │ │ │ │ ├── setup.sh │ │ │ │ │ ├── dropall.js │ │ │ │ │ ├── wait.js │ │ │ │ │ ├── server.pem │ │ │ │ │ ├── client.pem │ │ │ │ │ ├── init.js │ │ │ │ │ └── supervisord.conf │ │ │ │ │ ├── txn │ │ │ │ │ ├── chaos.go │ │ │ │ │ ├── tarjan.go │ │ │ │ │ └── debug.go │ │ │ │ │ ├── queue.go │ │ │ │ │ └── stats.go │ │ │ │ └── golang.org │ │ │ │ └── x │ │ │ │ └── crypto │ │ │ │ ├── bcrypt │ │ │ │ └── base64.go │ │ │ │ ├── PATENTS │ │ │ │ ├── LICENSE │ │ │ │ └── blowfish │ │ │ │ └── cipher.go │ │ ├── Readme │ │ └── Godeps.json │ ├── common │ │ ├── config.json │ │ ├── bootstrapper.go │ │ ├── utils.go │ │ ├── mongoUtils.go │ │ └── auth.go │ ├── keys │ │ ├── app.rsa.pub │ │ └── app.rsa │ ├── routers │ │ ├── user.go │ │ ├── router.go │ │ ├── note.go │ │ └── task.go │ ├── main.go │ ├── Dockerfile │ ├── controllers │ │ ├── context.go │ │ ├── resources.go │ │ └── userController.go │ ├── data │ │ ├── userRepository.go │ │ ├── noteRepository.go │ │ └── taskRepository.go │ └── models │ │ └── models.go ├── chapter-1 │ ├── hello │ │ └── main.go │ ├── calc │ │ ├── calc.go │ │ └── calc_test.go │ ├── calcdemo │ │ └── main.go │ └── web │ │ └── main.go ├── chapter-11 │ ├── gae-server │ │ ├── app.yaml │ │ └── task.go │ ├── hybridapp │ │ ├── app.yaml │ │ ├── appengine.go │ │ └── main.go │ ├── datastore │ │ ├── app.yaml │ │ └── task.go │ ├── cloudendpoint │ │ ├── app.yaml │ │ ├── endpoints.go │ │ └── task.go │ ├── hybridapplib │ │ └── handler.go │ └── onpremises-server │ │ └── task.go ├── chapter-5 │ ├── htmltemp │ │ └── templates │ │ │ ├── base.html │ │ │ ├── add.html │ │ │ ├── edit.html │ │ │ └── index.html │ ├── texttemp │ │ ├── deftemp.go │ │ ├── main.go │ │ └── main1.go │ └── htmlsecurity │ │ └── main.go ├── chapter-7 │ ├── oauth │ │ ├── config.json │ │ └── main.go │ ├── keys │ │ ├── demo.rsa.pub │ │ └── demo.rsa │ └── jwtauth │ │ ├── keys │ │ ├── app.rsa.pub │ │ └── app.rsa │ │ └── jwtmiddleware.go ├── chapter-10 │ ├── httptestbdd │ │ ├── main.go │ │ └── lib │ │ │ ├── lib_suite_test.go │ │ │ ├── repository.go │ │ │ ├── handlers.go │ │ │ └── users_test.go │ ├── stringutils │ │ └── utils.go │ ├── httptest │ │ ├── main.go │ │ └── main_test.go │ └── stringutils_test │ │ └── utils_test.go ├── .gitignore ├── chapter-6 │ ├── negroni │ │ ├── server.go │ │ ├── muxrouter.go │ │ ├── auth.go │ │ └── flowcontrol.go │ └── middleware │ │ ├── gorillahandlers.go │ │ ├── logger.go │ │ ├── server.log │ │ ├── alice.go │ │ └── flowcontrol.go ├── chapter-8 │ ├── insert-map-slice.go │ ├── index.go │ ├── insert-struct.go │ ├── insert-embedded.go │ ├── manage-session.go │ └── embedded-doc.go └── LICENSE ├── LICENSE.txt ├── 9781484210536.jpg ├── README.md └── contributing.md /go-web-master/README.md: -------------------------------------------------------------------------------- 1 | # go-web 2 | -------------------------------------------------------------------------------- /go-web-master/chapter-4/staticweb/public/readme.txt: -------------------------------------------------------------------------------- 1 | sample text -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/.gitignore: -------------------------------------------------------------------------------- 1 | /pkg 2 | /bin 3 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/web-dev-w-go/HEAD/LICENSE.txt -------------------------------------------------------------------------------- /9781484210536.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/web-dev-w-go/HEAD/9781484210536.jpg -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | bin 3 | 4 | 5 | -------------------------------------------------------------------------------- /go-web-master/chapter-1/hello/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println("Hello, world") 7 | } 8 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/gopkg.in/mgo.v2/raceon.go: -------------------------------------------------------------------------------- 1 | // +build race 2 | 3 | package mgo 4 | 5 | const raceDetector = true 6 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/gopkg.in/mgo.v2/raceoff.go: -------------------------------------------------------------------------------- 1 | // +build !race 2 | 3 | package mgo 4 | 5 | const raceDetector = false 6 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/gopkg.in/mgo.v2/Makefile: -------------------------------------------------------------------------------- 1 | startdb: 2 | @testdb/setup.sh start 3 | 4 | stopdb: 5 | @testdb/setup.sh stop 6 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/github.com/gorilla/mux/.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | go: 4 | - 1.0 5 | - 1.1 6 | - 1.2 7 | - tip 8 | -------------------------------------------------------------------------------- /go-web-master/chapter-1/calc/calc.go: -------------------------------------------------------------------------------- 1 | package calc 2 | 3 | func Add(x, y int) int { 4 | return x + y 5 | } 6 | func Subtract(x, y int) int { 7 | return x - y 8 | } 9 | -------------------------------------------------------------------------------- /go-web-master/chapter-11/gae-server/app.yaml: -------------------------------------------------------------------------------- 1 | application: gae-demo 2 | version: 1 3 | runtime: go 4 | api_version: go1 5 | 6 | handlers: 7 | - url: /.* 8 | script: _go_app -------------------------------------------------------------------------------- /go-web-master/chapter-11/hybridapp/app.yaml: -------------------------------------------------------------------------------- 1 | application: hybridapp 2 | version: 1 3 | runtime: go 4 | api_version: go1 5 | 6 | handlers: 7 | - url: /.* 8 | script: _go_app -------------------------------------------------------------------------------- /go-web-master/chapter-4/staticweb/public/img/iconshiju.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/web-dev-w-go/HEAD/go-web-master/chapter-4/staticweb/public/img/iconshiju.jpg -------------------------------------------------------------------------------- /go-web-master/chapter-11/datastore/app.yaml: -------------------------------------------------------------------------------- 1 | application: datastore-demo 2 | version: 1 3 | runtime: go 4 | api_version: go1 5 | 6 | handlers: 7 | - url: /.* 8 | script: _go_app -------------------------------------------------------------------------------- /go-web-master/chapter-5/htmltemp/templates/base.html: -------------------------------------------------------------------------------- 1 | {{define "base"}} 2 | 3 | {{template "head" .}} 4 | {{template "body" .}} 5 | 6 | {{end}} -------------------------------------------------------------------------------- /go-web-master/chapter-7/oauth/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "TwitterKey" : "Your Key", 3 | "TwitterSecret" : "Your Secret", 4 | "FacebookKey" : "Your Key", 5 | "FacebookSecret" : "Your Secret" 6 | } -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/Readme: -------------------------------------------------------------------------------- 1 | This directory tree is generated automatically by godep. 2 | 3 | Please do not edit. 4 | 5 | See https://github.com/tools/godep for more information. 6 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/github.com/gorilla/context/.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | go: 4 | - 1.0 5 | - 1.1 6 | - 1.2 7 | - 1.3 8 | - 1.4 9 | - tip 10 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/common/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "Server" : "0.0.0.0:8080", 3 | "MongoDBHost" : "127.0.0.1", 4 | "MongoDBUser" : "", 5 | "MongoDBPwd" : "", 6 | "Database" : "taskdb" 7 | } 8 | -------------------------------------------------------------------------------- /go-web-master/chapter-11/hybridapp/appengine.go: -------------------------------------------------------------------------------- 1 | // +build appengine 2 | 3 | package task 4 | 5 | import ( 6 | _ "github.com/shijuvar/go-web/chapter-11/hybridapplib" 7 | ) 8 | 9 | func init() { 10 | } 11 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/gopkg.in/mgo.v2/README.md: -------------------------------------------------------------------------------- 1 | The MongoDB driver for Go 2 | ------------------------- 3 | 4 | Please go to [http://labix.org/mgo](http://labix.org/mgo) for all project details. 5 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/test/hmacTestKey: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/web-dev-w-go/HEAD/go-web-master/taskmanager/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/test/hmacTestKey -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/doc.go: -------------------------------------------------------------------------------- 1 | // Package jwt is a Go implementation of JSON Web Tokens: http://self-issued.info/docs/draft-jones-json-web-token.html 2 | // 3 | // See README.md for more info. 4 | package jwt 5 | -------------------------------------------------------------------------------- /go-web-master/chapter-4/staticweb/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "net/http" 5 | ) 6 | 7 | func main() { 8 | mux := http.NewServeMux() 9 | fs := http.FileServer(http.Dir("public")) 10 | mux.Handle("/", fs) 11 | http.ListenAndServe(":8080", mux) 12 | } 13 | -------------------------------------------------------------------------------- /go-web-master/chapter-10/httptestbdd/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "net/http" 5 | 6 | "github.com/shijuvar/go-web/chapter-10/httptestbdd/lib" 7 | ) 8 | 9 | func main() { 10 | routers := lib.SetUserRoutes() 11 | http.ListenAndServe(":8080", routers) 12 | } 13 | -------------------------------------------------------------------------------- /go-web-master/chapter-11/hybridapp/main.go: -------------------------------------------------------------------------------- 1 | // +build !appengine 2 | 3 | package main 4 | 5 | import ( 6 | "net/http" 7 | 8 | _ "github.com/shijuvar/go-web/chapter-11/hybridapplib" 9 | ) 10 | 11 | func main() { 12 | http.ListenAndServe("localhost:8080", nil) 13 | } 14 | -------------------------------------------------------------------------------- /go-web-master/chapter-1/calcdemo/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/shijuvar/go-web/chapter-1/calc" 7 | ) 8 | 9 | func main() { 10 | //var x, y int= 10, 5 11 | x, y := 10, 5 12 | fmt.Println(calc.Add(x, y)) 13 | fmt.Println(calc.Subtract(x, y)) 14 | } 15 | -------------------------------------------------------------------------------- /go-web-master/chapter-10/httptestbdd/lib/lib_suite_test.go: -------------------------------------------------------------------------------- 1 | package lib_test 2 | 3 | import ( 4 | "testing" 5 | 6 | . "github.com/onsi/ginkgo" 7 | . "github.com/onsi/gomega" 8 | ) 9 | 10 | func TestLib(t *testing.T) { 11 | RegisterFailHandler(Fail) 12 | RunSpecs(t, "Lib Suite") 13 | } 14 | -------------------------------------------------------------------------------- /go-web-master/chapter-1/web/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "net/http" 6 | ) 7 | 8 | func handler(w http.ResponseWriter, r *http.Request) { 9 | fmt.Fprint(w, "Hello, world!") 10 | } 11 | 12 | func main() { 13 | http.HandleFunc("/", handler) 14 | http.ListenAndServe(":8080", nil) 15 | } 16 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/gopkg.in/mgo.v2/saslstub.go: -------------------------------------------------------------------------------- 1 | //+build !sasl 2 | 3 | package mgo 4 | 5 | import ( 6 | "fmt" 7 | ) 8 | 9 | func saslNew(cred Credential, host string) (saslStepper, error) { 10 | return nil, fmt.Errorf("SASL support not enabled during build (-tags sasl)") 11 | } 12 | -------------------------------------------------------------------------------- /go-web-master/chapter-7/keys/demo.rsa.pub: -------------------------------------------------------------------------------- 1 | -----BEGIN PUBLIC KEY----- 2 | MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDPSMNALgfEMEDbS3kCLiTlpx0S 3 | 4tZH1jZLcGF5Pjhc9IuEIf7p6obYT1W7urDPWM8JGO1mdx+GnJCnPcvFSsX8FjGw 4 | DqIp7afTdislYCJwQLXL7qPzwvG7ZlrtXrC9+0xkDGNxB+5Cui++8gWGbfTpTZiC 5 | iP413esxVQ30btKk2QIDAQAB 6 | -----END PUBLIC KEY----- 7 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/keys/app.rsa.pub: -------------------------------------------------------------------------------- 1 | -----BEGIN PUBLIC KEY----- 2 | MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDPSMNALgfEMEDbS3kCLiTlpx0S 3 | 4tZH1jZLcGF5Pjhc9IuEIf7p6obYT1W7urDPWM8JGO1mdx+GnJCnPcvFSsX8FjGw 4 | DqIp7afTdislYCJwQLXL7qPzwvG7ZlrtXrC9+0xkDGNxB+5Cui++8gWGbfTpTZiC 5 | iP413esxVQ30btKk2QIDAQAB 6 | -----END PUBLIC KEY----- 7 | -------------------------------------------------------------------------------- /go-web-master/chapter-7/jwtauth/keys/app.rsa.pub: -------------------------------------------------------------------------------- 1 | -----BEGIN PUBLIC KEY----- 2 | MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDPSMNALgfEMEDbS3kCLiTlpx0S 3 | 4tZH1jZLcGF5Pjhc9IuEIf7p6obYT1W7urDPWM8JGO1mdx+GnJCnPcvFSsX8FjGw 4 | DqIp7afTdislYCJwQLXL7qPzwvG7ZlrtXrC9+0xkDGNxB+5Cui++8gWGbfTpTZiC 5 | iP413esxVQ30btKk2QIDAQAB 6 | -----END PUBLIC KEY----- 7 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/github.com/gorilla/mux/README.md: -------------------------------------------------------------------------------- 1 | mux 2 | === 3 | [![Build Status](https://travis-ci.org/gorilla/mux.png?branch=master)](https://travis-ci.org/gorilla/mux) 4 | 5 | gorilla/mux is a powerful URL router and dispatcher. 6 | 7 | Read the full documentation here: http://www.gorillatoolkit.org/pkg/mux 8 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/common/bootstrapper.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | func StartUp() { 4 | // Initialize AppConfig variable 5 | initConfig() 6 | // Initialize private/public keys for JWT authentication 7 | initKeys() 8 | // Start a MongoDB session 9 | createDbSession() 10 | // Add indexes into MongoDB 11 | addIndexes() 12 | } 13 | -------------------------------------------------------------------------------- /go-web-master/chapter-5/texttemp/deftemp.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "os" 6 | "text/template" 7 | ) 8 | 9 | func main() { 10 | t, err := template.New("test").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`) 11 | err = t.ExecuteTemplate(os.Stdout, "T", "World") 12 | if err != nil { 13 | log.Fatal("Execute: ", err) 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /go-web-master/chapter-1/calc/calc_test.go: -------------------------------------------------------------------------------- 1 | package calc 2 | 3 | import "testing" 4 | 5 | func TestAdd(t *testing.T) { 6 | var v int 7 | v = Add(15,10) 8 | if v != 25 { 9 | t.Error("Expected 25, got ", v) 10 | } 11 | } 12 | func TestSubtract(t *testing.T) { 13 | var v int 14 | v = Subtract(15,10) 15 | if v != 5 { 16 | t.Error("Expected 5, got ", v) 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/github.com/gorilla/context/README.md: -------------------------------------------------------------------------------- 1 | context 2 | ======= 3 | [![Build Status](https://travis-ci.org/gorilla/context.png?branch=master)](https://travis-ci.org/gorilla/context) 4 | 5 | gorilla/context is a general purpose registry for global request variables. 6 | 7 | Read the full documentation here: http://www.gorillatoolkit.org/pkg/context 8 | -------------------------------------------------------------------------------- /go-web-master/chapter-5/htmlsecurity/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "html/template" 5 | "log" 6 | "os" 7 | ) 8 | 9 | func main() { 10 | t, err := template.New("test").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`) 11 | err = t.ExecuteTemplate(os.Stdout, "T", "") 12 | if err != nil { 13 | log.Fatal("Execute: ", err) 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /go-web-master/chapter-5/htmltemp/templates/add.html: -------------------------------------------------------------------------------- 1 | {{define "head"}}Add Note{{end}} 2 | {{define "body"}} 3 |

Add Note

4 |
5 |

Title:

6 |

Description:

7 |

8 |
9 | {{end}} -------------------------------------------------------------------------------- /go-web-master/.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | *.test 24 | *.prof 25 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/gopkg.in/mgo.v2/saslimpl.go: -------------------------------------------------------------------------------- 1 | //+build sasl 2 | 3 | package mgo 4 | 5 | import ( 6 | "github.com/shijuvar/go-web/taskmanager/Godeps/_workspace/src/gopkg.in/mgo.v2/internal/sasl" 7 | ) 8 | 9 | func saslNew(cred Credential, host string) (saslStepper, error) { 10 | return sasl.New(cred.Username, cred.Password, cred.Mechanism, cred.Service, host) 11 | } 12 | -------------------------------------------------------------------------------- /go-web-master/chapter-11/cloudendpoint/app.yaml: -------------------------------------------------------------------------------- 1 | application: go-endpoints-1152 2 | version: v1 3 | threadsafe: true 4 | 5 | runtime: go 6 | api_version: go1 7 | 8 | handlers: 9 | - url: /.* 10 | script: _go_app 11 | 12 | # Important! Even though there's a catch all routing above, 13 | # without these two lines it's not going to work. 14 | # Make sure you have this: 15 | - url: /_ah/spi/.* 16 | script: _go_app -------------------------------------------------------------------------------- /go-web-master/taskmanager/routers/user.go: -------------------------------------------------------------------------------- 1 | package routers 2 | 3 | import ( 4 | "github.com/gorilla/mux" 5 | "github.com/shijuvar/go-web/taskmanager/controllers" 6 | ) 7 | 8 | func SetUserRoutes(router *mux.Router) *mux.Router { 9 | router.HandleFunc("/users/register", controllers.Register).Methods("POST") 10 | router.HandleFunc("/users/login", controllers.Login).Methods("POST") 11 | return router 12 | } 13 | -------------------------------------------------------------------------------- /go-web-master/chapter-6/negroni/server.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "net/http" 6 | 7 | "github.com/codegangsta/negroni" 8 | ) 9 | 10 | func index(w http.ResponseWriter, req *http.Request) { 11 | fmt.Fprintf(w, "Welcome!") 12 | } 13 | func main() { 14 | mux := http.NewServeMux() 15 | mux.HandleFunc("/", index) 16 | n := negroni.Classic() 17 | n.UseHandler(mux) 18 | n.Run(":8080") 19 | } 20 | -------------------------------------------------------------------------------- /go-web-master/chapter-4/defaultservemux/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net/http" 7 | ) 8 | 9 | func messageHandler(w http.ResponseWriter, r *http.Request) { 10 | fmt.Fprintf(w, "Welcome to Go Web Development") 11 | } 12 | 13 | func main() { 14 | 15 | http.HandleFunc("/welcome", messageHandler) 16 | 17 | log.Println("Listening...") 18 | http.ListenAndServe(":8080", nil) 19 | } 20 | -------------------------------------------------------------------------------- /go-web-master/chapter-5/htmltemp/templates/edit.html: -------------------------------------------------------------------------------- 1 | {{define "head"}}Edit Note{{end}} 2 | {{define "body"}} 3 |

Edit Note

4 |
5 |

Title:

6 |

Description:

7 |

8 |
9 | {{end}} -------------------------------------------------------------------------------- /go-web-master/taskmanager/routers/router.go: -------------------------------------------------------------------------------- 1 | package routers 2 | 3 | import ( 4 | "github.com/gorilla/mux" 5 | ) 6 | 7 | func InitRoutes() *mux.Router { 8 | router := mux.NewRouter().StrictSlash(false) 9 | // Routes for the User entity 10 | router = SetUserRoutes(router) 11 | // Routes for the Task entity 12 | router = SetTaskRoutes(router) 13 | // Routes for the TaskNote entity 14 | router = SetNoteRoutes(router) 15 | return router 16 | } 17 | -------------------------------------------------------------------------------- /go-web-master/chapter-6/negroni/muxrouter.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "net/http" 6 | 7 | "github.com/codegangsta/negroni" 8 | "github.com/gorilla/mux" 9 | ) 10 | 11 | func index(w http.ResponseWriter, req *http.Request) { 12 | fmt.Fprintf(w, "Welcome!") 13 | } 14 | func main() { 15 | router := mux.NewRouter() 16 | router.HandleFunc("/", index) 17 | n := negroni.Classic() 18 | n.UseHandler(router) 19 | n.Run(":8080") 20 | } 21 | -------------------------------------------------------------------------------- /go-web-master/chapter-4/handlefunc/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net/http" 7 | ) 8 | 9 | func messageHandler(w http.ResponseWriter, r *http.Request) { 10 | fmt.Fprintf(w, "Welcome to Go Web Development") 11 | } 12 | 13 | func main() { 14 | mux := http.NewServeMux() 15 | 16 | // Use the shortcut method ServeMux.HandleFunc 17 | mux.HandleFunc("/welcome", messageHandler) 18 | 19 | log.Println("Listening...") 20 | http.ListenAndServe(":8080", mux) 21 | } 22 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/gopkg.in/mgo.v2/internal/sasl/sasl_windows.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "sspi_windows.h" 4 | 5 | SECURITY_STATUS SEC_ENTRY sspi_acquire_credentials_handle(CredHandle* cred_handle, char* username, char* password, char* domain); 6 | int sspi_step(CredHandle* cred_handle, int has_context, CtxtHandle* context, PVOID* buffer, ULONG* buffer_length, char* target); 7 | int sspi_send_client_authz_id(CtxtHandle* context, PVOID* buffer, ULONG* buffer_length, char* user_plus_realm); 8 | -------------------------------------------------------------------------------- /go-web-master/chapter-4/handlerfunc/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net/http" 7 | ) 8 | 9 | func messageHandler(w http.ResponseWriter, r *http.Request) { 10 | fmt.Fprintf(w, "Welcome to Go Web Development") 11 | } 12 | 13 | func main() { 14 | mux := http.NewServeMux() 15 | 16 | // Convert the messageHandler function to a HandlerFunc type 17 | mh := http.HandlerFunc(messageHandler) 18 | mux.Handle("/welcome", mh) 19 | 20 | log.Println("Listening...") 21 | http.ListenAndServe(":8080", mux) 22 | } 23 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/test/sample_key.pub: -------------------------------------------------------------------------------- 1 | -----BEGIN PUBLIC KEY----- 2 | MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4f5wg5l2hKsTeNem/V41 3 | fGnJm6gOdrj8ym3rFkEU/wT8RDtnSgFEZOQpHEgQ7JL38xUfU0Y3g6aYw9QT0hJ7 4 | mCpz9Er5qLaMXJwZxzHzAahlfA0icqabvJOMvQtzD6uQv6wPEyZtDTWiQi9AXwBp 5 | HssPnpYGIn20ZZuNlX2BrClciHhCPUIIZOQn/MmqTD31jSyjoQoV7MhhMTATKJx2 6 | XrHhR+1DcKJzQBSTAGnpYVaqpsARap+nwRipr3nUTuxyGohBTSmjJ2usSeQXHI3b 7 | ODIRe1AuTyHceAbewn8b462yEWKARdpd9AjQW5SIVPfdsz5B6GlYQ5LdYKtznTuy 8 | 7wIDAQAB 9 | -----END PUBLIC KEY----- 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Apress Source Code 2 | 3 | This repository accompanies [*Web Development with Go*](http://www.apress.com/9781484210536) by Shiju Varghese (Apress, 2015). 4 | 5 | ![Cover image](9781484210536.jpg) 6 | 7 | Download the files as a zip using the green button, or clone the repository to your machine using Git. 8 | 9 | ## Releases 10 | 11 | Release v1.0 corresponds to the code in the published book, without corrections or updates. 12 | 13 | ## Contributions 14 | 15 | See the file Contributing.md for more information on how you can contribute to this repository. 16 | -------------------------------------------------------------------------------- /go-web-master/chapter-4/handle/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net/http" 7 | ) 8 | 9 | func messageHandler(message string) http.Handler { 10 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 11 | fmt.Fprintf(w, message) 12 | }) 13 | } 14 | func main() { 15 | mux := http.NewServeMux() 16 | 17 | mux.Handle("/welcome", messageHandler("Welcome to Go Web Development")) 18 | mux.Handle("/message", messageHandler("net/http is awesome")) 19 | 20 | log.Println("Listening...") 21 | http.ListenAndServe(":8080", mux) 22 | } 23 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/gopkg.in/mgo.v2/bson/specdata/update.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | set -e 4 | 5 | if [ ! -d specifications ]; then 6 | git clone -b bson git@github.com:jyemin/specifications 7 | fi 8 | 9 | TESTFILE="../specdata_test.go" 10 | 11 | cat < $TESTFILE 12 | package bson_test 13 | 14 | var specTests = []string{ 15 | END 16 | 17 | for file in specifications/source/bson/tests/*.yml; do 18 | ( 19 | echo '`' 20 | cat $file 21 | echo -n '`,' 22 | ) >> $TESTFILE 23 | done 24 | 25 | echo '}' >> $TESTFILE 26 | 27 | gofmt -w $TESTFILE 28 | -------------------------------------------------------------------------------- /go-web-master/chapter-4/server/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net/http" 7 | "time" 8 | ) 9 | 10 | func messageHandler(w http.ResponseWriter, r *http.Request) { 11 | fmt.Fprintf(w, "Welcome to Go Web Development") 12 | } 13 | 14 | func main() { 15 | 16 | http.HandleFunc("/welcome", messageHandler) 17 | 18 | server := &http.Server{ 19 | Addr: ":8080", 20 | ReadTimeout: 10 * time.Second, 21 | WriteTimeout: 10 * time.Second, 22 | MaxHeaderBytes: 1 << 20, 23 | } 24 | 25 | log.Println("Listening...") 26 | server.ListenAndServe() 27 | } 28 | -------------------------------------------------------------------------------- /go-web-master/chapter-4/customhandler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net/http" 7 | ) 8 | 9 | type messageHandler struct { 10 | message string 11 | } 12 | 13 | func (m *messageHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { 14 | fmt.Fprintf(w, m.message) 15 | } 16 | 17 | func main() { 18 | mux := http.NewServeMux() 19 | 20 | mh1 := &messageHandler{"Welcome to Go Web Development"} 21 | mux.Handle("/welcome", mh1) 22 | 23 | mh2 := &messageHandler{"net/http is awesome"} 24 | mux.Handle("/message", mh2) 25 | 26 | log.Println("Listening...") 27 | http.ListenAndServe(":8080", mux) 28 | } 29 | -------------------------------------------------------------------------------- /go-web-master/chapter-10/stringutils/utils.go: -------------------------------------------------------------------------------- 1 | package stringutils 2 | 3 | import ( 4 | "bytes" 5 | "unicode" 6 | ) 7 | 8 | // Change the case of a string parameter 9 | func SwapCase(str string) string { 10 | 11 | buf := &bytes.Buffer{} 12 | for _, r := range str { 13 | if unicode.IsUpper(r) { 14 | buf.WriteRune(unicode.ToLower(r)) 15 | } else { 16 | buf.WriteRune(unicode.ToUpper(r)) 17 | } 18 | } 19 | 20 | return buf.String() 21 | } 22 | 23 | // Reverse the string parameter 24 | func Reverse(s string) string { 25 | r := []rune(s) 26 | for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { 27 | r[i], r[j] = r[j], r[i] 28 | } 29 | return string(r) 30 | } 31 | -------------------------------------------------------------------------------- /go-web-master/chapter-5/htmltemp/templates/index.html: -------------------------------------------------------------------------------- 1 | {{define "head"}}Index{{end}} 2 | {{define "body"}} 3 |

Notes List

4 |

5 | Add Note 6 |

7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | {{range $key,$value := . }} 16 | 17 | 18 | 19 | 20 | 24 | 25 | {{end}} 26 |
TitleDescriptionCreated OnActions
{{$value.Title}}{{$value.Description}}{{$value.CreatedOn}} 21 | Edit | 22 | Delete 23 |
27 |
28 | {{end}} 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /contributing.md: -------------------------------------------------------------------------------- 1 | # Contributing to Apress Source Code 2 | 3 | Copyright for Apress source code belongs to the author(s). However, under fair use you are encouraged to fork and contribute minor corrections and updates for the benefit of the author(s) and other readers. 4 | 5 | ## How to Contribute 6 | 7 | 1. Make sure you have a GitHub account. 8 | 2. Fork the repository for the relevant book. 9 | 3. Create a new branch on which to make your change, e.g. 10 | `git checkout -b my_code_contribution` 11 | 4. Commit your change. Include a commit message describing the correction. Please note that if your commit message is not clear, the correction will not be accepted. 12 | 5. Submit a pull request. 13 | 14 | Thank you for your contribution! -------------------------------------------------------------------------------- /go-web-master/taskmanager/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "net/http" 6 | 7 | "github.com/shijuvar/go-web/taskmanager/Godeps/_workspace/src/github.com/codegangsta/negroni" 8 | "github.com/shijuvar/go-web/taskmanager/common" 9 | "github.com/shijuvar/go-web/taskmanager/routers" 10 | ) 11 | 12 | //Entry point of the program 13 | func main() { 14 | 15 | // Calls startup logic 16 | common.StartUp() 17 | // Get the mux router object 18 | router := routers.InitRoutes() 19 | // Create a negroni instance 20 | n := negroni.Classic() 21 | n.UseHandler(router) 22 | 23 | server := &http.Server{ 24 | Addr: common.AppConfig.Server, 25 | Handler: n, 26 | } 27 | log.Println("Listening...") 28 | server.ListenAndServe() 29 | } 30 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Dockerfile: -------------------------------------------------------------------------------- 1 | # golang image where workspace (GOPATH) configured at /go. 2 | FROM golang 3 | 4 | # Copy the local package files to the container’s workspace. 5 | ADD . /go/src/github.com/shijuvar/go-web/taskmanager 6 | 7 | # Setting up working directory 8 | WORKDIR /go/src/github.com/shijuvar/go-web/taskmanager 9 | 10 | # Get godeps for managing and restoring dependencies 11 | RUN go get github.com/tools/godep 12 | 13 | # Restore godep dependencies 14 | RUN godep restore 15 | 16 | # Build the taskmanager command inside the container. 17 | RUN go install github.com/shijuvar/go-web/taskmanager 18 | 19 | # Run the taskmanager command when the container starts. 20 | ENTRYPOINT /go/bin/taskmanager 21 | 22 | # Service listens on port 8080. 23 | EXPOSE 8080 -------------------------------------------------------------------------------- /go-web-master/chapter-4/staticweb/public/about.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | About Me – 8 | 9 | 10 |

About Shiju

11 |

12 | 13 |

14 | 15 |

16 | Shiju Varghese is a Solutions Architect focused on building highly scalable Cloud solutions with a special interest in APIs, Microservices, Containerization and Distributed apps. 17 | He currently specializes in Golang, Google Cloud, Microsoft Azure and Docker. 18 |

19 | 20 | 21 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/controllers/context.go: -------------------------------------------------------------------------------- 1 | package controllers 2 | 3 | import ( 4 | "gopkg.in/mgo.v2" 5 | 6 | "github.com/shijuvar/go-web/taskmanager/common" 7 | ) 8 | 9 | // Struct used for maintaining HTTP Request Context 10 | type Context struct { 11 | MongoSession *mgo.Session 12 | } 13 | 14 | // Close mgo.Session 15 | func (c *Context) Close() { 16 | c.MongoSession.Close() 17 | } 18 | 19 | // Returns mgo.collection for the given name 20 | func (c *Context) DbCollection(name string) *mgo.Collection { 21 | return c.MongoSession.DB(common.AppConfig.Database).C(name) 22 | } 23 | 24 | // Create a new Context object for each HTTP request 25 | func NewContext() *Context { 26 | session := common.GetSession().Copy() 27 | context := &Context{ 28 | MongoSession: session, 29 | } 30 | return context 31 | } 32 | -------------------------------------------------------------------------------- /go-web-master/chapter-5/texttemp/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "os" 6 | "text/template" 7 | ) 8 | 9 | type Note struct { 10 | Title string 11 | Description string 12 | } 13 | 14 | const tmpl = `Note - Title: {{.Title}}, Description: {{.Description}}` 15 | 16 | func main() { 17 | //Create an instance of Note struct 18 | note := Note{"text/templates", "Template generates textual output"} 19 | 20 | //create a new template with a name 21 | t := template.New("note") 22 | 23 | //parse some content and generate a template 24 | t, err := t.Parse(tmpl) 25 | if err != nil { 26 | log.Fatal("Parse: ", err) 27 | return 28 | } 29 | //Applies a parsed template to the data of Note object 30 | if err := t.Execute(os.Stdout, note); err != nil { 31 | log.Fatal("Execute: ", err) 32 | return 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/signing_method.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | var signingMethods = map[string]func() SigningMethod{} 4 | 5 | // Signing method 6 | type SigningMethod interface { 7 | Verify(signingString, signature string, key interface{}) error 8 | Sign(signingString string, key interface{}) (string, error) 9 | Alg() string 10 | } 11 | 12 | // Register the "alg" name and a factory function for signing method. 13 | // This is typically done during init() in the method's implementation 14 | func RegisterSigningMethod(alg string, f func() SigningMethod) { 15 | signingMethods[alg] = f 16 | } 17 | 18 | // Get a signing method from an "alg" string 19 | func GetSigningMethod(alg string) (method SigningMethod) { 20 | if methodF, ok := signingMethods[alg]; ok { 21 | method = methodF() 22 | } 23 | return 24 | } 25 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/github.com/codegangsta/negroni/doc.go: -------------------------------------------------------------------------------- 1 | // Package negroni is an idiomatic approach to web middleware in Go. It is tiny, non-intrusive, and encourages use of net/http Handlers. 2 | // 3 | // If you like the idea of Martini, but you think it contains too much magic, then Negroni is a great fit. 4 | // 5 | // For a full guide visit http://github.com/codegangsta/negroni 6 | // 7 | // package main 8 | // 9 | // import ( 10 | // "github.com/codegangsta/negroni" 11 | // "net/http" 12 | // "fmt" 13 | // ) 14 | // 15 | // func main() { 16 | // mux := http.NewServeMux() 17 | // mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { 18 | // fmt.Fprintf(w, "Welcome to the home page!") 19 | // }) 20 | // 21 | // n := negroni.Classic() 22 | // n.UseHandler(mux) 23 | // n.Run(":3000") 24 | // } 25 | package negroni 26 | -------------------------------------------------------------------------------- /go-web-master/chapter-6/negroni/auth.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net/http" 7 | 8 | "github.com/codegangsta/negroni" 9 | "github.com/gorilla/context" 10 | ) 11 | 12 | func Authorize(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) { 13 | token := r.Header.Get("X-AppToken") 14 | if token == "bXlVc2VybmFtZTpteVBhc3N3b3Jk" { 15 | log.Printf("Authorized to the system") 16 | context.Set(r, "user", "Shiju Varghese") 17 | next(w, r) 18 | } else { 19 | http.Error(w, "Not Authorized", 401) 20 | } 21 | } 22 | 23 | func index(w http.ResponseWriter, r *http.Request) { 24 | user := context.Get(r, "user") 25 | fmt.Fprintf(w, "Welcome %s!", user) 26 | } 27 | 28 | func main() { 29 | mux := http.NewServeMux() 30 | mux.HandleFunc("/", index) 31 | n := negroni.Classic() 32 | n.Use(negroni.HandlerFunc(Authorize)) 33 | n.UseHandler(mux) 34 | n.Run(":8080") 35 | } 36 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/github.com/codegangsta/negroni/logger.go: -------------------------------------------------------------------------------- 1 | package negroni 2 | 3 | import ( 4 | "log" 5 | "net/http" 6 | "os" 7 | "time" 8 | ) 9 | 10 | // Logger is a middleware handler that logs the request as it goes in and the response as it goes out. 11 | type Logger struct { 12 | // Logger inherits from log.Logger used to log messages with the Logger middleware 13 | *log.Logger 14 | } 15 | 16 | // NewLogger returns a new Logger instance 17 | func NewLogger() *Logger { 18 | return &Logger{log.New(os.Stdout, "[negroni] ", 0)} 19 | } 20 | 21 | func (l *Logger) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) { 22 | start := time.Now() 23 | l.Printf("Started %s %s", r.Method, r.URL.Path) 24 | 25 | next(rw, r) 26 | 27 | res := rw.(ResponseWriter) 28 | l.Printf("Completed %v %s in %v", res.Status(), http.StatusText(res.Status()), time.Since(start)) 29 | } 30 | -------------------------------------------------------------------------------- /go-web-master/chapter-5/texttemp/main1.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "os" 6 | "text/template" 7 | ) 8 | 9 | type Note struct { 10 | Title string 11 | Description string 12 | } 13 | 14 | const tmpl = `Notes are: 15 | {{range .}} 16 | Title: {{.Title}}, Description: {{.Description}} 17 | {{end}} 18 | ` 19 | 20 | func main() { 21 | //Create slice of Note objects 22 | notes := []Note{ 23 | {"text/template", "Template generates textual output"}, 24 | {"html/template", "Template generates HTML output"}, 25 | } 26 | 27 | //create a new template with a name 28 | t := template.New("note") 29 | 30 | //parse some content and generate a template 31 | t, err := t.Parse(tmpl) 32 | if err != nil { 33 | log.Fatal("Parse: ", err) 34 | return 35 | } 36 | 37 | //Applies a parsed template to the slice of Note objects 38 | if err := t.Execute(os.Stdout, notes); err != nil { 39 | log.Fatal("Execute: ", err) 40 | return 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /go-web-master/chapter-7/keys/demo.rsa: -------------------------------------------------------------------------------- 1 | -----BEGIN RSA PRIVATE KEY----- 2 | MIICWwIBAAKBgQDPSMNALgfEMEDbS3kCLiTlpx0S4tZH1jZLcGF5Pjhc9IuEIf7p 3 | 6obYT1W7urDPWM8JGO1mdx+GnJCnPcvFSsX8FjGwDqIp7afTdislYCJwQLXL7qPz 4 | wvG7ZlrtXrC9+0xkDGNxB+5Cui++8gWGbfTpTZiCiP413esxVQ30btKk2QIDAQAB 5 | AoGACfj1M9RDGWQ86pAB/WHc8pOMqYjySDh9GjoI5n1g1tAJGk1MZ1KaNDP06vg7 6 | Y25hX42sdj6K7L4Bk5o8gHxtc/IsheSeUFbdqbFdiAzTxgHq2zi1ZRPaxtNuw1Wk 7 | KPxcehMpXl/eKCY50+bkVUTvBtfPjRat0fSZnQ4X24zHcAECQQDtU1S/Lu/7vfKI 8 | BR9P2VoCfJvGuwpMcoaXcJuH9oEbeGKnSd7cKVeZdtuapHFjAm/yPWveOYmjrg6a 9 | CiPIgWoBAkEA35hIN/f6wzpLiKPB1TERO/YH1qrRKoM17Y7qcqh8pjmfgY/8we6m 10 | aGrFPd2eUVEpo5XMhQVpsluHmG8ZbXvK2QJAUlfueKM9ixg91WoJkjf03hYEKrDt 11 | Atdd0Z+1pzglVbWwbSDZXYROq6WsznwuB09qLh+XlLRcCFm1IUdRYRleAQJAWQI9 12 | FZKxD5CgSwetfNnom28IlcswMvVCvYvcBsLNxDpCJgiUvPrs4bpHRKZ5hLODmOxk 13 | GzwZZHgNVYA8phnWmQJAER8blPRwsHaEUdPLKWPffvlGPh8RJwpWtaneBOhkyylh 14 | HbPOBvC2WGJ7uXYTiXPHwOeLyRtUYx2GaoKQImi3sw== 15 | -----END RSA PRIVATE KEY----- 16 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/keys/app.rsa: -------------------------------------------------------------------------------- 1 | -----BEGIN RSA PRIVATE KEY----- 2 | MIICWwIBAAKBgQDPSMNALgfEMEDbS3kCLiTlpx0S4tZH1jZLcGF5Pjhc9IuEIf7p 3 | 6obYT1W7urDPWM8JGO1mdx+GnJCnPcvFSsX8FjGwDqIp7afTdislYCJwQLXL7qPz 4 | wvG7ZlrtXrC9+0xkDGNxB+5Cui++8gWGbfTpTZiCiP413esxVQ30btKk2QIDAQAB 5 | AoGACfj1M9RDGWQ86pAB/WHc8pOMqYjySDh9GjoI5n1g1tAJGk1MZ1KaNDP06vg7 6 | Y25hX42sdj6K7L4Bk5o8gHxtc/IsheSeUFbdqbFdiAzTxgHq2zi1ZRPaxtNuw1Wk 7 | KPxcehMpXl/eKCY50+bkVUTvBtfPjRat0fSZnQ4X24zHcAECQQDtU1S/Lu/7vfKI 8 | BR9P2VoCfJvGuwpMcoaXcJuH9oEbeGKnSd7cKVeZdtuapHFjAm/yPWveOYmjrg6a 9 | CiPIgWoBAkEA35hIN/f6wzpLiKPB1TERO/YH1qrRKoM17Y7qcqh8pjmfgY/8we6m 10 | aGrFPd2eUVEpo5XMhQVpsluHmG8ZbXvK2QJAUlfueKM9ixg91WoJkjf03hYEKrDt 11 | Atdd0Z+1pzglVbWwbSDZXYROq6WsznwuB09qLh+XlLRcCFm1IUdRYRleAQJAWQI9 12 | FZKxD5CgSwetfNnom28IlcswMvVCvYvcBsLNxDpCJgiUvPrs4bpHRKZ5hLODmOxk 13 | GzwZZHgNVYA8phnWmQJAER8blPRwsHaEUdPLKWPffvlGPh8RJwpWtaneBOhkyylh 14 | HbPOBvC2WGJ7uXYTiXPHwOeLyRtUYx2GaoKQImi3sw== 15 | -----END RSA PRIVATE KEY----- 16 | -------------------------------------------------------------------------------- /go-web-master/chapter-7/jwtauth/keys/app.rsa: -------------------------------------------------------------------------------- 1 | -----BEGIN RSA PRIVATE KEY----- 2 | MIICWwIBAAKBgQDPSMNALgfEMEDbS3kCLiTlpx0S4tZH1jZLcGF5Pjhc9IuEIf7p 3 | 6obYT1W7urDPWM8JGO1mdx+GnJCnPcvFSsX8FjGwDqIp7afTdislYCJwQLXL7qPz 4 | wvG7ZlrtXrC9+0xkDGNxB+5Cui++8gWGbfTpTZiCiP413esxVQ30btKk2QIDAQAB 5 | AoGACfj1M9RDGWQ86pAB/WHc8pOMqYjySDh9GjoI5n1g1tAJGk1MZ1KaNDP06vg7 6 | Y25hX42sdj6K7L4Bk5o8gHxtc/IsheSeUFbdqbFdiAzTxgHq2zi1ZRPaxtNuw1Wk 7 | KPxcehMpXl/eKCY50+bkVUTvBtfPjRat0fSZnQ4X24zHcAECQQDtU1S/Lu/7vfKI 8 | BR9P2VoCfJvGuwpMcoaXcJuH9oEbeGKnSd7cKVeZdtuapHFjAm/yPWveOYmjrg6a 9 | CiPIgWoBAkEA35hIN/f6wzpLiKPB1TERO/YH1qrRKoM17Y7qcqh8pjmfgY/8we6m 10 | aGrFPd2eUVEpo5XMhQVpsluHmG8ZbXvK2QJAUlfueKM9ixg91WoJkjf03hYEKrDt 11 | Atdd0Z+1pzglVbWwbSDZXYROq6WsznwuB09qLh+XlLRcCFm1IUdRYRleAQJAWQI9 12 | FZKxD5CgSwetfNnom28IlcswMvVCvYvcBsLNxDpCJgiUvPrs4bpHRKZ5hLODmOxk 13 | GzwZZHgNVYA8phnWmQJAER8blPRwsHaEUdPLKWPffvlGPh8RJwpWtaneBOhkyylh 14 | HbPOBvC2WGJ7uXYTiXPHwOeLyRtUYx2GaoKQImi3sw== 15 | -----END RSA PRIVATE KEY----- 16 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/routers/note.go: -------------------------------------------------------------------------------- 1 | package routers 2 | 3 | import ( 4 | "github.com/codegangsta/negroni" 5 | "github.com/gorilla/mux" 6 | "github.com/shijuvar/go-web/taskmanager/common" 7 | "github.com/shijuvar/go-web/taskmanager/controllers" 8 | ) 9 | 10 | func SetNoteRoutes(router *mux.Router) *mux.Router { 11 | noteRouter := mux.NewRouter() 12 | noteRouter.HandleFunc("/notes", controllers.CreateNote).Methods("POST") 13 | noteRouter.HandleFunc("/notes/{id}", controllers.UpdateNote).Methods("PUT") 14 | noteRouter.HandleFunc("/notes/{id}", controllers.GetNoteById).Methods("GET") 15 | noteRouter.HandleFunc("/notes", controllers.GetNotes).Methods("GET") 16 | noteRouter.HandleFunc("/notes/tasks/{id}", controllers.GetNotesByTask).Methods("GET") 17 | noteRouter.HandleFunc("/notes/{id}", controllers.DeleteNote).Methods("DELETE") 18 | router.PathPrefix("/notes").Handler(negroni.New( 19 | negroni.HandlerFunc(common.Authorize), 20 | negroni.Wrap(noteRouter), 21 | )) 22 | return router 23 | } 24 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/routers/task.go: -------------------------------------------------------------------------------- 1 | package routers 2 | 3 | import ( 4 | "github.com/codegangsta/negroni" 5 | "github.com/gorilla/mux" 6 | "github.com/shijuvar/go-web/taskmanager/common" 7 | "github.com/shijuvar/go-web/taskmanager/controllers" 8 | ) 9 | 10 | func SetTaskRoutes(router *mux.Router) *mux.Router { 11 | taskRouter := mux.NewRouter() 12 | taskRouter.HandleFunc("/tasks", controllers.CreateTask).Methods("POST") 13 | taskRouter.HandleFunc("/tasks/{id}", controllers.UpdateTask).Methods("PUT") 14 | taskRouter.HandleFunc("/tasks", controllers.GetTasks).Methods("GET") 15 | taskRouter.HandleFunc("/tasks/{id}", controllers.GetTaskById).Methods("GET") 16 | taskRouter.HandleFunc("/tasks/users/{id}", controllers.GetTasksByUser).Methods("GET") 17 | taskRouter.HandleFunc("/tasks/{id}", controllers.DeleteTask).Methods("DELETE") 18 | router.PathPrefix("/tasks").Handler(negroni.New( 19 | negroni.HandlerFunc(common.Authorize), 20 | negroni.Wrap(taskRouter), 21 | )) 22 | return router 23 | } 24 | -------------------------------------------------------------------------------- /go-web-master/chapter-11/cloudendpoint/endpoints.go: -------------------------------------------------------------------------------- 1 | package cloudendpoint 2 | 3 | import ( 4 | "log" 5 | 6 | "github.com/GoogleCloudPlatform/go-endpoints/endpoints" 7 | ) 8 | 9 | // Register the API endpoints 10 | func init() { 11 | taskService := &TaskService{} 12 | // Adds the TaskService to the server. 13 | api, err := endpoints.RegisterService( 14 | taskService, 15 | "tasks", 16 | "v1", 17 | "Tasks API", 18 | true, 19 | ) 20 | if err != nil { 21 | log.Fatalf("Register service: %v", err) 22 | } 23 | 24 | // Get ServiceMethod's MethodInfo for List method 25 | info := api.MethodByName("List").Info() 26 | // Provide values to MethodInfo - name, HTTP method, and path. 27 | info.Name, info.HTTPMethod, info.Path = "listTasks", "GET", "tasks" 28 | 29 | // Get ServiceMethod's MethodInfo for Add method 30 | info = api.MethodByName("Add").Info() 31 | info.Name, info.HTTPMethod, info.Path = "addTask", "POST", "tasks" 32 | // Calls DefaultServer's HandleHttp method using default serve mux 33 | endpoints.HandleHTTP() 34 | } 35 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/golang.org/x/crypto/bcrypt/base64.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package bcrypt 6 | 7 | import "encoding/base64" 8 | 9 | const alphabet = "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" 10 | 11 | var bcEncoding = base64.NewEncoding(alphabet) 12 | 13 | func base64Encode(src []byte) []byte { 14 | n := bcEncoding.EncodedLen(len(src)) 15 | dst := make([]byte, n) 16 | bcEncoding.Encode(dst, src) 17 | for dst[n-1] == '=' { 18 | n-- 19 | } 20 | return dst[:n] 21 | } 22 | 23 | func base64Decode(src []byte) ([]byte, error) { 24 | numOfEquals := 4 - (len(src) % 4) 25 | for i := 0; i < numOfEquals; i++ { 26 | src = append(src, '=') 27 | } 28 | 29 | dst := make([]byte, bcEncoding.DecodedLen(len(src))) 30 | n, err := bcEncoding.Decode(dst, src) 31 | if err != nil { 32 | return nil, err 33 | } 34 | return dst[:n], nil 35 | } 36 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/data/userRepository.go: -------------------------------------------------------------------------------- 1 | package data 2 | 3 | import ( 4 | "github.com/shijuvar/go-web/taskmanager/models" 5 | "golang.org/x/crypto/bcrypt" 6 | "gopkg.in/mgo.v2" 7 | "gopkg.in/mgo.v2/bson" 8 | ) 9 | 10 | type UserRepository struct { 11 | C *mgo.Collection 12 | } 13 | 14 | func (r *UserRepository) CreateUser(user *models.User) error { 15 | obj_id := bson.NewObjectId() 16 | user.Id = obj_id 17 | hpass, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost) 18 | if err != nil { 19 | panic(err) 20 | } 21 | user.HashPassword = hpass 22 | //clear the incoming text password 23 | user.Password = "" 24 | err = r.C.Insert(&user) 25 | return err 26 | } 27 | 28 | func (r *UserRepository) Login(user models.User) (u models.User, err error) { 29 | 30 | err = r.C.Find(bson.M{"email": user.Email}).One(&u) 31 | if err != nil { 32 | return 33 | } 34 | // Validate password 35 | err = bcrypt.CompareHashAndPassword(u.HashPassword, []byte(user.Password)) 36 | if err != nil { 37 | u = models.User{} 38 | } 39 | return 40 | } 41 | -------------------------------------------------------------------------------- /go-web-master/chapter-10/httptestbdd/lib/repository.go: -------------------------------------------------------------------------------- 1 | package lib 2 | 3 | import ( 4 | "errors" 5 | ) 6 | 7 | type User struct { 8 | FirstName string `json:"firstname"` 9 | LastName string `json:"lastname"` 10 | Email string `json:email"` 11 | } 12 | 13 | type UserRepository interface { 14 | GetAll() []User 15 | Create(User) error 16 | Validate(User) error 17 | } 18 | type InMemoryUserRepository struct { 19 | DataStore []User 20 | } 21 | 22 | func (repo *InMemoryUserRepository) GetAll() []User { 23 | return repo.DataStore 24 | } 25 | func (repo *InMemoryUserRepository) Create(user User) error { 26 | err := repo.Validate(user) 27 | if err != nil { 28 | return err 29 | } 30 | repo.DataStore = append(repo.DataStore, user) 31 | return nil 32 | } 33 | func (repo *InMemoryUserRepository) Validate(user User) error { 34 | for _, u := range repo.DataStore { 35 | if u.Email == user.Email { 36 | return errors.New("The Email is already exists") 37 | } 38 | } 39 | return nil 40 | } 41 | func NewInMemoryUserRepo() *InMemoryUserRepository { 42 | return &InMemoryUserRepository{DataStore: []User{}} 43 | } 44 | -------------------------------------------------------------------------------- /go-web-master/chapter-8/insert-map-slice.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | 7 | "gopkg.in/mgo.v2" 8 | "gopkg.in/mgo.v2/bson" 9 | ) 10 | 11 | type Category struct { 12 | Id bson.ObjectId `bson:"_id,omitempty"` 13 | Name string 14 | Description string 15 | } 16 | 17 | func main() { 18 | session, err := mgo.Dial("localhost") 19 | if err != nil { 20 | panic(err) 21 | } 22 | defer session.Close() 23 | session.SetMode(mgo.Monotonic, true) 24 | 25 | //get collection 26 | c := session.DB("taskdb").C("categories") 27 | c.RemoveAll(nil) 28 | doc := map[string]string{ 29 | "name": "Open Source", "description": "Tasks for open-source projects", 30 | } 31 | 32 | //insert a map object 33 | err = c.Insert(doc) 34 | if err != nil { 35 | log.Fatal(err) 36 | } 37 | doc1 := bson.D{ 38 | {"name", "Project"}, 39 | {"description", "Project Tasks"}, 40 | } 41 | err = c.Insert(doc1) 42 | if err != nil { 43 | log.Fatal(err) 44 | } 45 | var count int 46 | count, err = c.Count() 47 | if err != nil { 48 | log.Fatal(err) 49 | } 50 | fmt.Println("Count:", count) 51 | } 52 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2012 Dave Grijalva 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | 9 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/Godeps.json: -------------------------------------------------------------------------------- 1 | { 2 | "ImportPath": "github.com/shijuvar/go-web/taskmanager", 3 | "GoVersion": "go1.5.1", 4 | "Deps": [ 5 | { 6 | "ImportPath": "github.com/codegangsta/negroni", 7 | "Comment": "v0.1-70-gc7477ad", 8 | "Rev": "c7477ad8e330bef55bf1ebe300cf8aa67c492d1b" 9 | }, 10 | { 11 | "ImportPath": "github.com/dgrijalva/jwt-go", 12 | "Comment": "v2.2.0-23-g5ca8014", 13 | "Rev": "5ca80149b9d3f8b863af0e2bb6742e608603bd99" 14 | }, 15 | { 16 | "ImportPath": "github.com/gorilla/context", 17 | "Rev": "215affda49addc4c8ef7e2534915df2c8c35c6cd" 18 | }, 19 | { 20 | "ImportPath": "github.com/gorilla/mux", 21 | "Rev": "8a875a034c69b940914d83ea03d3f1299b4d094b" 22 | }, 23 | { 24 | "ImportPath": "golang.org/x/crypto/bcrypt", 25 | "Rev": "02a186af8b62cb007f392270669b91be5527d39c" 26 | }, 27 | { 28 | "ImportPath": "golang.org/x/crypto/blowfish", 29 | "Rev": "02a186af8b62cb007f392270669b91be5527d39c" 30 | }, 31 | { 32 | "ImportPath": "gopkg.in/mgo.v2", 33 | "Comment": "r2015.10.05-1-g4d04138", 34 | "Rev": "4d04138ffef2791c479c0c8bbffc30b34081b8d9" 35 | } 36 | ] 37 | } 38 | -------------------------------------------------------------------------------- /go-web-master/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Shiju Varghese 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /go-web-master/chapter-6/middleware/gorillahandlers.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net/http" 7 | "os" 8 | 9 | "github.com/gorilla/handlers" 10 | ) 11 | 12 | func index(w http.ResponseWriter, r *http.Request) { 13 | log.Println("Executing index handler") 14 | fmt.Fprintf(w, "Welcome!") 15 | } 16 | func about(w http.ResponseWriter, r *http.Request) { 17 | log.Println("Executing about handler") 18 | fmt.Fprintf(w, "Go Middleware") 19 | } 20 | func iconHandler(w http.ResponseWriter, r *http.Request) { 21 | http.ServeFile(w, r, "./favicon.ico") 22 | } 23 | func main() { 24 | http.HandleFunc("/favicon.ico", iconHandler) 25 | indexHandler := http.HandlerFunc(index) 26 | aboutHandler := http.HandlerFunc(about) 27 | logFile, err := os.OpenFile("server.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666) 28 | if err != nil { 29 | panic(err) 30 | } 31 | http.Handle("/", handlers.LoggingHandler(logFile, handlers.CompressHandler(indexHandler))) 32 | http.Handle("/about", handlers.LoggingHandler(logFile, handlers.CompressHandler(aboutHandler))) 33 | server := &http.Server{ 34 | Addr: ":8080", 35 | } 36 | log.Println("Listening...") 37 | server.ListenAndServe() 38 | } 39 | -------------------------------------------------------------------------------- /go-web-master/chapter-6/middleware/logger.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net/http" 7 | "time" 8 | ) 9 | 10 | func loggingHandler(next http.Handler) http.Handler { 11 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 12 | start := time.Now() 13 | log.Printf("Started %s %s", r.Method, r.URL.Path) 14 | next.ServeHTTP(w, r) 15 | log.Printf("Completed %s in %v", r.URL.Path, time.Since(start)) 16 | }) 17 | } 18 | func index(w http.ResponseWriter, r *http.Request) { 19 | log.Println("Executing index handler") 20 | fmt.Fprintf(w, "Welcome!") 21 | } 22 | func about(w http.ResponseWriter, r *http.Request) { 23 | log.Println("Executing about handler") 24 | fmt.Fprintf(w, "Go Middleware") 25 | } 26 | func iconHandler(w http.ResponseWriter, r *http.Request) { 27 | } 28 | 29 | func main() { 30 | http.HandleFunc("/favicon.ico", iconHandler) 31 | indexHandler := http.HandlerFunc(index) 32 | aboutHandler := http.HandlerFunc(about) 33 | http.Handle("/", loggingHandler(indexHandler)) 34 | http.Handle("/about", loggingHandler(aboutHandler)) 35 | server := &http.Server{ 36 | Addr: ":8080", 37 | } 38 | log.Println("Listening...") 39 | server.ListenAndServe() 40 | } 41 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/github.com/codegangsta/negroni/recovery.go: -------------------------------------------------------------------------------- 1 | package negroni 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net/http" 7 | "os" 8 | "runtime" 9 | ) 10 | 11 | // Recovery is a Negroni middleware that recovers from any panics and writes a 500 if there was one. 12 | type Recovery struct { 13 | Logger *log.Logger 14 | PrintStack bool 15 | StackAll bool 16 | StackSize int 17 | } 18 | 19 | // NewRecovery returns a new instance of Recovery 20 | func NewRecovery() *Recovery { 21 | return &Recovery{ 22 | Logger: log.New(os.Stdout, "[negroni] ", 0), 23 | PrintStack: true, 24 | StackAll: false, 25 | StackSize: 1024 * 8, 26 | } 27 | } 28 | 29 | func (rec *Recovery) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) { 30 | defer func() { 31 | if err := recover(); err != nil { 32 | rw.WriteHeader(http.StatusInternalServerError) 33 | stack := make([]byte, rec.StackSize) 34 | stack = stack[:runtime.Stack(stack, rec.StackAll)] 35 | 36 | f := "PANIC: %s\n%s" 37 | rec.Logger.Printf(f, err, stack) 38 | 39 | if rec.PrintStack { 40 | fmt.Fprintf(rw, f, err, stack) 41 | } 42 | } 43 | }() 44 | 45 | next(rw, r) 46 | } 47 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/github.com/codegangsta/negroni/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Jeremy Saenz 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/models/models.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | import ( 4 | "time" 5 | 6 | "gopkg.in/mgo.v2/bson" 7 | ) 8 | 9 | type ( 10 | User struct { 11 | Id bson.ObjectId `bson:"_id,omitempty" json:"id"` 12 | FirstName string `json:"firstname"` 13 | LastName string `json:"lastname"` 14 | Email string `json:"email"` 15 | Password string `json:"password,omitempty"` 16 | HashPassword []byte `json:"hashpassword,omitempty"` 17 | } 18 | Task struct { 19 | Id bson.ObjectId `bson:"_id,omitempty" json:"id"` 20 | CreatedBy string `json:"createdby"` 21 | Name string `json:"name"` 22 | Description string `json:"description"` 23 | CreatedOn time.Time `json:"createdon,omitempty"` 24 | Due time.Time `json:"due,omitempty"` 25 | Status string `json:"status,omitempty"` 26 | Tags []string `json:"tags,omitempty"` 27 | } 28 | TaskNote struct { 29 | Id bson.ObjectId `bson:"_id,omitempty" json:"id"` 30 | TaskId bson.ObjectId `json:"taskid"` 31 | Description string `json:"description"` 32 | CreatedOn time.Time `json:"createdon,omitempty"` 33 | } 34 | ) 35 | -------------------------------------------------------------------------------- /go-web-master/chapter-10/httptestbdd/lib/handlers.go: -------------------------------------------------------------------------------- 1 | package lib 2 | 3 | import ( 4 | "encoding/json" 5 | "net/http" 6 | 7 | "github.com/gorilla/mux" 8 | ) 9 | 10 | func GetUsers(repo UserRepository) http.Handler { 11 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 12 | userStore := repo.GetAll() 13 | users, err := json.Marshal(userStore) 14 | 15 | if err != nil { 16 | w.WriteHeader(http.StatusInternalServerError) 17 | return 18 | } 19 | w.Header().Set("Content-Type", "application/json") 20 | w.WriteHeader(http.StatusOK) 21 | w.Write(users) 22 | }) 23 | } 24 | func CreateUser(repo UserRepository) http.Handler { 25 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 26 | var user User 27 | err := json.NewDecoder(r.Body).Decode(&user) 28 | if err != nil { 29 | w.WriteHeader(http.StatusInternalServerError) 30 | return 31 | } 32 | err = repo.Create(user) 33 | if err != nil { 34 | w.WriteHeader(http.StatusBadRequest) 35 | return 36 | } 37 | w.WriteHeader(http.StatusCreated) 38 | }) 39 | } 40 | func SetUserRoutes() *mux.Router { 41 | userRepository := NewInMemoryUserRepo() 42 | r := mux.NewRouter() 43 | r.Handle("/users", CreateUser(userRepository)).Methods("POST") 44 | r.Handle("/users", GetUsers(userRepository)).Methods("GET") 45 | return r 46 | } 47 | -------------------------------------------------------------------------------- /go-web-master/chapter-8/index.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | 7 | "gopkg.in/mgo.v2" 8 | "gopkg.in/mgo.v2/bson" 9 | ) 10 | 11 | type Category struct { 12 | Id bson.ObjectId `bson:"_id,omitempty"` 13 | Name string 14 | Description string 15 | } 16 | 17 | func main() { 18 | session, err := mgo.Dial("localhost") 19 | if err != nil { 20 | panic(err) 21 | } 22 | defer session.Close() 23 | 24 | session.SetMode(mgo.Monotonic, true) 25 | 26 | c := session.DB("taskdb").C("categories") 27 | c.RemoveAll(nil) 28 | // Index 29 | index := mgo.Index{ 30 | Key: []string{"name"}, 31 | Unique: true, 32 | DropDups: true, 33 | Background: true, 34 | Sparse: true, 35 | } 36 | 37 | err = c.EnsureIndex(index) 38 | if err != nil { 39 | panic(err) 40 | } 41 | 42 | //insert three category objects 43 | err = c.Insert( 44 | &Category{bson.NewObjectId(), "Open-Source", "Tasks for open-source projects"}, 45 | &Category{bson.NewObjectId(), "R & D", "R & D Tasks"}, 46 | &Category{bson.NewObjectId(), "Project", "Project Tasks"}, 47 | ) 48 | if err != nil { 49 | panic(err) 50 | } 51 | 52 | result := Category{} 53 | err = c.Find(bson.M{"name": "Open-Source"}).One(&result) 54 | if err != nil { 55 | log.Fatal(err) 56 | } else { 57 | fmt.Println("Description:", result.Description) 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /go-web-master/chapter-11/gae-server/task.go: -------------------------------------------------------------------------------- 1 | package task 2 | 3 | import ( 4 | "fmt" 5 | "html/template" 6 | "net/http" 7 | ) 8 | 9 | type Task struct { 10 | Name string 11 | Description string 12 | } 13 | 14 | const taskForm = ` 15 | 16 | 17 |
18 |

Task Name:

19 |

Description:

20 |

21 |
22 | 23 | 24 | ` 25 | const taskTemplateHTML = ` 26 | 27 | 28 |

New Task has been created:

29 |
Task: {{.Name}}
30 |
Description: {{.Description}}
31 | 32 | 33 | ` 34 | 35 | var taskTemplate = template.Must(template.New("task").Parse(taskTemplateHTML)) 36 | 37 | func init() { 38 | http.HandleFunc("/", index) 39 | http.HandleFunc("/task", task) 40 | } 41 | 42 | func index(w http.ResponseWriter, r *http.Request) { 43 | fmt.Fprint(w, taskForm) 44 | } 45 | 46 | func task(w http.ResponseWriter, r *http.Request) { 47 | task := Task{ 48 | Name: r.FormValue("taskname"), 49 | Description: r.FormValue("description"), 50 | } 51 | err := taskTemplate.Execute(w, task) 52 | if err != nil { 53 | http.Error(w, err.Error(), http.StatusInternalServerError) 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /go-web-master/chapter-11/hybridapplib/handler.go: -------------------------------------------------------------------------------- 1 | package hybridapplib 2 | 3 | import ( 4 | "fmt" 5 | "html/template" 6 | "net/http" 7 | ) 8 | 9 | type Task struct { 10 | Name string 11 | Description string 12 | } 13 | 14 | const taskForm = ` 15 | 16 | 17 |
18 |

Task Name:

19 |

Description:

20 |

21 |
22 | 23 | 24 | ` 25 | const taskTemplateHTML = ` 26 | 27 | 28 |

New Task has been created:

29 |
Task: {{.Name}}
30 |
Description: {{.Description}}
31 | 32 | 33 | ` 34 | 35 | var taskTemplate = template.Must(template.New("task").Parse(taskTemplateHTML)) 36 | 37 | func init() { 38 | http.HandleFunc("/", index) 39 | http.HandleFunc("/task", task) 40 | } 41 | 42 | func index(w http.ResponseWriter, r *http.Request) { 43 | fmt.Fprint(w, taskForm) 44 | } 45 | 46 | func task(w http.ResponseWriter, r *http.Request) { 47 | task := Task{ 48 | Name: r.FormValue("taskname"), 49 | Description: r.FormValue("description"), 50 | } 51 | err := taskTemplate.Execute(w, task) 52 | if err != nil { 53 | http.Error(w, err.Error(), http.StatusInternalServerError) 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /go-web-master/chapter-11/cloudendpoint/task.go: -------------------------------------------------------------------------------- 1 | package cloudendpoint 2 | 3 | import ( 4 | "time" 5 | 6 | "golang.org/x/net/context" 7 | "google.golang.org/appengine/datastore" 8 | ) 9 | 10 | // Task is a datastore entity 11 | type Task struct { 12 | Key *datastore.Key `json:"id" datastore:"-"` 13 | Name string `json:"name" endpoints:"req"` 14 | Description string `json:"description" datastore:",noindex" endpoints:"req"` 15 | CreatedOn time.Time `json:"createdon,omitempty"` 16 | } 17 | 18 | // Tasks is a response type of TaskService.List method 19 | type Tasks struct { 20 | Tasks []Task `json:"tasks"` 21 | } 22 | 23 | // Struct is used to add API method 24 | type TaskService struct { 25 | } 26 | 27 | // List returns a list of all the existing tasks. 28 | func (ts *TaskService) List(c context.Context) (*Tasks, error) { 29 | tasks := []Task{} 30 | keys, err := datastore.NewQuery("tasks").Order("-CreatedOn").GetAll(c, &tasks) 31 | if err != nil { 32 | return nil, err 33 | } 34 | 35 | for i, k := range keys { 36 | tasks[i].Key = k 37 | } 38 | return &Tasks{tasks}, nil 39 | } 40 | 41 | // Add inserts a new Task into Datastore 42 | func (ts *TaskService) Add(c context.Context, t *Task) error { 43 | t.CreatedOn = time.Now() 44 | key := datastore.NewIncompleteKey(c, "tasks", nil) 45 | _, err := datastore.Put(c, key, t) 46 | return err 47 | } 48 | -------------------------------------------------------------------------------- /go-web-master/chapter-11/onpremises-server/task.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "html/template" 6 | "net/http" 7 | ) 8 | 9 | type Task struct { 10 | Name string 11 | Description string 12 | } 13 | 14 | func main() { 15 | http.HandleFunc("/", index) 16 | http.HandleFunc("/task", task) 17 | http.ListenAndServe(":8080",nil) 18 | } 19 | 20 | const taskForm = ` 21 | 22 | 23 |
24 |

Task Name:

25 |

Description:

26 |

27 |
28 | 29 | 30 | ` 31 | const taskTemplateHTML = ` 32 | 33 | 34 |

New Task has been added:

35 |
Task: {{.Name}}
36 |
Description: {{.Description}}
37 | 38 | 39 | ` 40 | 41 | var taskTemplate = template.Must(template.New("task").Parse(taskTemplateHTML)) 42 | 43 | func index(w http.ResponseWriter, r *http.Request) { 44 | fmt.Fprint(w, taskForm) 45 | } 46 | 47 | func task(w http.ResponseWriter, r *http.Request) { 48 | task := Task{ 49 | Name: r.FormValue("taskname"), 50 | Description: r.FormValue("description"), 51 | } 52 | err := taskTemplate.Execute(w, task) 53 | if err != nil { 54 | http.Error(w, err.Error(), http.StatusInternalServerError) 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/gopkg.in/mgo.v2/doc.go: -------------------------------------------------------------------------------- 1 | // Package mgo offers a rich MongoDB driver for Go. 2 | // 3 | // Details about the mgo project (pronounced as "mango") are found 4 | // in its web page: 5 | // 6 | // http://labix.org/mgo 7 | // 8 | // Usage of the driver revolves around the concept of sessions. To 9 | // get started, obtain a session using the Dial function: 10 | // 11 | // session, err := mgo.Dial(url) 12 | // 13 | // This will establish one or more connections with the cluster of 14 | // servers defined by the url parameter. From then on, the cluster 15 | // may be queried with multiple consistency rules (see SetMode) and 16 | // documents retrieved with statements such as: 17 | // 18 | // c := session.DB(database).C(collection) 19 | // err := c.Find(query).One(&result) 20 | // 21 | // New sessions are typically created by calling session.Copy on the 22 | // initial session obtained at dial time. These new sessions will share 23 | // the same cluster information and connection pool, and may be easily 24 | // handed into other methods and functions for organizing logic. 25 | // Every session created must have its Close method called at the end 26 | // of its life time, so its resources may be put back in the pool or 27 | // collected, depending on the case. 28 | // 29 | // For more details, see the documentation for the types and methods. 30 | // 31 | package mgo 32 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/errors.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "errors" 5 | ) 6 | 7 | // Error constants 8 | var ( 9 | ErrInvalidKey = errors.New("key is invalid or of invalid type") 10 | ErrHashUnavailable = errors.New("the requested hash function is unavailable") 11 | ErrNoTokenInRequest = errors.New("no token present in request") 12 | ) 13 | 14 | // The errors that might occur when parsing and validating a token 15 | const ( 16 | ValidationErrorMalformed uint32 = 1 << iota // Token is malformed 17 | ValidationErrorUnverifiable // Token could not be verified because of signing problems 18 | ValidationErrorSignatureInvalid // Signature validation failed 19 | ValidationErrorExpired // Exp validation failed 20 | ValidationErrorNotValidYet // NBF validation failed 21 | ) 22 | 23 | // The error from Parse if token is not valid 24 | type ValidationError struct { 25 | err string 26 | Errors uint32 // bitfield. see ValidationError... constants 27 | } 28 | 29 | // Validation error is an error type 30 | func (e ValidationError) Error() string { 31 | if e.err == "" { 32 | return "token is invalid" 33 | } 34 | return e.err 35 | } 36 | 37 | // No errors 38 | func (e *ValidationError) valid() bool { 39 | if e.Errors > 0 { 40 | return false 41 | } 42 | return true 43 | } 44 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/golang.org/x/crypto/PATENTS: -------------------------------------------------------------------------------- 1 | Additional IP Rights Grant (Patents) 2 | 3 | "This implementation" means the copyrightable works distributed by 4 | Google as part of the Go project. 5 | 6 | Google hereby grants to You a perpetual, worldwide, non-exclusive, 7 | no-charge, royalty-free, irrevocable (except as stated in this section) 8 | patent license to make, have made, use, offer to sell, sell, import, 9 | transfer and otherwise run, modify and propagate the contents of this 10 | implementation of Go, where such license applies only to those patent 11 | claims, both currently owned or controlled by Google and acquired in 12 | the future, licensable by Google that are necessarily infringed by this 13 | implementation of Go. This grant does not include claims that would be 14 | infringed only as a consequence of further modification of this 15 | implementation. If you or your agent or exclusive licensee institute or 16 | order or agree to the institution of patent litigation against any 17 | entity (including a cross-claim or counterclaim in a lawsuit) alleging 18 | that this implementation of Go or any code incorporated within this 19 | implementation of Go constitutes direct or contributory patent 20 | infringement, or inducement of patent infringement, then any patent 21 | rights granted to you under this License for this implementation of Go 22 | shall terminate as of the date such litigation is filed. 23 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/controllers/resources.go: -------------------------------------------------------------------------------- 1 | package controllers 2 | 3 | import ( 4 | "github.com/shijuvar/go-web/taskmanager/models" 5 | ) 6 | 7 | //Models for JSON resources 8 | type ( 9 | //For Post - /user/register 10 | UserResource struct { 11 | Data models.User `json:"data"` 12 | } 13 | //For Post - /user/login 14 | LoginResource struct { 15 | Data LoginModel `json:"data"` 16 | } 17 | //Response for authorized user Post - /user/login 18 | AuthUserResource struct { 19 | Data AuthUserModel `json:"data"` 20 | } 21 | // For Post/Put - /tasks 22 | // For Get - /tasks/id 23 | TaskResource struct { 24 | Data models.Task `json:"data"` 25 | } 26 | // For Get - /tasks 27 | TasksResource struct { 28 | Data []models.Task `json:"data"` 29 | } 30 | // For Post/Put - /notes 31 | NoteResource struct { 32 | Data NoteModel `json:"data"` 33 | } 34 | // For Get - /notes 35 | // For /notes/tasks/id 36 | NotesResource struct { 37 | Data []models.TaskNote `json:"data"` 38 | } 39 | //Model for authentication 40 | LoginModel struct { 41 | Email string `json:"email"` 42 | Password string `json:"password"` 43 | } 44 | //Model for authorized user with access token 45 | AuthUserModel struct { 46 | User models.User `json:"user"` 47 | Token string `json:"token"` 48 | } 49 | //Model for a TaskNote 50 | NoteModel struct { 51 | TaskId string `json:"taskid"` 52 | Description string `json:"description"` 53 | } 54 | ) 55 | -------------------------------------------------------------------------------- /go-web-master/chapter-6/middleware/server.log: -------------------------------------------------------------------------------- 1 | ::1 - - [26/Apr/2015:16:42:41 +0530] "GET / HTTP/1.1" 200 32 2 | ::1 - - [26/Apr/2015:16:42:45 +0530] "GET /about HTTP/1.1" 200 37 3 | 61.160.213.33 - - [26/Apr/2015:17:09:31 +0530] "GET /cgi-bin/chs/numreg/init HTTP/1.1" 200 8 4 | 61.160.213.33 - - [26/Apr/2015:17:09:31 +0530] "GET /cgi-bin/chs/numreg/init HTTP/1.1" 200 8 5 | 222.186.50.73 - - [26/Apr/2015:17:23:15 +0530] "GET / HTTP/1.1" 200 8 6 | 61.160.213.33 - - [26/Apr/2015:18:17:51 +0530] "GET /cgi-bin/chs/numreg/init HTTP/1.1" 200 8 7 | 61.160.213.33 - - [26/Apr/2015:19:26:11 +0530] "GET /cgi-bin/chs/numreg/init HTTP/1.1" 200 8 8 | 61.160.213.33 - - [26/Apr/2015:19:43:21 +0530] "GET /cgi-bin/chs/numreg/init HTTP/1.1" 200 8 9 | 61.160.213.33 - - [26/Apr/2015:19:43:21 +0530] "GET /cgi-bin/chs/numreg/init HTTP/1.1" 200 8 10 | 61.160.213.33 - - [26/Apr/2015:19:43:21 +0530] "GET /cgi-bin/chs/numreg/init HTTP/1.1" 200 8 11 | 180.153.100.126 - - [26/Apr/2015:20:05:16 +0530] "GET /manager/html HTTP/1.1" 200 8 12 | ::1 - - [26/Apr/2015:21:26:47 +0530] "GET / HTTP/1.1" 200 32 13 | ::1 - - [26/Apr/2015:21:26:53 +0530] "GET /about HTTP/1.1" 200 37 14 | ::1 - - [27/Apr/2015:10:27:52 +0530] "GET / HTTP/1.1" 200 97 15 | ::1 - - [27/Apr/2015:10:27:53 +0530] "GET / HTTP/1.1" 200 97 16 | ::1 - - [27/Apr/2015:10:28:00 +0530] "GET /about HTTP/1.1" 200 131 17 | ::1 - - [27/Apr/2015:10:30:53 +0530] "GET / HTTP/1.1" 200 97 18 | ::1 - - [27/Apr/2015:10:50:05 +0530] "GET /about HTTP/1.1" 200 131 19 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/gopkg.in/mgo.v2/bson/LICENSE: -------------------------------------------------------------------------------- 1 | BSON library for Go 2 | 3 | Copyright (c) 2010-2012 - Gustavo Niemeyer 4 | 5 | All rights reserved. 6 | 7 | Redistribution and use in source and binary forms, with or without 8 | modification, are permitted provided that the following conditions are met: 9 | 10 | 1. Redistributions of source code must retain the above copyright notice, this 11 | list of conditions and the following disclaimer. 12 | 2. Redistributions in binary form must reproduce the above copyright notice, 13 | this list of conditions and the following disclaimer in the documentation 14 | and/or other materials provided with the distribution. 15 | 16 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 20 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/gopkg.in/mgo.v2/LICENSE: -------------------------------------------------------------------------------- 1 | mgo - MongoDB driver for Go 2 | 3 | Copyright (c) 2010-2013 - Gustavo Niemeyer 4 | 5 | All rights reserved. 6 | 7 | Redistribution and use in source and binary forms, with or without 8 | modification, are permitted provided that the following conditions are met: 9 | 10 | 1. Redistributions of source code must retain the above copyright notice, this 11 | list of conditions and the following disclaimer. 12 | 2. Redistributions in binary form must reproduce the above copyright notice, 13 | this list of conditions and the following disclaimer in the documentation 14 | and/or other materials provided with the distribution. 15 | 16 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 20 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/common/utils.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | import ( 4 | "encoding/json" 5 | "log" 6 | "net/http" 7 | "os" 8 | ) 9 | 10 | type ( 11 | appError struct { 12 | Error string `json:"error"` 13 | Message string `json:"message"` 14 | HttpStatus int `json:"status"` 15 | } 16 | errorResource struct { 17 | Data appError `json:"data"` 18 | } 19 | configuration struct { 20 | Server, MongoDBHost, DBUser, DBPwd, Database string 21 | } 22 | ) 23 | 24 | func DisplayAppError(w http.ResponseWriter, handlerError error, message string, code int) { 25 | errObj := appError{ 26 | Error: handlerError.Error(), 27 | Message: message, 28 | HttpStatus: code, 29 | } 30 | log.Printf("AppError]: %s\n", handlerError) 31 | w.Header().Set("Content-Type", "application/json; charset=utf-8") 32 | w.WriteHeader(code) 33 | if j, err := json.Marshal(errorResource{Data: errObj}); err == nil { 34 | w.Write(j) 35 | } 36 | } 37 | 38 | // AppConfig holds the configuration values from config.json file 39 | var AppConfig configuration 40 | 41 | // Initialize AppConfig 42 | func initConfig() { 43 | loadAppConfig() 44 | } 45 | 46 | // Reads config.json and decode into AppConfig 47 | func loadAppConfig() { 48 | file, err := os.Open("common/config.json") 49 | defer file.Close() 50 | if err != nil { 51 | log.Fatalf("[loadConfig]: %s\n", err) 52 | } 53 | decoder := json.NewDecoder(file) 54 | AppConfig = configuration{} 55 | err = decoder.Decode(&AppConfig) 56 | if err != nil { 57 | log.Fatalf("[loadAppConfig]: %s\n", err) 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /go-web-master/chapter-8/insert-struct.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | 7 | "gopkg.in/mgo.v2" 8 | "gopkg.in/mgo.v2/bson" 9 | ) 10 | 11 | type Category struct { 12 | Id bson.ObjectId `bson:"_id,omitempty"` 13 | Name string 14 | Description string 15 | } 16 | 17 | func main() { 18 | session, err := mgo.Dial("localhost") 19 | if err != nil { 20 | panic(err) 21 | } 22 | defer session.Close() 23 | 24 | // Optional. Switch the session to a monotonic behavior. 25 | // Reads may not be entirely up-to-date, but they will always see the 26 | // history of changes moving forward, the data read will be consistent 27 | // across sequential queries in the same session, and modifications made 28 | // within the session will be observed in following queries (read-your-writes). 29 | // http://godoc.org/labix.org/v2/mgo#Session.SetMode 30 | session.SetMode(mgo.Monotonic, true) 31 | 32 | //get collection 33 | c := session.DB("taskdb").C("categories") 34 | 35 | doc := Category{ 36 | bson.NewObjectId(), 37 | "Open Source", 38 | "Tasks for open-source projects", 39 | } 40 | //insert a category object 41 | err = c.Insert(&doc) 42 | if err != nil { 43 | log.Fatal(err) 44 | } 45 | 46 | //insert two category objects 47 | err = c.Insert(&Category{bson.NewObjectId(), "R & D", "R & D Tasks"}, 48 | &Category{bson.NewObjectId(), "Project", "Project Tasks"}) 49 | 50 | var count int 51 | count, err = c.Count() 52 | if err != nil { 53 | log.Fatal(err) 54 | } else { 55 | fmt.Printf("%d records inserted", count) 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /go-web-master/chapter-8/insert-embedded.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "time" 7 | 8 | "gopkg.in/mgo.v2" 9 | "gopkg.in/mgo.v2/bson" 10 | ) 11 | 12 | type Task struct { 13 | Description string 14 | Due time.Time 15 | } 16 | type Category struct { 17 | Id bson.ObjectId `bson:"_id,omitempty"` 18 | Name string 19 | Description string 20 | Tasks []Task 21 | } 22 | 23 | func main() { 24 | session, err := mgo.Dial("localhost") 25 | if err != nil { 26 | panic(err) 27 | } 28 | defer session.Close() 29 | session.SetMode(mgo.Monotonic, true) 30 | //get collection 31 | c := session.DB("taskdb").C("categories") 32 | c.RemoveAll(nil) 33 | doc := Category{ 34 | bson.NewObjectId(), 35 | "Open Source", 36 | "Tasks for open-source projects", 37 | []Task{ 38 | Task{"Create project in mgo", time.Date(2015, time.August, 10, 0, 0, 0, 0, time.UTC)}, 39 | Task{"Create REST API", time.Date(2015, time.August, 20, 0, 0, 0, 0, time.UTC)}, 40 | }, 41 | } 42 | //insert a Category object with embedded Tasks 43 | err = c.Insert(&doc) 44 | if err != nil { 45 | log.Fatal(err) 46 | } 47 | 48 | var count int 49 | count, err = c.Count() 50 | if err != nil { 51 | log.Fatal(err) 52 | } 53 | fmt.Printf("%d records inserted", count) 54 | 55 | iter := c.Find(nil).Iter() 56 | result := Category{} 57 | for iter.Next(&result) { 58 | fmt.Printf("Name:%s, Description:%s\n", result.Name, result.Description) 59 | tasks := result.Tasks 60 | for _, v := range tasks { 61 | fmt.Println(v.Description) 62 | fmt.Println(v.Due) 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /go-web-master/chapter-6/negroni/flowcontrol.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net/http" 7 | 8 | "github.com/codegangsta/negroni" 9 | ) 10 | 11 | func middlewareFirst(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) { 12 | log.Println("MiddlewareFirst - Before Handler") 13 | next(w, r) 14 | log.Println("MiddlewareFirst - After Handler") 15 | } 16 | 17 | func middlewareSecond(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) { 18 | log.Println("MiddlewareSecond - Before Handler") 19 | if r.URL.Path == "/message" { 20 | if r.URL.Query().Get("password") == "pass123" { 21 | log.Println("Authorized to the system") 22 | next(w, r) 23 | } else { 24 | log.Println("Failed to authorize to the system") 25 | return 26 | } 27 | } else { 28 | next(w, r) 29 | } 30 | log.Println("MiddlewareSecond - After Handler") 31 | } 32 | 33 | func index(w http.ResponseWriter, r *http.Request) { 34 | log.Println("Executing index Handler") 35 | fmt.Fprintf(w, "Welcome") 36 | } 37 | func message(w http.ResponseWriter, r *http.Request) { 38 | log.Println("Executing message Handler") 39 | fmt.Fprintf(w, "HTTP Middleware is awesome") 40 | } 41 | 42 | func iconHandler(w http.ResponseWriter, r *http.Request) { 43 | } 44 | func main() { 45 | mux := http.NewServeMux() 46 | mux.HandleFunc("/favicon.ico", iconHandler) 47 | mux.HandleFunc("/", index) 48 | mux.HandleFunc("/message", message) 49 | n := negroni.Classic() 50 | n.Use(negroni.HandlerFunc(middlewareFirst)) 51 | n.Use(negroni.HandlerFunc(middlewareSecond)) 52 | n.UseHandler(mux) 53 | n.Run(":8080") 54 | } 55 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/data/noteRepository.go: -------------------------------------------------------------------------------- 1 | package data 2 | 3 | import ( 4 | "time" 5 | 6 | "github.com/shijuvar/go-web/taskmanager/models" 7 | "gopkg.in/mgo.v2" 8 | "gopkg.in/mgo.v2/bson" 9 | ) 10 | 11 | type NoteRepository struct { 12 | C *mgo.Collection 13 | } 14 | 15 | func (r *NoteRepository) Create(note *models.TaskNote) error { 16 | obj_id := bson.NewObjectId() 17 | note.Id = obj_id 18 | note.CreatedOn = time.Now() 19 | err := r.C.Insert(¬e) 20 | return err 21 | } 22 | 23 | func (r *NoteRepository) Update(note *models.TaskNote) error { 24 | // partial update on MogoDB 25 | err := r.C.Update(bson.M{"_id": note.Id}, 26 | bson.M{"$set": bson.M{ 27 | "description": note.Description, 28 | }}) 29 | return err 30 | } 31 | func (r *NoteRepository) Delete(id string) error { 32 | err := r.C.Remove(bson.M{"_id": bson.ObjectIdHex(id)}) 33 | return err 34 | } 35 | func (r *NoteRepository) GetByTask(id string) []models.TaskNote { 36 | var notes []models.TaskNote 37 | taskid := bson.ObjectIdHex(id) 38 | iter := r.C.Find(bson.M{"taskid": taskid}).Iter() 39 | result := models.TaskNote{} 40 | for iter.Next(&result) { 41 | notes = append(notes, result) 42 | } 43 | return notes 44 | } 45 | func (r *NoteRepository) GetAll() []models.TaskNote { 46 | var notes []models.TaskNote 47 | iter := r.C.Find(nil).Iter() 48 | result := models.TaskNote{} 49 | for iter.Next(&result) { 50 | notes = append(notes, result) 51 | } 52 | return notes 53 | } 54 | func (r *NoteRepository) GetById(id string) (note models.TaskNote, err error) { 55 | err = r.C.FindId(bson.ObjectIdHex(id)).One(¬e) 56 | return 57 | } 58 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/github.com/gorilla/mux/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2012 Rodrigo Moraes. All rights reserved. 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions are 5 | met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above 10 | copyright notice, this list of conditions and the following disclaimer 11 | in the documentation and/or other materials provided with the 12 | distribution. 13 | * Neither the name of Google Inc. nor the names of its 14 | contributors may be used to endorse or promote products derived from 15 | this software without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 18 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 19 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 20 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 21 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 22 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 23 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/golang.org/x/crypto/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2009 The Go Authors. All rights reserved. 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions are 5 | met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above 10 | copyright notice, this list of conditions and the following disclaimer 11 | in the documentation and/or other materials provided with the 12 | distribution. 13 | * Neither the name of Google Inc. nor the names of its 14 | contributors may be used to endorse or promote products derived from 15 | this software without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 18 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 19 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 20 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 21 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 22 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 23 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/github.com/gorilla/context/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2012 Rodrigo Moraes. All rights reserved. 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions are 5 | met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above 10 | copyright notice, this list of conditions and the following disclaimer 11 | in the documentation and/or other materials provided with the 12 | distribution. 13 | * Neither the name of Google Inc. nor the names of its 14 | contributors may be used to endorse or promote products derived from 15 | this software without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 18 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 19 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 20 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 21 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 22 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 23 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/data/taskRepository.go: -------------------------------------------------------------------------------- 1 | package data 2 | 3 | import ( 4 | "time" 5 | 6 | "github.com/shijuvar/go-web/taskmanager/models" 7 | "gopkg.in/mgo.v2" 8 | "gopkg.in/mgo.v2/bson" 9 | ) 10 | 11 | type TaskRepository struct { 12 | C *mgo.Collection 13 | } 14 | 15 | func (r *TaskRepository) Create(task *models.Task) error { 16 | obj_id := bson.NewObjectId() 17 | task.Id = obj_id 18 | task.CreatedOn = time.Now() 19 | task.Status = "Created" 20 | err := r.C.Insert(&task) 21 | return err 22 | } 23 | 24 | func (r *TaskRepository) Update(task *models.Task) error { 25 | // partial update on MogoDB 26 | err := r.C.Update(bson.M{"_id": task.Id}, 27 | bson.M{"$set": bson.M{ 28 | "name": task.Name, 29 | "description": task.Description, 30 | "due": task.Due, 31 | "status": task.Status, 32 | "tags": task.Tags, 33 | }}) 34 | return err 35 | } 36 | func (r *TaskRepository) Delete(id string) error { 37 | err := r.C.Remove(bson.M{"_id": bson.ObjectIdHex(id)}) 38 | return err 39 | } 40 | func (r *TaskRepository) GetAll() []models.Task { 41 | var tasks []models.Task 42 | iter := r.C.Find(nil).Iter() 43 | result := models.Task{} 44 | for iter.Next(&result) { 45 | tasks = append(tasks, result) 46 | } 47 | return tasks 48 | } 49 | func (r *TaskRepository) GetById(id string) (task models.Task, err error) { 50 | err = r.C.FindId(bson.ObjectIdHex(id)).One(&task) 51 | return 52 | } 53 | func (r *TaskRepository) GetByUser(user string) []models.Task { 54 | var tasks []models.Task 55 | iter := r.C.Find(bson.M{"createdby": user}).Iter() 56 | result := models.Task{} 57 | for iter.Next(&result) { 58 | tasks = append(tasks, result) 59 | } 60 | return tasks 61 | } 62 | -------------------------------------------------------------------------------- /go-web-master/chapter-6/middleware/alice.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "io" 5 | "log" 6 | "net/http" 7 | "os" 8 | 9 | "github.com/gorilla/handlers" 10 | "github.com/justinas/alice" 11 | ) 12 | 13 | func loggingHandler(next http.Handler) http.Handler { 14 | logFile, err := os.OpenFile("server.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0777) 15 | if err != nil { 16 | panic(err) 17 | } 18 | return handlers.LoggingHandler(logFile, next) 19 | } 20 | func index(w http.ResponseWriter, r *http.Request) { 21 | 22 | w.Header().Set( 23 | "Content-Type", 24 | "text/html", 25 | ) 26 | io.WriteString( 27 | w, 28 | ` 29 | 30 | 31 | Index 32 | 33 | 34 | Hello Gopher! 35 | 36 | `, 37 | ) 38 | 39 | } 40 | func about(w http.ResponseWriter, r *http.Request) { 41 | w.Header().Set( 42 | "Content-Type", 43 | "text/html", 44 | ) 45 | io.WriteString( 46 | w, 47 | ` 48 | 49 | 50 | About 51 | 52 | 53 | Go Web development with HTTP Middleware 54 | 55 | `, 56 | ) 57 | } 58 | func iconHandler(w http.ResponseWriter, r *http.Request) { 59 | } 60 | func main() { 61 | http.HandleFunc("/favicon.ico", iconHandler) 62 | indexHandler := http.HandlerFunc(index) 63 | aboutHandler := http.HandlerFunc(about) 64 | commonHandlers := alice.New(loggingHandler, handlers.CompressHandler) 65 | http.Handle("/", commonHandlers.ThenFunc(indexHandler)) 66 | http.Handle("/about", commonHandlers.ThenFunc(aboutHandler)) 67 | server := &http.Server{ 68 | Addr: ":8080", 69 | } 70 | log.Println("Listening...") 71 | server.ListenAndServe() 72 | } 73 | -------------------------------------------------------------------------------- /go-web-master/chapter-10/httptest/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | "net/http" 7 | 8 | "github.com/gorilla/mux" 9 | ) 10 | 11 | type User struct { 12 | FirstName string `json:"firstname"` 13 | LastName string `json:"lastname"` 14 | Email string `json:email"` 15 | } 16 | 17 | var userStore = []User{} 18 | 19 | func getUsers(w http.ResponseWriter, r *http.Request) { 20 | users, err := json.Marshal(userStore) 21 | 22 | if err != nil { 23 | w.WriteHeader(http.StatusInternalServerError) 24 | return 25 | } 26 | w.Header().Set("Content-Type", "application/json") 27 | w.WriteHeader(http.StatusOK) 28 | w.Write(users) 29 | 30 | } 31 | func createUser(w http.ResponseWriter, r *http.Request) { 32 | 33 | var user User 34 | // Decode the incoming User json 35 | err := json.NewDecoder(r.Body).Decode(&user) 36 | if err != nil { 37 | w.WriteHeader(http.StatusInternalServerError) 38 | return 39 | } 40 | // Validate the User entity 41 | err = validate(user) 42 | if err != nil { 43 | w.WriteHeader(http.StatusBadRequest) 44 | return 45 | } 46 | // Insert User entity into User Store 47 | userStore = append(userStore, user) 48 | w.WriteHeader(http.StatusCreated) 49 | } 50 | 51 | // Validate User entity 52 | func validate(user User) error { 53 | for _, u := range userStore { 54 | if u.Email == user.Email { 55 | return errors.New("The Email is already exists") 56 | } 57 | } 58 | return nil 59 | } 60 | func SetUserRoutes() *mux.Router { 61 | r := mux.NewRouter() 62 | r.HandleFunc("/users", createUser).Methods("POST") 63 | r.HandleFunc("/users", getUsers).Methods("GET") 64 | return r 65 | } 66 | 67 | func main() { 68 | http.ListenAndServe(":8080", SetUserRoutes()) 69 | } 70 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/gopkg.in/mgo.v2/testdb/setup.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh -e 2 | 3 | start() { 4 | mkdir _testdb 5 | cd _testdb 6 | mkdir db1 db2 db3 rs1a rs1b rs1c rs2a rs2b rs2c rs3a rs3b rs3c rs4a cfg1 cfg2 cfg3 7 | cp ../testdb/supervisord.conf supervisord.conf 8 | cp ../testdb/server.pem server.pem 9 | echo keyfile > keyfile 10 | chmod 600 keyfile 11 | COUNT=$(grep '^\[program' supervisord.conf | wc -l | tr -d ' ') 12 | if ! mongod --help | grep -q -- --ssl; then 13 | COUNT=$(($COUNT - 1)) 14 | fi 15 | echo "Running supervisord..." 16 | supervisord || ( echo "Supervisord failed executing ($?)" && exit 1 ) 17 | echo "Supervisord is up, starting $COUNT processes..." 18 | for i in $(seq 10); do 19 | RUNNING=$(supervisorctl status | grep RUNNING | wc -l | tr -d ' ') 20 | echo "$RUNNING processes running..." 21 | if [ x$COUNT = x$RUNNING ]; then 22 | echo "Running setup.js with mongo..." 23 | mongo --nodb ../testdb/init.js 24 | exit 0 25 | fi 26 | sleep 1 27 | done 28 | echo "Failed to start all processes. Check out what's up at $PWD now!" 29 | exit 1 30 | } 31 | 32 | stop() { 33 | if [ -d _testdb ]; then 34 | echo "Shutting down test cluster..." 35 | (cd _testdb && supervisorctl shutdown) 36 | rm -rf _testdb 37 | fi 38 | } 39 | 40 | 41 | if [ ! -f suite_test.go ]; then 42 | echo "This script must be run from within the source directory." 43 | exit 1 44 | fi 45 | 46 | case "$1" in 47 | 48 | start) 49 | start $2 50 | ;; 51 | 52 | stop) 53 | stop $2 54 | ;; 55 | 56 | esac 57 | 58 | # vim:ts=4:sw=4:et 59 | -------------------------------------------------------------------------------- /go-web-master/chapter-6/middleware/flowcontrol.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net/http" 7 | ) 8 | 9 | func middlewareFirst(next http.Handler) http.Handler { 10 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 11 | log.Println("MiddlewareFirst - Before Handler") 12 | next.ServeHTTP(w, r) 13 | log.Println("MiddlewareFirst - After Handler") 14 | }) 15 | } 16 | 17 | func middlewareSecond(next http.Handler) http.Handler { 18 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 19 | log.Println("MiddlewareSecond - Before Handler") 20 | if r.URL.Path == "/message" { 21 | if r.URL.Query().Get("password") == "pass123" { 22 | log.Println("Authorized to the system") 23 | next.ServeHTTP(w, r) 24 | } else { 25 | log.Println("Failed to authorize to the system") 26 | return 27 | } 28 | } else { 29 | next.ServeHTTP(w, r) 30 | } 31 | 32 | log.Println("MiddlewareSecond - After Handler") 33 | }) 34 | } 35 | 36 | func index(w http.ResponseWriter, r *http.Request) { 37 | log.Println("Executing index Handler") 38 | fmt.Fprintf(w, "Welcome") 39 | } 40 | func message(w http.ResponseWriter, r *http.Request) { 41 | log.Println("Executing message Handler") 42 | fmt.Fprintf(w, "HTTP Middleware is awesome") 43 | } 44 | 45 | func iconHandler(w http.ResponseWriter, r *http.Request) { 46 | } 47 | 48 | func main() { 49 | 50 | http.HandleFunc("/favicon.ico", iconHandler) 51 | http.Handle("/", middlewareFirst(middlewareSecond(http.HandlerFunc(index)))) 52 | http.Handle("/message", middlewareFirst(middlewareSecond(http.HandlerFunc(message)))) 53 | server := &http.Server{ 54 | Addr: ":8080", 55 | } 56 | log.Println("Listening...") 57 | server.ListenAndServe() 58 | } 59 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/gopkg.in/mgo.v2/txn/chaos.go: -------------------------------------------------------------------------------- 1 | package txn 2 | 3 | import ( 4 | mrand "math/rand" 5 | "time" 6 | ) 7 | 8 | var chaosEnabled = false 9 | var chaosSetting Chaos 10 | 11 | // Chaos holds parameters for the failure injection mechanism. 12 | type Chaos struct { 13 | // KillChance is the 0.0 to 1.0 chance that a given checkpoint 14 | // within the algorithm will raise an interruption that will 15 | // stop the procedure. 16 | KillChance float64 17 | 18 | // SlowdownChance is the 0.0 to 1.0 chance that a given checkpoint 19 | // within the algorithm will be delayed by Slowdown before 20 | // continuing. 21 | SlowdownChance float64 22 | Slowdown time.Duration 23 | 24 | // If Breakpoint is set, the above settings will only affect the 25 | // named breakpoint. 26 | Breakpoint string 27 | } 28 | 29 | // SetChaos sets the failure injection parameters to c. 30 | func SetChaos(c Chaos) { 31 | chaosSetting = c 32 | chaosEnabled = c.KillChance > 0 || c.SlowdownChance > 0 33 | } 34 | 35 | func chaos(bpname string) { 36 | if !chaosEnabled { 37 | return 38 | } 39 | switch chaosSetting.Breakpoint { 40 | case "", bpname: 41 | kc := chaosSetting.KillChance 42 | if kc > 0 && mrand.Intn(1000) < int(kc*1000) { 43 | panic(chaosError{}) 44 | } 45 | if bpname == "insert" { 46 | return 47 | } 48 | sc := chaosSetting.SlowdownChance 49 | if sc > 0 && mrand.Intn(1000) < int(sc*1000) { 50 | time.Sleep(chaosSetting.Slowdown) 51 | } 52 | } 53 | } 54 | 55 | type chaosError struct{} 56 | 57 | func (f *flusher) handleChaos(err *error) { 58 | v := recover() 59 | if v == nil { 60 | return 61 | } 62 | if _, ok := v.(chaosError); ok { 63 | f.debugf("Killed by chaos!") 64 | *err = ErrChaos 65 | return 66 | } 67 | panic(v) 68 | } 69 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/test/sample_key: -------------------------------------------------------------------------------- 1 | -----BEGIN RSA PRIVATE KEY----- 2 | MIIEowIBAAKCAQEA4f5wg5l2hKsTeNem/V41fGnJm6gOdrj8ym3rFkEU/wT8RDtn 3 | SgFEZOQpHEgQ7JL38xUfU0Y3g6aYw9QT0hJ7mCpz9Er5qLaMXJwZxzHzAahlfA0i 4 | cqabvJOMvQtzD6uQv6wPEyZtDTWiQi9AXwBpHssPnpYGIn20ZZuNlX2BrClciHhC 5 | PUIIZOQn/MmqTD31jSyjoQoV7MhhMTATKJx2XrHhR+1DcKJzQBSTAGnpYVaqpsAR 6 | ap+nwRipr3nUTuxyGohBTSmjJ2usSeQXHI3bODIRe1AuTyHceAbewn8b462yEWKA 7 | Rdpd9AjQW5SIVPfdsz5B6GlYQ5LdYKtznTuy7wIDAQABAoIBAQCwia1k7+2oZ2d3 8 | n6agCAbqIE1QXfCmh41ZqJHbOY3oRQG3X1wpcGH4Gk+O+zDVTV2JszdcOt7E5dAy 9 | MaomETAhRxB7hlIOnEN7WKm+dGNrKRvV0wDU5ReFMRHg31/Lnu8c+5BvGjZX+ky9 10 | POIhFFYJqwCRlopGSUIxmVj5rSgtzk3iWOQXr+ah1bjEXvlxDOWkHN6YfpV5ThdE 11 | KdBIPGEVqa63r9n2h+qazKrtiRqJqGnOrHzOECYbRFYhexsNFz7YT02xdfSHn7gM 12 | IvabDDP/Qp0PjE1jdouiMaFHYnLBbgvlnZW9yuVf/rpXTUq/njxIXMmvmEyyvSDn 13 | FcFikB8pAoGBAPF77hK4m3/rdGT7X8a/gwvZ2R121aBcdPwEaUhvj/36dx596zvY 14 | mEOjrWfZhF083/nYWE2kVquj2wjs+otCLfifEEgXcVPTnEOPO9Zg3uNSL0nNQghj 15 | FuD3iGLTUBCtM66oTe0jLSslHe8gLGEQqyMzHOzYxNqibxcOZIe8Qt0NAoGBAO+U 16 | I5+XWjWEgDmvyC3TrOSf/KCGjtu0TSv30ipv27bDLMrpvPmD/5lpptTFwcxvVhCs 17 | 2b+chCjlghFSWFbBULBrfci2FtliClOVMYrlNBdUSJhf3aYSG2Doe6Bgt1n2CpNn 18 | /iu37Y3NfemZBJA7hNl4dYe+f+uzM87cdQ214+jrAoGAXA0XxX8ll2+ToOLJsaNT 19 | OvNB9h9Uc5qK5X5w+7G7O998BN2PC/MWp8H+2fVqpXgNENpNXttkRm1hk1dych86 20 | EunfdPuqsX+as44oCyJGFHVBnWpm33eWQw9YqANRI+pCJzP08I5WK3osnPiwshd+ 21 | hR54yjgfYhBFNI7B95PmEQkCgYBzFSz7h1+s34Ycr8SvxsOBWxymG5zaCsUbPsL0 22 | 4aCgLScCHb9J+E86aVbbVFdglYa5Id7DPTL61ixhl7WZjujspeXZGSbmq0Kcnckb 23 | mDgqkLECiOJW2NHP/j0McAkDLL4tysF8TLDO8gvuvzNC+WQ6drO2ThrypLVZQ+ry 24 | eBIPmwKBgEZxhqa0gVvHQG/7Od69KWj4eJP28kq13RhKay8JOoN0vPmspXJo1HY3 25 | CKuHRG+AP579dncdUnOMvfXOtkdM4vk0+hWASBQzM9xzVcztCa+koAugjVaLS9A+ 26 | 9uQoqEeVNTckxx0S2bYevRy7hGQmUJTyQm3j1zEUR5jpdbL83Fbq 27 | -----END RSA PRIVATE KEY----- 28 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/rsa_utils.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "crypto/rsa" 5 | "crypto/x509" 6 | "encoding/pem" 7 | "errors" 8 | ) 9 | 10 | var ( 11 | ErrKeyMustBePEMEncoded = errors.New("Invalid Key: Key must be PEM encoded PKCS1 or PKCS8 private key") 12 | ErrNotRSAPrivateKey = errors.New("Key is not a valid RSA private key") 13 | ) 14 | 15 | // Parse PEM encoded PKCS1 or PKCS8 private key 16 | func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error) { 17 | var err error 18 | 19 | // Parse PEM block 20 | var block *pem.Block 21 | if block, _ = pem.Decode(key); block == nil { 22 | return nil, ErrKeyMustBePEMEncoded 23 | } 24 | 25 | var parsedKey interface{} 26 | if parsedKey, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil { 27 | if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil { 28 | return nil, err 29 | } 30 | } 31 | 32 | var pkey *rsa.PrivateKey 33 | var ok bool 34 | if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok { 35 | return nil, ErrNotRSAPrivateKey 36 | } 37 | 38 | return pkey, nil 39 | } 40 | 41 | // Parse PEM encoded PKCS1 or PKCS8 public key 42 | func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) { 43 | var err error 44 | 45 | // Parse PEM block 46 | var block *pem.Block 47 | if block, _ = pem.Decode(key); block == nil { 48 | return nil, ErrKeyMustBePEMEncoded 49 | } 50 | 51 | // Parse the key 52 | var parsedKey interface{} 53 | if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { 54 | if cert, err := x509.ParseCertificate(block.Bytes); err == nil { 55 | parsedKey = cert.PublicKey 56 | } else { 57 | return nil, err 58 | } 59 | } 60 | 61 | var pkey *rsa.PublicKey 62 | var ok bool 63 | if pkey, ok = parsedKey.(*rsa.PublicKey); !ok { 64 | return nil, ErrNotRSAPrivateKey 65 | } 66 | 67 | return pkey, nil 68 | } 69 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/gopkg.in/mgo.v2/internal/sasl/sasl.c: -------------------------------------------------------------------------------- 1 | // +build !windows 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | static int mgo_sasl_simple(void *context, int id, const char **result, unsigned int *len) 9 | { 10 | if (!result) { 11 | return SASL_BADPARAM; 12 | } 13 | switch (id) { 14 | case SASL_CB_USER: 15 | *result = (char *)context; 16 | break; 17 | case SASL_CB_AUTHNAME: 18 | *result = (char *)context; 19 | break; 20 | case SASL_CB_LANGUAGE: 21 | *result = NULL; 22 | break; 23 | default: 24 | return SASL_BADPARAM; 25 | } 26 | if (len) { 27 | *len = *result ? strlen(*result) : 0; 28 | } 29 | return SASL_OK; 30 | } 31 | 32 | typedef int (*callback)(void); 33 | 34 | static int mgo_sasl_secret(sasl_conn_t *conn, void *context, int id, sasl_secret_t **result) 35 | { 36 | if (!conn || !result || id != SASL_CB_PASS) { 37 | return SASL_BADPARAM; 38 | } 39 | *result = (sasl_secret_t *)context; 40 | return SASL_OK; 41 | } 42 | 43 | sasl_callback_t *mgo_sasl_callbacks(const char *username, const char *password) 44 | { 45 | sasl_callback_t *cb = malloc(4 * sizeof(sasl_callback_t)); 46 | int n = 0; 47 | 48 | size_t len = strlen(password); 49 | sasl_secret_t *secret = (sasl_secret_t*)malloc(sizeof(sasl_secret_t) + len); 50 | if (!secret) { 51 | free(cb); 52 | return NULL; 53 | } 54 | strcpy((char *)secret->data, password); 55 | secret->len = len; 56 | 57 | cb[n].id = SASL_CB_PASS; 58 | cb[n].proc = (callback)&mgo_sasl_secret; 59 | cb[n].context = secret; 60 | n++; 61 | 62 | cb[n].id = SASL_CB_USER; 63 | cb[n].proc = (callback)&mgo_sasl_simple; 64 | cb[n].context = (char*)username; 65 | n++; 66 | 67 | cb[n].id = SASL_CB_AUTHNAME; 68 | cb[n].proc = (callback)&mgo_sasl_simple; 69 | cb[n].context = (char*)username; 70 | n++; 71 | 72 | cb[n].id = SASL_CB_LIST_END; 73 | cb[n].proc = NULL; 74 | cb[n].context = NULL; 75 | 76 | return cb; 77 | } 78 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/common/mongoUtils.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | import ( 4 | "log" 5 | "time" 6 | 7 | "gopkg.in/mgo.v2" 8 | ) 9 | 10 | var session *mgo.Session 11 | 12 | func GetSession() *mgo.Session { 13 | if session == nil { 14 | var err error 15 | session, err = mgo.DialWithInfo(&mgo.DialInfo{ 16 | Addrs: []string{AppConfig.MongoDBHost}, 17 | Username: AppConfig.DBUser, 18 | Password: AppConfig.DBPwd, 19 | Timeout: 60 * time.Second, 20 | }) 21 | if err != nil { 22 | log.Fatalf("[GetSession]: %s\n", err) 23 | } 24 | } 25 | return session 26 | } 27 | func createDbSession() { 28 | var err error 29 | session, err = mgo.DialWithInfo(&mgo.DialInfo{ 30 | Addrs: []string{AppConfig.MongoDBHost}, 31 | Username: AppConfig.DBUser, 32 | Password: AppConfig.DBPwd, 33 | Timeout: 60 * time.Second, 34 | }) 35 | if err != nil { 36 | log.Fatalf("[createDbSession]: %s\n", err) 37 | } 38 | } 39 | 40 | // Add indexes into MongoDB 41 | func addIndexes() { 42 | var err error 43 | userIndex := mgo.Index{ 44 | Key: []string{"email"}, 45 | Unique: true, 46 | Background: true, 47 | Sparse: true, 48 | } 49 | taskIndex := mgo.Index{ 50 | Key: []string{"createdby"}, 51 | Unique: false, 52 | Background: true, 53 | Sparse: true, 54 | } 55 | noteIndex := mgo.Index{ 56 | Key: []string{"taskid"}, 57 | Unique: false, 58 | Background: true, 59 | Sparse: true, 60 | } 61 | // Add indexes into MongoDB 62 | session := GetSession().Copy() 63 | defer session.Close() 64 | userCol := session.DB(AppConfig.Database).C("users") 65 | taskCol := session.DB(AppConfig.Database).C("tasks") 66 | noteCol := session.DB(AppConfig.Database).C("notes") 67 | 68 | err = userCol.EnsureIndex(userIndex) 69 | if err != nil { 70 | log.Fatalf("[addIndexes]: %s\n", err) 71 | } 72 | err = taskCol.EnsureIndex(taskIndex) 73 | if err != nil { 74 | log.Fatalf("[addIndexes]: %s\n", err) 75 | } 76 | err = noteCol.EnsureIndex(noteIndex) 77 | if err != nil { 78 | log.Fatalf("[addIndexes]: %s\n", err) 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/github.com/codegangsta/negroni/static.go: -------------------------------------------------------------------------------- 1 | package negroni 2 | 3 | import ( 4 | "net/http" 5 | "path" 6 | "strings" 7 | ) 8 | 9 | // Static is a middleware handler that serves static files in the given directory/filesystem. 10 | type Static struct { 11 | // Dir is the directory to serve static files from 12 | Dir http.FileSystem 13 | // Prefix is the optional prefix used to serve the static directory content 14 | Prefix string 15 | // IndexFile defines which file to serve as index if it exists. 16 | IndexFile string 17 | } 18 | 19 | // NewStatic returns a new instance of Static 20 | func NewStatic(directory http.FileSystem) *Static { 21 | return &Static{ 22 | Dir: directory, 23 | Prefix: "", 24 | IndexFile: "index.html", 25 | } 26 | } 27 | 28 | func (s *Static) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) { 29 | if r.Method != "GET" && r.Method != "HEAD" { 30 | next(rw, r) 31 | return 32 | } 33 | file := r.URL.Path 34 | // if we have a prefix, filter requests by stripping the prefix 35 | if s.Prefix != "" { 36 | if !strings.HasPrefix(file, s.Prefix) { 37 | next(rw, r) 38 | return 39 | } 40 | file = file[len(s.Prefix):] 41 | if file != "" && file[0] != '/' { 42 | next(rw, r) 43 | return 44 | } 45 | } 46 | f, err := s.Dir.Open(file) 47 | if err != nil { 48 | // discard the error? 49 | next(rw, r) 50 | return 51 | } 52 | defer f.Close() 53 | 54 | fi, err := f.Stat() 55 | if err != nil { 56 | next(rw, r) 57 | return 58 | } 59 | 60 | // try to serve index file 61 | if fi.IsDir() { 62 | // redirect if missing trailing slash 63 | if !strings.HasSuffix(r.URL.Path, "/") { 64 | http.Redirect(rw, r, r.URL.Path+"/", http.StatusFound) 65 | return 66 | } 67 | 68 | file = path.Join(file, s.IndexFile) 69 | f, err = s.Dir.Open(file) 70 | if err != nil { 71 | next(rw, r) 72 | return 73 | } 74 | defer f.Close() 75 | 76 | fi, err = f.Stat() 77 | if err != nil || fi.IsDir() { 78 | next(rw, r) 79 | return 80 | } 81 | } 82 | 83 | http.ServeContent(rw, r, file, fi.ModTime(), f) 84 | } 85 | -------------------------------------------------------------------------------- /go-web-master/chapter-11/datastore/task.go: -------------------------------------------------------------------------------- 1 | package task 2 | 3 | import ( 4 | "fmt" 5 | "html/template" 6 | "net/http" 7 | "time" 8 | 9 | "google.golang.org/appengine" 10 | "google.golang.org/appengine/datastore" 11 | ) 12 | 13 | type Task struct { 14 | Name string 15 | Description string 16 | CreatedOn time.Time 17 | } 18 | 19 | const taskForm = ` 20 | 21 | 22 |
23 |

Task Name:

24 |

Description:

25 |

26 |
27 | 28 | 29 | ` 30 | const taskListTmplHTML = ` 31 | 32 | 33 |

Task List

34 | {{range .}} 35 |

{{.Name}} - {{.Description}}

36 | {{end}} 37 |

Create task

38 | 39 | 40 | ` 41 | 42 | var taskListTemplate = template.Must(template.New("taskList").Parse(taskListTmplHTML)) 43 | 44 | func init() { 45 | http.HandleFunc("/", index) 46 | http.HandleFunc("/create", create) 47 | http.HandleFunc("/save", save) 48 | } 49 | 50 | func index(w http.ResponseWriter, r *http.Request) { 51 | q := datastore.NewQuery("tasks"). 52 | Order("-CreatedOn") 53 | c := appengine.NewContext(r) 54 | var tasks []Task 55 | _, err := q.GetAll(c, &tasks) 56 | if err != nil { 57 | http.Error(w, err.Error(), http.StatusInternalServerError) 58 | } 59 | if err := taskListTemplate.Execute(w, tasks); err != nil { 60 | http.Error(w, err.Error(), http.StatusInternalServerError) 61 | } 62 | } 63 | func create(w http.ResponseWriter, r *http.Request) { 64 | fmt.Fprint(w, taskForm) 65 | } 66 | 67 | func save(w http.ResponseWriter, r *http.Request) { 68 | task := Task{ 69 | Name: r.FormValue("taskname"), 70 | Description: r.FormValue("description"), 71 | CreatedOn: time.Now(), 72 | } 73 | c := appengine.NewContext(r) 74 | _, err := datastore.Put(c, datastore.NewIncompleteKey(c, "tasks", nil), &task) 75 | if err != nil { 76 | http.Error(w, err.Error(), http.StatusInternalServerError) 77 | return 78 | } 79 | http.Redirect(w, r, "/", http.StatusMovedPermanently) 80 | } 81 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/gopkg.in/mgo.v2/testdb/dropall.js: -------------------------------------------------------------------------------- 1 | 2 | var ports = [40001, 40002, 40011, 40012, 40013, 40021, 40022, 40023, 40041, 40101, 40102, 40103, 40201, 40202, 40203] 3 | var auth = [40002, 40103, 40203, 40031] 4 | var db1 = new Mongo("localhost:40001") 5 | 6 | if (db1.getDB("admin").serverBuildInfo().OpenSSLVersion) { 7 | ports.push(40003) 8 | auth.push(40003) 9 | } 10 | 11 | for (var i in ports) { 12 | var port = ports[i] 13 | var server = "localhost:" + port 14 | var mongo = new Mongo("localhost:" + port) 15 | var admin = mongo.getDB("admin") 16 | 17 | for (var j in auth) { 18 | if (auth[j] == port) { 19 | admin.auth("root", "rapadura") 20 | admin.system.users.find().forEach(function(u) { 21 | if (u.user == "root" || u.user == "reader") { 22 | return; 23 | } 24 | if (typeof admin.dropUser == "function") { 25 | mongo.getDB(u.db).dropUser(u.user); 26 | } else { 27 | admin.removeUser(u.user); 28 | } 29 | }) 30 | break 31 | } 32 | } 33 | var result = admin.runCommand({"listDatabases": 1}) 34 | for (var j = 0; j != 100; j++) { 35 | if (typeof result.databases != "undefined" || notMaster(result)) { 36 | break 37 | } 38 | result = admin.runCommand({"listDatabases": 1}) 39 | } 40 | if (notMaster(result)) { 41 | continue 42 | } 43 | if (typeof result.databases == "undefined") { 44 | print("Could not list databases. Command result:") 45 | print(JSON.stringify(result)) 46 | quit(12) 47 | } 48 | var dbs = result.databases 49 | for (var j = 0; j != dbs.length; j++) { 50 | var db = dbs[j] 51 | switch (db.name) { 52 | case "admin": 53 | case "local": 54 | case "config": 55 | break 56 | default: 57 | mongo.getDB(db.name).dropDatabase() 58 | } 59 | } 60 | } 61 | 62 | function notMaster(result) { 63 | return typeof result.errmsg != "undefined" && (result.errmsg.indexOf("not master") >= 0 || result.errmsg.indexOf("no master found")) 64 | } 65 | 66 | // vim:ts=4:sw=4:et 67 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/hmac.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "crypto" 5 | "crypto/hmac" 6 | "errors" 7 | ) 8 | 9 | // Implements the HMAC-SHA family of signing methods signing methods 10 | type SigningMethodHMAC struct { 11 | Name string 12 | Hash crypto.Hash 13 | } 14 | 15 | // Specific instances for HS256 and company 16 | var ( 17 | SigningMethodHS256 *SigningMethodHMAC 18 | SigningMethodHS384 *SigningMethodHMAC 19 | SigningMethodHS512 *SigningMethodHMAC 20 | ErrSignatureInvalid = errors.New("signature is invalid") 21 | ) 22 | 23 | func init() { 24 | // HS256 25 | SigningMethodHS256 = &SigningMethodHMAC{"HS256", crypto.SHA256} 26 | RegisterSigningMethod(SigningMethodHS256.Alg(), func() SigningMethod { 27 | return SigningMethodHS256 28 | }) 29 | 30 | // HS384 31 | SigningMethodHS384 = &SigningMethodHMAC{"HS384", crypto.SHA384} 32 | RegisterSigningMethod(SigningMethodHS384.Alg(), func() SigningMethod { 33 | return SigningMethodHS384 34 | }) 35 | 36 | // HS512 37 | SigningMethodHS512 = &SigningMethodHMAC{"HS512", crypto.SHA512} 38 | RegisterSigningMethod(SigningMethodHS512.Alg(), func() SigningMethod { 39 | return SigningMethodHS512 40 | }) 41 | } 42 | 43 | func (m *SigningMethodHMAC) Alg() string { 44 | return m.Name 45 | } 46 | 47 | func (m *SigningMethodHMAC) Verify(signingString, signature string, key interface{}) error { 48 | if keyBytes, ok := key.([]byte); ok { 49 | var sig []byte 50 | var err error 51 | if sig, err = DecodeSegment(signature); err == nil { 52 | if !m.Hash.Available() { 53 | return ErrHashUnavailable 54 | } 55 | 56 | hasher := hmac.New(m.Hash.New, keyBytes) 57 | hasher.Write([]byte(signingString)) 58 | 59 | if !hmac.Equal(sig, hasher.Sum(nil)) { 60 | err = ErrSignatureInvalid 61 | } 62 | } 63 | return err 64 | } 65 | 66 | return ErrInvalidKey 67 | } 68 | 69 | // Implements the Sign method from SigningMethod for this signing method. 70 | // Key must be []byte 71 | func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) (string, error) { 72 | if keyBytes, ok := key.([]byte); ok { 73 | if !m.Hash.Available() { 74 | return "", ErrHashUnavailable 75 | } 76 | 77 | hasher := hmac.New(m.Hash.New, keyBytes) 78 | hasher.Write([]byte(signingString)) 79 | 80 | return EncodeSegment(hasher.Sum(nil)), nil 81 | } 82 | 83 | return "", ErrInvalidKey 84 | } 85 | -------------------------------------------------------------------------------- /go-web-master/chapter-7/oauth/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "html/template" 7 | "log" 8 | "net/http" 9 | "os" 10 | 11 | "github.com/gorilla/pat" 12 | "github.com/markbates/goth" 13 | "github.com/markbates/goth/gothic" 14 | "github.com/markbates/goth/providers/facebook" 15 | "github.com/markbates/goth/providers/twitter" 16 | ) 17 | 18 | //Struct for parsing JSON configuration 19 | type Configuration struct { 20 | TwitterKey string 21 | TwitterSecret string 22 | FacebookKey string 23 | FacebookSecret string 24 | } 25 | 26 | var config Configuration 27 | 28 | //Read configuration values from config.json 29 | func init() { 30 | file, _ := os.Open("config.json") 31 | decoder := json.NewDecoder(file) 32 | config = Configuration{} 33 | err := decoder.Decode(&config) 34 | if err != nil { 35 | log.Fatal(err) 36 | } 37 | } 38 | func callbackAuthHandler(res http.ResponseWriter, req *http.Request) { 39 | user, err := gothic.CompleteUserAuth(res, req) 40 | if err != nil { 41 | fmt.Fprintln(res, err) 42 | return 43 | } 44 | t, _ := template.New("userinfo").Parse(userTemplate) 45 | t.Execute(res, user) 46 | } 47 | func indexHandler(res http.ResponseWriter, req *http.Request) { 48 | t, _ := template.New("index").Parse(indexTemplate) 49 | t.Execute(res, nil) 50 | } 51 | func main() { 52 | //Register OAuth2 providers with Goth 53 | goth.UseProviders( 54 | twitter.New(config.TwitterKey, config.TwitterSecret, "http://localhost:8080/auth/twitter/callback"), 55 | facebook.New(config.FacebookKey, config.FacebookSecret, "http://localhost:8080/auth/facebook/callback"), 56 | ) 57 | //Routing using Pat package 58 | r := pat.New() 59 | r.Get("/auth/{provider}/callback", callbackAuthHandler) 60 | r.Get("/auth/{provider}", gothic.BeginAuthHandler) 61 | r.Get("/", indexHandler) 62 | 63 | server := &http.Server{ 64 | Addr: ":8080", 65 | Handler: r, 66 | } 67 | log.Println("Listening...") 68 | server.ListenAndServe() 69 | 70 | } 71 | 72 | //View templates 73 | var indexTemplate = ` 74 |

Log in with Twitter

75 |

Log in with Facebook

76 | ` 77 | 78 | var userTemplate = ` 79 |

Name: {{.Name}}

80 |

Email: {{.Email}}

81 |

NickName: {{.NickName}}

82 |

Location: {{.Location}}

83 |

AvatarURL: {{.AvatarURL}}

84 |

Description: {{.Description}}

85 |

UserID: {{.UserID}}

86 |

AccessToken: {{.AccessToken}}

87 | ` 88 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/gopkg.in/mgo.v2/testdb/wait.js: -------------------------------------------------------------------------------- 1 | // We know the master of the first set (pri=1), but not of the second. 2 | var settings = {} 3 | var rs1cfg = {_id: "rs1", 4 | members: [{_id: 1, host: "127.0.0.1:40011", priority: 1}, 5 | {_id: 2, host: "127.0.0.1:40012", priority: 0}, 6 | {_id: 3, host: "127.0.0.1:40013", priority: 0}]} 7 | var rs2cfg = {_id: "rs2", 8 | members: [{_id: 1, host: "127.0.0.1:40021", priority: 1}, 9 | {_id: 2, host: "127.0.0.1:40022", priority: 1}, 10 | {_id: 3, host: "127.0.0.1:40023", priority: 0}]} 11 | var rs3cfg = {_id: "rs3", 12 | members: [{_id: 1, host: "127.0.0.1:40031", priority: 1}, 13 | {_id: 2, host: "127.0.0.1:40032", priority: 1}, 14 | {_id: 3, host: "127.0.0.1:40033", priority: 1}], 15 | settings: settings} 16 | 17 | for (var i = 0; i != 60; i++) { 18 | try { 19 | rs1a = new Mongo("127.0.0.1:40011").getDB("admin") 20 | rs2a = new Mongo("127.0.0.1:40021").getDB("admin") 21 | rs3a = new Mongo("127.0.0.1:40031").getDB("admin") 22 | rs3a.auth("root", "rapadura") 23 | db1 = new Mongo("127.0.0.1:40001").getDB("admin") 24 | db2 = new Mongo("127.0.0.1:40002").getDB("admin") 25 | break 26 | } catch(err) { 27 | print("Can't connect yet...") 28 | } 29 | sleep(1000) 30 | } 31 | 32 | function countHealthy(rs) { 33 | var status = rs.runCommand({replSetGetStatus: 1}) 34 | var count = 0 35 | var primary = 0 36 | if (typeof status.members != "undefined") { 37 | for (var i = 0; i != status.members.length; i++) { 38 | var m = status.members[i] 39 | if (m.health == 1 && (m.state == 1 || m.state == 2)) { 40 | count += 1 41 | if (m.state == 1) { 42 | primary = 1 43 | } 44 | } 45 | } 46 | } 47 | if (primary == 0) { 48 | count = 0 49 | } 50 | return count 51 | } 52 | 53 | var totalRSMembers = rs1cfg.members.length + rs2cfg.members.length + rs3cfg.members.length 54 | 55 | for (var i = 0; i != 60; i++) { 56 | var count = countHealthy(rs1a) + countHealthy(rs2a) + countHealthy(rs3a) 57 | print("Replica sets have", count, "healthy nodes.") 58 | if (count == totalRSMembers) { 59 | quit(0) 60 | } 61 | sleep(1000) 62 | } 63 | 64 | print("Replica sets didn't sync up properly.") 65 | quit(12) 66 | 67 | // vim:ts=4:sw=4:et 68 | -------------------------------------------------------------------------------- /go-web-master/chapter-8/manage-session.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "log" 6 | "net/http" 7 | 8 | "github.com/gorilla/mux" 9 | "gopkg.in/mgo.v2" 10 | "gopkg.in/mgo.v2/bson" 11 | ) 12 | 13 | var session *mgo.Session 14 | 15 | type ( 16 | Category struct { 17 | Id bson.ObjectId `bson:"_id,omitempty"` 18 | Name string 19 | Description string 20 | } 21 | DataStore struct { 22 | session *mgo.Session 23 | } 24 | ) 25 | 26 | //Close mgo.Session 27 | func (d *DataStore) Close() { 28 | d.session.Close() 29 | } 30 | 31 | //Returns a collection from the database. 32 | func (d *DataStore) C(name string) *mgo.Collection { 33 | return d.session.DB("taskdb").C(name) 34 | } 35 | 36 | //Create a new DataStore object for each HTTP request 37 | func NewDataStore() *DataStore { 38 | ds := &DataStore{ 39 | session: session.Copy(), 40 | } 41 | return ds 42 | } 43 | 44 | //Insert a record 45 | func PostCategory(w http.ResponseWriter, r *http.Request) { 46 | var category Category 47 | // Decode the incoming Category json 48 | err := json.NewDecoder(r.Body).Decode(&category) 49 | if err != nil { 50 | panic(err) 51 | } 52 | ds := NewDataStore() 53 | defer ds.Close() 54 | //Getting the mgo.Collection 55 | c := ds.C("categories") 56 | //Insert record 57 | err = c.Insert(&category) 58 | if err != nil { 59 | panic(err) 60 | } 61 | w.WriteHeader(http.StatusCreated) 62 | } 63 | 64 | //Read all records 65 | func GetCategories(w http.ResponseWriter, r *http.Request) { 66 | 67 | var categories []Category 68 | ds := NewDataStore() 69 | defer ds.Close() 70 | //Getting the mgo.Collection 71 | c := ds.C("categories") 72 | iter := c.Find(nil).Iter() 73 | result := Category{} 74 | for iter.Next(&result) { 75 | categories = append(categories, result) 76 | } 77 | w.Header().Set("Content-Type", "application/json") 78 | j, err := json.Marshal(categories) 79 | if err != nil { 80 | panic(err) 81 | } 82 | w.WriteHeader(http.StatusOK) 83 | w.Write(j) 84 | } 85 | 86 | func main() { 87 | var err error 88 | session, err = mgo.Dial("localhost") 89 | if err != nil { 90 | panic(err) 91 | } 92 | r := mux.NewRouter() 93 | r.HandleFunc("/api/categories", GetCategories).Methods("GET") 94 | r.HandleFunc("/api/categories", PostCategory).Methods("POST") 95 | 96 | server := &http.Server{ 97 | Addr: ":8080", 98 | Handler: r, 99 | } 100 | log.Println("Listening...") 101 | server.ListenAndServe() 102 | 103 | } 104 | -------------------------------------------------------------------------------- /go-web-master/chapter-10/stringutils_test/utils_test.go: -------------------------------------------------------------------------------- 1 | package stringutils_test 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | "time" 7 | 8 | . "github.com/shijuvar/go-web/chapter-10/stringutils" 9 | ) 10 | 11 | // Test case for the SwapCase function to execute in parallel 12 | func TestSwapCaseInParallel(t *testing.T) { 13 | t.Parallel() 14 | // Delaying 1 second for the sake of demonstration 15 | time.Sleep(1 * time.Second) 16 | input, expected := "Hello, World", "hELLO, wORLD" 17 | result := SwapCase(input) 18 | 19 | if result != expected { 20 | 21 | t.Errorf("SwapCase(%q) == %q, expected %q", input, result, expected) 22 | } 23 | 24 | } 25 | 26 | // Test case for the Reverse function to execute in parallel 27 | func TestReverseInParallel(t *testing.T) { 28 | t.Parallel() 29 | // Delaying 2 seconds for the sake of demonstration 30 | time.Sleep(2 * time.Second) 31 | input, expected := "Hello, World", "dlroW ,olleH" 32 | result := Reverse(input) 33 | 34 | if result != expected { 35 | 36 | t.Errorf("Reverse(%q) == %q, expected %q", input, result, expected) 37 | } 38 | 39 | } 40 | 41 | // Test case for the SwapCase function 42 | func TestSwapCase(t *testing.T) { 43 | input, expected := "Hello, World", "hELLO, wORLD" 44 | result := SwapCase(input) 45 | 46 | if result != expected { 47 | 48 | t.Errorf("SwapCase(%q) == %q, expected %q", input, result, expected) 49 | } 50 | 51 | } 52 | 53 | // Test case for the Reverse function 54 | func TestReverse(t *testing.T) { 55 | input, expected := "Hello, World", "dlroW ,olleH" 56 | result := Reverse(input) 57 | 58 | if result != expected { 59 | 60 | t.Errorf("Reverse(%q) == %q, expected %q", input, result, expected) 61 | } 62 | 63 | } 64 | 65 | //Benchmark for SwapCase function 66 | func BenchmarkSwapCase(b *testing.B) { 67 | for i := 0; i < b.N; i++ { 68 | SwapCase("Hello, World") 69 | } 70 | } 71 | 72 | //Benchmark for Reverse function 73 | func BenchmarkReverse(b *testing.B) { 74 | for i := 0; i < b.N; i++ { 75 | Reverse("Hello, World") 76 | } 77 | } 78 | 79 | //Example code for Reverse function 80 | func ExampleReverse() { 81 | fmt.Println(Reverse("Hello, World")) 82 | // Output: dlroW ,olleH 83 | } 84 | 85 | //Example code for Reverse function 86 | func ExampleSwapCase() { 87 | fmt.Println(SwapCase("Hello, World")) 88 | // Output: hELLO, wORLD 89 | } 90 | func TestLongRun(t *testing.T) { 91 | // Checks whether the short flag is provided 92 | if testing.Short() { 93 | t.Skip("Skipping test in short mode") 94 | } 95 | // Long running implementation goes here 96 | time.Sleep(5 * time.Second) 97 | } 98 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/gopkg.in/mgo.v2/txn/tarjan.go: -------------------------------------------------------------------------------- 1 | package txn 2 | 3 | import ( 4 | "github.com/shijuvar/go-web/taskmanager/Godeps/_workspace/src/gopkg.in/mgo.v2/bson" 5 | "sort" 6 | ) 7 | 8 | func tarjanSort(successors map[bson.ObjectId][]bson.ObjectId) [][]bson.ObjectId { 9 | // http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm 10 | data := &tarjanData{ 11 | successors: successors, 12 | nodes: make([]tarjanNode, 0, len(successors)), 13 | index: make(map[bson.ObjectId]int, len(successors)), 14 | } 15 | 16 | for id := range successors { 17 | id := bson.ObjectId(string(id)) 18 | if _, seen := data.index[id]; !seen { 19 | data.strongConnect(id) 20 | } 21 | } 22 | 23 | // Sort connected components to stabilize the algorithm. 24 | for _, ids := range data.output { 25 | if len(ids) > 1 { 26 | sort.Sort(idList(ids)) 27 | } 28 | } 29 | return data.output 30 | } 31 | 32 | type tarjanData struct { 33 | successors map[bson.ObjectId][]bson.ObjectId 34 | output [][]bson.ObjectId 35 | 36 | nodes []tarjanNode 37 | stack []bson.ObjectId 38 | index map[bson.ObjectId]int 39 | } 40 | 41 | type tarjanNode struct { 42 | lowlink int 43 | stacked bool 44 | } 45 | 46 | type idList []bson.ObjectId 47 | 48 | func (l idList) Len() int { return len(l) } 49 | func (l idList) Swap(i, j int) { l[i], l[j] = l[j], l[i] } 50 | func (l idList) Less(i, j int) bool { return l[i] < l[j] } 51 | 52 | func (data *tarjanData) strongConnect(id bson.ObjectId) *tarjanNode { 53 | index := len(data.nodes) 54 | data.index[id] = index 55 | data.stack = append(data.stack, id) 56 | data.nodes = append(data.nodes, tarjanNode{index, true}) 57 | node := &data.nodes[index] 58 | 59 | for _, succid := range data.successors[id] { 60 | succindex, seen := data.index[succid] 61 | if !seen { 62 | succnode := data.strongConnect(succid) 63 | if succnode.lowlink < node.lowlink { 64 | node.lowlink = succnode.lowlink 65 | } 66 | } else if data.nodes[succindex].stacked { 67 | // Part of the current strongly-connected component. 68 | if succindex < node.lowlink { 69 | node.lowlink = succindex 70 | } 71 | } 72 | } 73 | 74 | if node.lowlink == index { 75 | // Root node; pop stack and output new 76 | // strongly-connected component. 77 | var scc []bson.ObjectId 78 | i := len(data.stack) - 1 79 | for { 80 | stackid := data.stack[i] 81 | stackindex := data.index[stackid] 82 | data.nodes[stackindex].stacked = false 83 | scc = append(scc, stackid) 84 | if stackindex == index { 85 | break 86 | } 87 | i-- 88 | } 89 | data.stack = data.stack[:i] 90 | data.output = append(data.output, scc) 91 | } 92 | 93 | return node 94 | } 95 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/gopkg.in/mgo.v2/txn/debug.go: -------------------------------------------------------------------------------- 1 | package txn 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "sort" 7 | "sync/atomic" 8 | 9 | "github.com/shijuvar/go-web/taskmanager/Godeps/_workspace/src/gopkg.in/mgo.v2/bson" 10 | ) 11 | 12 | var ( 13 | debugEnabled bool 14 | logger log_Logger 15 | ) 16 | 17 | type log_Logger interface { 18 | Output(calldepth int, s string) error 19 | } 20 | 21 | // Specify the *log.Logger where logged messages should be sent to. 22 | func SetLogger(l log_Logger) { 23 | logger = l 24 | } 25 | 26 | // SetDebug enables or disables debugging. 27 | func SetDebug(debug bool) { 28 | debugEnabled = debug 29 | } 30 | 31 | var ErrChaos = fmt.Errorf("interrupted by chaos") 32 | 33 | var debugId uint32 34 | 35 | func debugPrefix() string { 36 | d := atomic.AddUint32(&debugId, 1) - 1 37 | s := make([]byte, 0, 10) 38 | for i := uint(0); i < 8; i++ { 39 | s = append(s, "abcdefghijklmnop"[(d>>(4*i))&0xf]) 40 | if d>>(4*(i+1)) == 0 { 41 | break 42 | } 43 | } 44 | s = append(s, ')', ' ') 45 | return string(s) 46 | } 47 | 48 | func logf(format string, args ...interface{}) { 49 | if logger != nil { 50 | logger.Output(2, fmt.Sprintf(format, argsForLog(args)...)) 51 | } 52 | } 53 | 54 | func debugf(format string, args ...interface{}) { 55 | if debugEnabled && logger != nil { 56 | logger.Output(2, fmt.Sprintf(format, argsForLog(args)...)) 57 | } 58 | } 59 | 60 | func argsForLog(args []interface{}) []interface{} { 61 | for i, arg := range args { 62 | switch v := arg.(type) { 63 | case bson.ObjectId: 64 | args[i] = v.Hex() 65 | case []bson.ObjectId: 66 | lst := make([]string, len(v)) 67 | for j, id := range v { 68 | lst[j] = id.Hex() 69 | } 70 | args[i] = lst 71 | case map[docKey][]bson.ObjectId: 72 | buf := &bytes.Buffer{} 73 | var dkeys docKeys 74 | for dkey := range v { 75 | dkeys = append(dkeys, dkey) 76 | } 77 | sort.Sort(dkeys) 78 | for i, dkey := range dkeys { 79 | if i > 0 { 80 | buf.WriteByte(' ') 81 | } 82 | buf.WriteString(fmt.Sprintf("%v: {", dkey)) 83 | for j, id := range v[dkey] { 84 | if j > 0 { 85 | buf.WriteByte(' ') 86 | } 87 | buf.WriteString(id.Hex()) 88 | } 89 | buf.WriteByte('}') 90 | } 91 | args[i] = buf.String() 92 | case map[docKey][]int64: 93 | buf := &bytes.Buffer{} 94 | var dkeys docKeys 95 | for dkey := range v { 96 | dkeys = append(dkeys, dkey) 97 | } 98 | sort.Sort(dkeys) 99 | for i, dkey := range dkeys { 100 | if i > 0 { 101 | buf.WriteByte(' ') 102 | } 103 | buf.WriteString(fmt.Sprintf("%v: %v", dkey, v[dkey])) 104 | } 105 | args[i] = buf.String() 106 | } 107 | } 108 | return args 109 | } 110 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/github.com/gorilla/context/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Gorilla Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | /* 6 | Package context stores values shared during a request lifetime. 7 | 8 | For example, a router can set variables extracted from the URL and later 9 | application handlers can access those values, or it can be used to store 10 | sessions values to be saved at the end of a request. There are several 11 | others common uses. 12 | 13 | The idea was posted by Brad Fitzpatrick to the go-nuts mailing list: 14 | 15 | http://groups.google.com/group/golang-nuts/msg/e2d679d303aa5d53 16 | 17 | Here's the basic usage: first define the keys that you will need. The key 18 | type is interface{} so a key can be of any type that supports equality. 19 | Here we define a key using a custom int type to avoid name collisions: 20 | 21 | package foo 22 | 23 | import ( 24 | "github.com/gorilla/context" 25 | ) 26 | 27 | type key int 28 | 29 | const MyKey key = 0 30 | 31 | Then set a variable. Variables are bound to an http.Request object, so you 32 | need a request instance to set a value: 33 | 34 | context.Set(r, MyKey, "bar") 35 | 36 | The application can later access the variable using the same key you provided: 37 | 38 | func MyHandler(w http.ResponseWriter, r *http.Request) { 39 | // val is "bar". 40 | val := context.Get(r, foo.MyKey) 41 | 42 | // returns ("bar", true) 43 | val, ok := context.GetOk(r, foo.MyKey) 44 | // ... 45 | } 46 | 47 | And that's all about the basic usage. We discuss some other ideas below. 48 | 49 | Any type can be stored in the context. To enforce a given type, make the key 50 | private and wrap Get() and Set() to accept and return values of a specific 51 | type: 52 | 53 | type key int 54 | 55 | const mykey key = 0 56 | 57 | // GetMyKey returns a value for this package from the request values. 58 | func GetMyKey(r *http.Request) SomeType { 59 | if rv := context.Get(r, mykey); rv != nil { 60 | return rv.(SomeType) 61 | } 62 | return nil 63 | } 64 | 65 | // SetMyKey sets a value for this package in the request values. 66 | func SetMyKey(r *http.Request, val SomeType) { 67 | context.Set(r, mykey, val) 68 | } 69 | 70 | Variables must be cleared at the end of a request, to remove all values 71 | that were stored. This can be done in an http.Handler, after a request was 72 | served. Just call Clear() passing the request: 73 | 74 | context.Clear(r) 75 | 76 | ...or use ClearHandler(), which conveniently wraps an http.Handler to clear 77 | variables at the end of a request lifetime. 78 | 79 | The Routers from the packages gorilla/mux and gorilla/pat call Clear() 80 | so if you are using either of them you don't need to clear the context manually. 81 | */ 82 | package context 83 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/common/auth.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | import ( 4 | "io/ioutil" 5 | "log" 6 | "net/http" 7 | "time" 8 | 9 | jwt "github.com/dgrijalva/jwt-go" 10 | ) 11 | 12 | // using asymmetric crypto/RSA keys 13 | // location of private/public key files 14 | const ( 15 | // openssl genrsa -out app.rsa 1024 16 | privKeyPath = "keys/app.rsa" 17 | // openssl rsa -in app.rsa -pubout > app.rsa.pub 18 | pubKeyPath = "keys/app.rsa.pub" 19 | ) 20 | 21 | // Private key for signing and public key for verification 22 | var ( 23 | verifyKey, signKey []byte 24 | ) 25 | 26 | // Read the key files before starting http handlers 27 | func initKeys() { 28 | var err error 29 | 30 | signKey, err = ioutil.ReadFile(privKeyPath) 31 | if err != nil { 32 | log.Fatalf("[initKeys]: %s\n", err) 33 | } 34 | 35 | verifyKey, err = ioutil.ReadFile(pubKeyPath) 36 | if err != nil { 37 | log.Fatalf("[initKeys]: %s\n", err) 38 | panic(err) 39 | } 40 | } 41 | 42 | // Generate JWT token 43 | func GenerateJWT(name, role string) (string, error) { 44 | // create a signer for rsa 256 45 | t := jwt.New(jwt.GetSigningMethod("RS256")) 46 | 47 | // set claims for JWT token 48 | t.Claims["iss"] = "admin" 49 | t.Claims["UserInfo"] = struct { 50 | Name string 51 | Role string 52 | }{name, role} 53 | 54 | // set the expire time for JWT token 55 | t.Claims["exp"] = time.Now().Add(time.Minute * 20).Unix() 56 | tokenString, err := t.SignedString(signKey) 57 | if err != nil { 58 | return "", err 59 | } 60 | return tokenString, nil 61 | } 62 | 63 | // Middleware for validating JWT tokens 64 | func Authorize(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) { 65 | // validate the token 66 | token, err := jwt.ParseFromRequest(r, func(token *jwt.Token) (interface{}, error) { 67 | 68 | // Verify the token with public key, which is the counter part of private key 69 | return verifyKey, nil 70 | }) 71 | 72 | if err != nil { 73 | switch err.(type) { 74 | 75 | case *jwt.ValidationError: // JWT validation error 76 | vErr := err.(*jwt.ValidationError) 77 | 78 | switch vErr.Errors { 79 | case jwt.ValidationErrorExpired: //JWT expired 80 | DisplayAppError( 81 | w, 82 | err, 83 | "Access Token is expired, get a new Token", 84 | 401, 85 | ) 86 | return 87 | 88 | default: 89 | DisplayAppError(w, 90 | err, 91 | "Error while parsing the Access Token!", 92 | 500, 93 | ) 94 | return 95 | } 96 | 97 | default: 98 | DisplayAppError(w, 99 | err, 100 | "Error while parsing Access Token!", 101 | 500) 102 | return 103 | } 104 | 105 | } 106 | if token.Valid { 107 | next(w, r) 108 | } else { 109 | DisplayAppError( 110 | w, 111 | err, 112 | "Invalid Access Token", 113 | 401, 114 | ) 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /go-web-master/chapter-10/httptest/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "net/http" 6 | "net/http/httptest" 7 | "strings" 8 | "testing" 9 | 10 | "github.com/gorilla/mux" 11 | ) 12 | 13 | func TestGetUsers(t *testing.T) { 14 | r := mux.NewRouter() 15 | r.HandleFunc("/users", getUsers).Methods("GET") 16 | req, err := http.NewRequest("GET", "/users", nil) 17 | if err != nil { 18 | t.Error(err) 19 | } 20 | w := httptest.NewRecorder() 21 | 22 | r.ServeHTTP(w, req) 23 | if w.Code != 200 { 24 | t.Errorf("HTTP Status expected: 200, got: %d", w.Code) 25 | } 26 | } 27 | 28 | func TestCreateUser(t *testing.T) { 29 | r := mux.NewRouter() 30 | r.HandleFunc("/users", createUser).Methods("POST") 31 | 32 | userJson := `{"firstname": "shiju", "lastname": "Varghese", "email": "shiju@xyz.com"}` 33 | 34 | req, err := http.NewRequest( 35 | "POST", 36 | "/users", 37 | strings.NewReader(userJson), 38 | ) 39 | if err != nil { 40 | t.Error(err) 41 | } 42 | 43 | w := httptest.NewRecorder() 44 | r.ServeHTTP(w, req) 45 | if w.Code != 201 { 46 | t.Errorf("HTTP Status expected: 201, got: %d", w.Code) 47 | } 48 | } 49 | func TestUniqueEmail(t *testing.T) { 50 | r := mux.NewRouter() 51 | r.HandleFunc("/users", createUser).Methods("POST") 52 | 53 | userJson := `{"firstname": "shiju", "lastname": "Varghese", "email": "shiju@xyz.com"}` 54 | 55 | req, err := http.NewRequest( 56 | "POST", 57 | "/users", 58 | strings.NewReader(userJson), 59 | ) 60 | if err != nil { 61 | t.Error(err) 62 | } 63 | 64 | w := httptest.NewRecorder() 65 | r.ServeHTTP(w, req) 66 | if w.Code != 400 { 67 | t.Error("Bad Request expected, got: %d", w.Code) 68 | } 69 | } 70 | func TestGetUsersClient(t *testing.T) { 71 | r := mux.NewRouter() 72 | r.HandleFunc("/users", getUsers).Methods("GET") 73 | server := httptest.NewServer(r) 74 | defer server.Close() 75 | usersUrl := fmt.Sprintf("%s/users", server.URL) 76 | request, err := http.NewRequest("GET", usersUrl, nil) 77 | 78 | res, err := http.DefaultClient.Do(request) 79 | 80 | if err != nil { 81 | t.Error(err) 82 | } 83 | 84 | if res.StatusCode != 200 { 85 | t.Errorf("HTTP Status expected: 200, got: %d", res.StatusCode) 86 | } 87 | } 88 | func TestCreateUserClient(t *testing.T) { 89 | r := mux.NewRouter() 90 | r.HandleFunc("/users", createUser).Methods("POST") 91 | server := httptest.NewServer(r) 92 | defer server.Close() 93 | usersUrl := fmt.Sprintf("%s/users", server.URL) 94 | userJson := `{"firstname": "Rosmi", "lastname": "Shiju", "email": "rose@xyz.com"}` 95 | request, err := http.NewRequest("POST", usersUrl, strings.NewReader(userJson)) 96 | 97 | res, err := http.DefaultClient.Do(request) 98 | 99 | if err != nil { 100 | t.Error(err) 101 | } 102 | 103 | if res.StatusCode != 201 { 104 | t.Errorf("HTTP Status expected: 201, got: %d", res.StatusCode) 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/github.com/codegangsta/negroni/response_writer.go: -------------------------------------------------------------------------------- 1 | package negroni 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "net" 7 | "net/http" 8 | ) 9 | 10 | // ResponseWriter is a wrapper around http.ResponseWriter that provides extra information about 11 | // the response. It is recommended that middleware handlers use this construct to wrap a responsewriter 12 | // if the functionality calls for it. 13 | type ResponseWriter interface { 14 | http.ResponseWriter 15 | http.Flusher 16 | // Status returns the status code of the response or 0 if the response has not been written. 17 | Status() int 18 | // Written returns whether or not the ResponseWriter has been written. 19 | Written() bool 20 | // Size returns the size of the response body. 21 | Size() int 22 | // Before allows for a function to be called before the ResponseWriter has been written to. This is 23 | // useful for setting headers or any other operations that must happen before a response has been written. 24 | Before(func(ResponseWriter)) 25 | } 26 | 27 | type beforeFunc func(ResponseWriter) 28 | 29 | // NewResponseWriter creates a ResponseWriter that wraps an http.ResponseWriter 30 | func NewResponseWriter(rw http.ResponseWriter) ResponseWriter { 31 | return &responseWriter{rw, 0, 0, nil} 32 | } 33 | 34 | type responseWriter struct { 35 | http.ResponseWriter 36 | status int 37 | size int 38 | beforeFuncs []beforeFunc 39 | } 40 | 41 | func (rw *responseWriter) WriteHeader(s int) { 42 | rw.status = s 43 | rw.callBefore() 44 | rw.ResponseWriter.WriteHeader(s) 45 | } 46 | 47 | func (rw *responseWriter) Write(b []byte) (int, error) { 48 | if !rw.Written() { 49 | // The status will be StatusOK if WriteHeader has not been called yet 50 | rw.WriteHeader(http.StatusOK) 51 | } 52 | size, err := rw.ResponseWriter.Write(b) 53 | rw.size += size 54 | return size, err 55 | } 56 | 57 | func (rw *responseWriter) Status() int { 58 | return rw.status 59 | } 60 | 61 | func (rw *responseWriter) Size() int { 62 | return rw.size 63 | } 64 | 65 | func (rw *responseWriter) Written() bool { 66 | return rw.status != 0 67 | } 68 | 69 | func (rw *responseWriter) Before(before func(ResponseWriter)) { 70 | rw.beforeFuncs = append(rw.beforeFuncs, before) 71 | } 72 | 73 | func (rw *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { 74 | hijacker, ok := rw.ResponseWriter.(http.Hijacker) 75 | if !ok { 76 | return nil, nil, fmt.Errorf("the ResponseWriter doesn't support the Hijacker interface") 77 | } 78 | return hijacker.Hijack() 79 | } 80 | 81 | func (rw *responseWriter) CloseNotify() <-chan bool { 82 | return rw.ResponseWriter.(http.CloseNotifier).CloseNotify() 83 | } 84 | 85 | func (rw *responseWriter) callBefore() { 86 | for i := len(rw.beforeFuncs) - 1; i >= 0; i-- { 87 | rw.beforeFuncs[i](rw) 88 | } 89 | } 90 | 91 | func (rw *responseWriter) Flush() { 92 | flusher, ok := rw.ResponseWriter.(http.Flusher) 93 | if ok { 94 | flusher.Flush() 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /go-web-master/chapter-4/mux/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "log" 6 | "net/http" 7 | "strconv" 8 | "time" 9 | 10 | "github.com/gorilla/mux" 11 | ) 12 | 13 | type Note struct { 14 | Title string `json:"title"` 15 | Description string `json:"description"` 16 | CreatedOn time.Time `json:"createdon"` 17 | } 18 | 19 | //Store for the Notes collection 20 | var noteStore = make(map[string]Note) 21 | 22 | //Variable to generate key for the collection 23 | var id int = 0 24 | 25 | //HTTP Post - /api/notes 26 | func PostNoteHandler(w http.ResponseWriter, r *http.Request) { 27 | var note Note 28 | // Decode the incoming Note json 29 | err := json.NewDecoder(r.Body).Decode(¬e) 30 | if err != nil { 31 | panic(err) 32 | } 33 | 34 | note.CreatedOn = time.Now() 35 | id++ 36 | k := strconv.Itoa(id) 37 | noteStore[k] = note 38 | 39 | j, err := json.Marshal(note) 40 | if err != nil { 41 | panic(err) 42 | } 43 | w.Header().Set("Content-Type", "application/json") 44 | w.WriteHeader(http.StatusCreated) 45 | w.Write(j) 46 | } 47 | 48 | //HTTP Get - /api/notes 49 | func GetNoteHandler(w http.ResponseWriter, r *http.Request) { 50 | var notes []Note 51 | for _, v := range noteStore { 52 | notes = append(notes, v) 53 | } 54 | w.Header().Set("Content-Type", "application/json") 55 | j, err := json.Marshal(notes) 56 | if err != nil { 57 | panic(err) 58 | } 59 | w.WriteHeader(http.StatusOK) 60 | w.Write(j) 61 | } 62 | 63 | //HTTP Put - /api/notes/{id} 64 | func PutNoteHandler(w http.ResponseWriter, r *http.Request) { 65 | var err error 66 | vars := mux.Vars(r) 67 | k := vars["id"] 68 | var noteToUpd Note 69 | // Decode the incoming Note json 70 | err = json.NewDecoder(r.Body).Decode(¬eToUpd) 71 | if err != nil { 72 | panic(err) 73 | } 74 | if note, ok := noteStore[k]; ok { 75 | noteToUpd.CreatedOn = note.CreatedOn 76 | //delete existing item and add the updated item 77 | delete(noteStore, k) 78 | noteStore[k] = noteToUpd 79 | } else { 80 | log.Printf("Could not find key of Note %s to delete", k) 81 | } 82 | w.WriteHeader(http.StatusNoContent) 83 | } 84 | 85 | //HTTP Delete - /api/notes/{id} 86 | func DeleteNoteHandler(w http.ResponseWriter, r *http.Request) { 87 | vars := mux.Vars(r) 88 | k := vars["id"] 89 | // Remove from Store 90 | if _, ok := noteStore[k]; ok { 91 | //delete existing item 92 | delete(noteStore, k) 93 | } else { 94 | log.Printf("Could not find key of Note %s to delete", k) 95 | } 96 | w.WriteHeader(http.StatusNoContent) 97 | } 98 | 99 | //Entry point of the program 100 | func main() { 101 | r := mux.NewRouter().StrictSlash(false) 102 | r.HandleFunc("/api/notes", GetNoteHandler).Methods("GET") 103 | r.HandleFunc("/api/notes", PostNoteHandler).Methods("POST") 104 | r.HandleFunc("/api/notes/{id}", PutNoteHandler).Methods("PUT") 105 | r.HandleFunc("/api/notes/{id}", DeleteNoteHandler).Methods("DELETE") 106 | 107 | server := &http.Server{ 108 | Addr: ":8080", 109 | Handler: r, 110 | } 111 | log.Println("Listening...") 112 | server.ListenAndServe() 113 | } 114 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/gopkg.in/mgo.v2/testdb/server.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN PRIVATE KEY----- 2 | MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQD9PlbW9OwAX7aB 3 | Nc/UkrKCMztP/YFceIlzoNEpWOWyFO09i4LeulN10Obp3zp3XstYSj5PZsJPgzNk 4 | mFIYC6f2l4W96F0SVEyvnvGzuPlXVBiPBp0xMGQtC4ogCDpwhI3Uo9TOlRNQqxYi 5 | xvH3uwDS3TCIQ+J9E5vud9IwhVCx3P9z0uVjZQ1gj7kaJTzyIMaDbCt2xrdT6XYb 6 | YpLH/24TdzmIWSLpt16q4uJaYFnqvF+hot7iCTUg2OJ8qyw2yfaLe4niLhOavc9R 7 | ziTHHSYwq5Yrcd2VCwyq2mr74dCYdK+w+tuByOX0fI8mIcOygn7g7ltu1wTnWhBs 8 | uHVtkCFjAgMBAAECggEASRAfRc1L+Z+jrAu2doIMdnwJdL6S//bW0UFolyFKw+I9 9 | wC/sBg6D3c3zkS4SVDZJPKPO7mGbVg1oWnGH3eAfCYoV0ACmOY+QwGp/GXcYmRVu 10 | MHWcDIEFpelaZHt7QNM9iEfsMd3YwMFblZUIYozVZADk66uKQMPTjS2Muur7qRSi 11 | wuVfSmsVZ5afH3B1Tr96BbmPsHrXLjvNpjO44k2wrnnSPQjUL7+YiZPvtnNW8Fby 12 | yuo2uoAyjg3+68PYZftOvvNneMsv1uyGlUs6Bk+DVWaqofIztWFdFZyXbHnK2PTk 13 | eGQt5EsL+RwIck5eoqd5vSE+KyzhhydL0zcpngVQoQKBgQD/Yelvholbz5NQtSy3 14 | ZoiW1y7hL1BKzvVNHuAMKJ5WOnj5szhjhKxt/wZ+hk0qcAmlV9WAPbf4izbEwPRC 15 | tnMBQzf1uBxqqbLL6WZ4YAyGrcX3UrT7GXsGfVT4zJjz7oYSw8aPircecw5V4exB 16 | xa4NF+ki8IycXSkHwvW2R56fRwKBgQD92xpxXtte/rUnmENbQmr0aKg7JEfMoih6 17 | MdX+f6mfgjMmqj+L4jPTI8/ql8HEy13SQS1534aDSHO+nBqBK5aHUCRMIgSLnTP9 18 | Xyx9Ngg03SZIkPfykqxQmnZgWkTPMhYS+K1Ao9FGVs8W5jVi7veyAdhHptAcxhP3 19 | IuxvrxVTBQKBgQCluMPiu0snaOwP04HRAZhhSgIB3tIbuXE1OnPpb/JPwmH+p25Q 20 | Jig+uN9d+4jXoRyhTv4c2fAoOS6xPwVCxWKbzyLhMTg/fx+ncy4rryhxvRJaDDGl 21 | QEO1Ul9xlFMs9/vI8YJIY5uxBrimwpStmbn4hSukoLSeQ1X802bfglpMwQKBgD8z 22 | GTY4Y20XBIrDAaHquy32EEwJEEcF6AXj+l7N8bDgfVOW9xMgUb6zH8RL29Xeu5Do 23 | 4SWCXL66fvZpbr/R1jwB28eIgJExpgvicfUKSqi+lhVi4hfmJDg8/FOopZDf61b1 24 | ykxZfHSCkDQnRAtJaylKBEpyYUWImtfgPfTgJfLxAoGAc8A/Tl2h/DsdTA+cA5d7 25 | 1e0l64m13ObruSWRczyru4hy8Yq6E/K2rOFw8cYCcFpy24NqNlk+2iXPLRpWm2zt 26 | 9R497zAPvhK/bfPXjvm0j/VjB44lvRTC9hby/RRMHy9UJk4o/UQaD+1IodxZovvk 27 | SruEA1+5bfBRMW0P+h7Qfe4= 28 | -----END PRIVATE KEY----- 29 | -----BEGIN CERTIFICATE----- 30 | MIIDjTCCAnWgAwIBAgIJAMW+wDfcdzC+MA0GCSqGSIb3DQEBCwUAMFwxCzAJBgNV 31 | BAYTAkdPMQwwCgYDVQQIDANNR08xDDAKBgNVBAcMA01HTzEMMAoGA1UECgwDTUdP 32 | MQ8wDQYDVQQLDAZTZXJ2ZXIxEjAQBgNVBAMMCWxvY2FsaG9zdDAgFw0xNTA5Mjkw 33 | ODM0MTBaGA8yMTE1MDkwNTA4MzQxMFowXDELMAkGA1UEBhMCR08xDDAKBgNVBAgM 34 | A01HTzEMMAoGA1UEBwwDTUdPMQwwCgYDVQQKDANNR08xDzANBgNVBAsMBlNlcnZl 35 | cjESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB 36 | CgKCAQEA/T5W1vTsAF+2gTXP1JKygjM7T/2BXHiJc6DRKVjlshTtPYuC3rpTddDm 37 | 6d86d17LWEo+T2bCT4MzZJhSGAun9peFvehdElRMr57xs7j5V1QYjwadMTBkLQuK 38 | IAg6cISN1KPUzpUTUKsWIsbx97sA0t0wiEPifROb7nfSMIVQsdz/c9LlY2UNYI+5 39 | GiU88iDGg2wrdsa3U+l2G2KSx/9uE3c5iFki6bdequLiWmBZ6rxfoaLe4gk1INji 40 | fKssNsn2i3uJ4i4Tmr3PUc4kxx0mMKuWK3HdlQsMqtpq++HQmHSvsPrbgcjl9HyP 41 | JiHDsoJ+4O5bbtcE51oQbLh1bZAhYwIDAQABo1AwTjAdBgNVHQ4EFgQUhku/u9Kd 42 | OAc1L0OR649vCCuQT+0wHwYDVR0jBBgwFoAUhku/u9KdOAc1L0OR649vCCuQT+0w 43 | DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAw7Bgw3hlWXWSZjLhnSOu 44 | 2mW/UJ2Sj31unHngmgtXwW/04cyzoULb+qmzPe/Z06QMgGIsku1jFBcu0JabQtUG 45 | TyalpfW77tfnvz238CYdImYwE9ZcIGuZGfhs6ySFN9XpW43B8YM7R8wTNPvOcSPw 46 | nfjqU6kueN4TTspQg9cKhDss5DcMTIdgJgLbITXhIsrCu6GlKOgtX3HrdMGpQX7s 47 | UoMXtZVG8pK32vxKWGTZ6DPqESeKjjq74NbYnB3H5U/kDU2dt7LF90C/Umdr9y+C 48 | W2OJb1WBrf6RTcbt8D6d7P9kOfLPOtyn/cbaA/pfXBMQMHqr7XNXzjnaNU+jB7hL 49 | yQ== 50 | -----END CERTIFICATE----- 51 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/gopkg.in/mgo.v2/queue.go: -------------------------------------------------------------------------------- 1 | // mgo - MongoDB driver for Go 2 | // 3 | // Copyright (c) 2010-2012 - Gustavo Niemeyer 4 | // 5 | // All rights reserved. 6 | // 7 | // Redistribution and use in source and binary forms, with or without 8 | // modification, are permitted provided that the following conditions are met: 9 | // 10 | // 1. Redistributions of source code must retain the above copyright notice, this 11 | // list of conditions and the following disclaimer. 12 | // 2. Redistributions in binary form must reproduce the above copyright notice, 13 | // this list of conditions and the following disclaimer in the documentation 14 | // and/or other materials provided with the distribution. 15 | // 16 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 20 | // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | 27 | package mgo 28 | 29 | type queue struct { 30 | elems []interface{} 31 | nelems, popi, pushi int 32 | } 33 | 34 | func (q *queue) Len() int { 35 | return q.nelems 36 | } 37 | 38 | func (q *queue) Push(elem interface{}) { 39 | //debugf("Pushing(pushi=%d popi=%d cap=%d): %#v\n", 40 | // q.pushi, q.popi, len(q.elems), elem) 41 | if q.nelems == len(q.elems) { 42 | q.expand() 43 | } 44 | q.elems[q.pushi] = elem 45 | q.nelems++ 46 | q.pushi = (q.pushi + 1) % len(q.elems) 47 | //debugf(" Pushed(pushi=%d popi=%d cap=%d): %#v\n", 48 | // q.pushi, q.popi, len(q.elems), elem) 49 | } 50 | 51 | func (q *queue) Pop() (elem interface{}) { 52 | //debugf("Popping(pushi=%d popi=%d cap=%d)\n", 53 | // q.pushi, q.popi, len(q.elems)) 54 | if q.nelems == 0 { 55 | return nil 56 | } 57 | elem = q.elems[q.popi] 58 | q.elems[q.popi] = nil // Help GC. 59 | q.nelems-- 60 | q.popi = (q.popi + 1) % len(q.elems) 61 | //debugf(" Popped(pushi=%d popi=%d cap=%d): %#v\n", 62 | // q.pushi, q.popi, len(q.elems), elem) 63 | return elem 64 | } 65 | 66 | func (q *queue) expand() { 67 | curcap := len(q.elems) 68 | var newcap int 69 | if curcap == 0 { 70 | newcap = 8 71 | } else if curcap < 1024 { 72 | newcap = curcap * 2 73 | } else { 74 | newcap = curcap + (curcap / 4) 75 | } 76 | elems := make([]interface{}, newcap) 77 | 78 | if q.popi == 0 { 79 | copy(elems, q.elems) 80 | q.pushi = curcap 81 | } else { 82 | newpopi := newcap - (curcap - q.popi) 83 | copy(elems, q.elems[:q.popi]) 84 | copy(elems[newpopi:], q.elems[q.popi:]) 85 | q.popi = newpopi 86 | } 87 | for i := range q.elems { 88 | q.elems[i] = nil // Help GC. 89 | } 90 | q.elems = elems 91 | } 92 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/controllers/userController.go: -------------------------------------------------------------------------------- 1 | package controllers 2 | 3 | import ( 4 | "encoding/json" 5 | "net/http" 6 | 7 | "github.com/shijuvar/go-web/taskmanager/common" 8 | "github.com/shijuvar/go-web/taskmanager/data" 9 | "github.com/shijuvar/go-web/taskmanager/models" 10 | ) 11 | 12 | // Handler for HTTP Post - "/users/register" 13 | // Add a new User document 14 | func Register(w http.ResponseWriter, r *http.Request) { 15 | var dataResource UserResource 16 | // Decode the incoming User json 17 | err := json.NewDecoder(r.Body).Decode(&dataResource) 18 | if err != nil { 19 | common.DisplayAppError( 20 | w, 21 | err, 22 | "Invalid User data", 23 | 500, 24 | ) 25 | return 26 | } 27 | user := &dataResource.Data 28 | context := NewContext() 29 | defer context.Close() 30 | c := context.DbCollection("users") 31 | repo := &data.UserRepository{c} 32 | // Insert User document 33 | repo.CreateUser(user) 34 | // Clean-up the hashpassword to eliminate it from response JSON 35 | user.HashPassword = nil 36 | if j, err := json.Marshal(UserResource{Data: *user}); err != nil { 37 | common.DisplayAppError( 38 | w, 39 | err, 40 | "An unexpected error has occurred", 41 | 500, 42 | ) 43 | return 44 | } else { 45 | w.Header().Set("Content-Type", "application/json") 46 | w.WriteHeader(http.StatusCreated) 47 | w.Write(j) 48 | } 49 | 50 | } 51 | 52 | // Handler for HTTP Post - "/users/login" 53 | // Authenticate with username and apssword 54 | func Login(w http.ResponseWriter, r *http.Request) { 55 | var dataResource LoginResource 56 | var token string 57 | // Decode the incoming Login json 58 | err := json.NewDecoder(r.Body).Decode(&dataResource) 59 | if err != nil { 60 | common.DisplayAppError( 61 | w, 62 | err, 63 | "Invalid Login data", 64 | 500, 65 | ) 66 | return 67 | } 68 | loginModel := dataResource.Data 69 | loginUser := models.User{ 70 | Email: loginModel.Email, 71 | Password: loginModel.Password, 72 | } 73 | context := NewContext() 74 | defer context.Close() 75 | c := context.DbCollection("users") 76 | repo := &data.UserRepository{c} 77 | // Authenticate the login user 78 | if user, err := repo.Login(loginUser); err != nil { 79 | common.DisplayAppError( 80 | w, 81 | err, 82 | "Invalid login credentials", 83 | 401, 84 | ) 85 | return 86 | } else { //if login is successful 87 | 88 | // Generate JWT token 89 | token, err = common.GenerateJWT(user.Email, "member") 90 | if err != nil { 91 | common.DisplayAppError( 92 | w, 93 | err, 94 | "Eror while generating the access token", 95 | 500, 96 | ) 97 | return 98 | } 99 | w.Header().Set("Content-Type", "application/json") 100 | // Clean-up the hashpassword to eliminate it from response JSON 101 | user.HashPassword = nil 102 | authUser := AuthUserModel{ 103 | User: user, 104 | Token: token, 105 | } 106 | j, err := json.Marshal(AuthUserResource{Data: authUser}) 107 | if err != nil { 108 | common.DisplayAppError( 109 | w, 110 | err, 111 | "An unexpected error has occurred", 112 | 500, 113 | ) 114 | return 115 | } 116 | w.WriteHeader(http.StatusOK) 117 | w.Write(j) 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md: -------------------------------------------------------------------------------- 1 | ## `jwt-go` Version History 2 | 3 | #### 2.2.0 4 | 5 | * Gracefully handle a `nil` `Keyfunc` being passed to `Parse`. Result will now be the parsed token and an error, instead of a panic. 6 | 7 | #### 2.1.0 8 | 9 | Backwards compatible API change that was missed in 2.0.0. 10 | 11 | * The `SignedString` method on `Token` now takes `interface{}` instead of `[]byte` 12 | 13 | #### 2.0.0 14 | 15 | There were two major reasons for breaking backwards compatibility with this update. The first was a refactor required to expand the width of the RSA and HMAC-SHA signing implementations. There will likely be no required code changes to support this change. 16 | 17 | The second update, while unfortunately requiring a small change in integration, is required to open up this library to other signing methods. Not all keys used for all signing methods have a single standard on-disk representation. Requiring `[]byte` as the type for all keys proved too limiting. Additionally, this implementation allows for pre-parsed tokens to be reused, which might matter in an application that parses a high volume of tokens with a small set of keys. Backwards compatibilty has been maintained for passing `[]byte` to the RSA signing methods, but they will also accept `*rsa.PublicKey` and `*rsa.PrivateKey`. 18 | 19 | It is likely the only integration change required here will be to change `func(t *jwt.Token) ([]byte, error)` to `func(t *jwt.Token) (interface{}, error)` when calling `Parse`. 20 | 21 | * **Compatibility Breaking Changes** 22 | * `SigningMethodHS256` is now `*SigningMethodHMAC` instead of `type struct` 23 | * `SigningMethodRS256` is now `*SigningMethodRSA` instead of `type struct` 24 | * `KeyFunc` now returns `interface{}` instead of `[]byte` 25 | * `SigningMethod.Sign` now takes `interface{}` instead of `[]byte` for the key 26 | * `SigningMethod.Verify` now takes `interface{}` instead of `[]byte` for the key 27 | * Renamed type `SigningMethodHS256` to `SigningMethodHMAC`. Specific sizes are now just instances of this type. 28 | * Added public package global `SigningMethodHS256` 29 | * Added public package global `SigningMethodHS384` 30 | * Added public package global `SigningMethodHS512` 31 | * Renamed type `SigningMethodRS256` to `SigningMethodRSA`. Specific sizes are now just instances of this type. 32 | * Added public package global `SigningMethodRS256` 33 | * Added public package global `SigningMethodRS384` 34 | * Added public package global `SigningMethodRS512` 35 | * Moved sample private key for HMAC tests from an inline value to a file on disk. Value is unchanged. 36 | * Refactored the RSA implementation to be easier to read 37 | * Exposed helper methods `ParseRSAPrivateKeyFromPEM` and `ParseRSAPublicKeyFromPEM` 38 | 39 | #### 1.0.2 40 | 41 | * Fixed bug in parsing public keys from certificates 42 | * Added more tests around the parsing of keys for RS256 43 | * Code refactoring in RS256 implementation. No functional changes 44 | 45 | #### 1.0.1 46 | 47 | * Fixed panic if RS256 signing method was passed an invalid key 48 | 49 | #### 1.0.0 50 | 51 | * First versioned release 52 | * API stabilized 53 | * Supports creating, signing, parsing, and validating JWT tokens 54 | * Supports RS256 and HS256 signing methods -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/rsa.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "crypto" 5 | "crypto/rand" 6 | "crypto/rsa" 7 | ) 8 | 9 | // Implements the RSA family of signing methods signing methods 10 | type SigningMethodRSA struct { 11 | Name string 12 | Hash crypto.Hash 13 | } 14 | 15 | // Specific instances for RS256 and company 16 | var ( 17 | SigningMethodRS256 *SigningMethodRSA 18 | SigningMethodRS384 *SigningMethodRSA 19 | SigningMethodRS512 *SigningMethodRSA 20 | ) 21 | 22 | func init() { 23 | // RS256 24 | SigningMethodRS256 = &SigningMethodRSA{"RS256", crypto.SHA256} 25 | RegisterSigningMethod(SigningMethodRS256.Alg(), func() SigningMethod { 26 | return SigningMethodRS256 27 | }) 28 | 29 | // RS384 30 | SigningMethodRS384 = &SigningMethodRSA{"RS384", crypto.SHA384} 31 | RegisterSigningMethod(SigningMethodRS384.Alg(), func() SigningMethod { 32 | return SigningMethodRS384 33 | }) 34 | 35 | // RS512 36 | SigningMethodRS512 = &SigningMethodRSA{"RS512", crypto.SHA512} 37 | RegisterSigningMethod(SigningMethodRS512.Alg(), func() SigningMethod { 38 | return SigningMethodRS512 39 | }) 40 | } 41 | 42 | func (m *SigningMethodRSA) Alg() string { 43 | return m.Name 44 | } 45 | 46 | // Implements the Verify method from SigningMethod 47 | // For this signing method, must be either a PEM encoded PKCS1 or PKCS8 RSA public key as 48 | // []byte, or an rsa.PublicKey structure. 49 | func (m *SigningMethodRSA) Verify(signingString, signature string, key interface{}) error { 50 | var err error 51 | 52 | // Decode the signature 53 | var sig []byte 54 | if sig, err = DecodeSegment(signature); err != nil { 55 | return err 56 | } 57 | 58 | var rsaKey *rsa.PublicKey 59 | 60 | switch k := key.(type) { 61 | case []byte: 62 | if rsaKey, err = ParseRSAPublicKeyFromPEM(k); err != nil { 63 | return err 64 | } 65 | case *rsa.PublicKey: 66 | rsaKey = k 67 | default: 68 | return ErrInvalidKey 69 | } 70 | 71 | // Create hasher 72 | if !m.Hash.Available() { 73 | return ErrHashUnavailable 74 | } 75 | hasher := m.Hash.New() 76 | hasher.Write([]byte(signingString)) 77 | 78 | // Verify the signature 79 | return rsa.VerifyPKCS1v15(rsaKey, m.Hash, hasher.Sum(nil), sig) 80 | } 81 | 82 | // Implements the Sign method from SigningMethod 83 | // For this signing method, must be either a PEM encoded PKCS1 or PKCS8 RSA private key as 84 | // []byte, or an rsa.PrivateKey structure. 85 | func (m *SigningMethodRSA) Sign(signingString string, key interface{}) (string, error) { 86 | var err error 87 | var rsaKey *rsa.PrivateKey 88 | 89 | switch k := key.(type) { 90 | case []byte: 91 | if rsaKey, err = ParseRSAPrivateKeyFromPEM(k); err != nil { 92 | return "", err 93 | } 94 | case *rsa.PrivateKey: 95 | rsaKey = k 96 | default: 97 | return "", ErrInvalidKey 98 | } 99 | 100 | // Create the hasher 101 | if !m.Hash.Available() { 102 | return "", ErrHashUnavailable 103 | } 104 | 105 | hasher := m.Hash.New() 106 | hasher.Write([]byte(signingString)) 107 | 108 | // Sign the string and return the encoded bytes 109 | if sigBytes, err := rsa.SignPKCS1v15(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil)); err == nil { 110 | return EncodeSegment(sigBytes), nil 111 | } else { 112 | return "", err 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /go-web-master/chapter-8/embedded-doc.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "time" 7 | 8 | "gopkg.in/mgo.v2" 9 | "gopkg.in/mgo.v2/bson" 10 | ) 11 | 12 | type Task struct { 13 | Description string 14 | Due time.Time 15 | } 16 | type Category struct { 17 | Id bson.ObjectId `bson:"_id,omitempty"` 18 | Name string 19 | Description string 20 | Tasks []Task 21 | } 22 | 23 | func main() { 24 | session, err := mgo.Dial("localhost") 25 | if err != nil { 26 | panic(err) 27 | } 28 | defer session.Close() 29 | session.SetMode(mgo.Monotonic, true) 30 | //get collection 31 | c := session.DB("taskdb").C("categories") 32 | c.RemoveAll(nil) 33 | //Embedding child collection 34 | doc1 := Category{ 35 | bson.NewObjectId(), 36 | "Open-Source", 37 | "Tasks for open-source projects", 38 | []Task{ 39 | Task{"Create project in mgo", time.Date(2015, time.August, 10, 0, 0, 0, 0, time.UTC)}, 40 | Task{"Create REST API", time.Date(2015, time.August, 20, 0, 0, 0, 0, time.UTC)}, 41 | }, 42 | } 43 | doc2 := Category{ 44 | bson.NewObjectId(), 45 | "GitHub", 46 | "Explore GitHub projects", 47 | []Task{ 48 | Task{"Evaluate Negroni Project", time.Date(2015, time.August, 15, 0, 0, 0, 0, time.UTC)}, 49 | Task{"Explore mgo Project", time.Date(2015, time.August, 10, 0, 0, 0, 0, time.UTC)}, 50 | }, 51 | } 52 | //insert a Category object with embedded Tasks 53 | err = c.Insert(&doc1, &doc2) 54 | if err != nil { 55 | log.Fatal(err) 56 | } 57 | 58 | //get all records 59 | iter := c.Find(nil).Sort("name").Iter() 60 | result := Category{} 61 | for iter.Next(&result) { 62 | fmt.Printf("Category:%s, Description:%s\n", result.Name, result.Description) 63 | fmt.Println("-------------------------------------------") 64 | tasks := result.Tasks 65 | for _, v := range tasks { 66 | fmt.Printf("Task:%s Due:%v\n", v.Description, v.Due) 67 | } 68 | fmt.Println("-------------------------------------------") 69 | } 70 | if err = iter.Close(); err != nil { 71 | log.Fatal(err) 72 | } 73 | // get a single result 74 | result = Category{} 75 | err = c.Find(bson.M{"name": "Open-Source"}).One(&result) 76 | if err != nil { 77 | log.Fatal(err) 78 | } 79 | fmt.Printf("Category:%s, Description:%s\n", result.Name, result.Description) 80 | tasks := result.Tasks 81 | for _, v := range tasks { 82 | fmt.Printf("Task:%s Due:%v\n", v.Description, v.Due) 83 | } 84 | id := result.Id 85 | //updating the document 86 | err = c.Update(bson.M{"_id": id}, 87 | bson.M{"$set": bson.M{ 88 | "description": "Create open-source projects", 89 | "tasks": []Task{ 90 | Task{"Evaluate Negroni Project", time.Date(2015, time.August, 15, 0, 0, 0, 0, time.UTC)}, 91 | Task{"Explore mgo Project", time.Date(2015, time.August, 10, 0, 0, 0, 0, time.UTC)}, 92 | Task{"Explore Gorilla Toolkit", time.Date(2015, time.August, 10, 0, 0, 0, 0, time.UTC)}, 93 | }, 94 | }}) 95 | //Get the updated values 96 | result = Category{} 97 | err = c.FindId(id).One(&result) 98 | if err != nil { 99 | log.Fatal(err) 100 | } 101 | fmt.Printf("Category:%s, Description:%s\n", result.Name, result.Description) 102 | tasks = result.Tasks 103 | for _, v := range tasks { 104 | fmt.Printf("Task:%s Due:%v\n", v.Description, v.Due) 105 | } 106 | 107 | } 108 | -------------------------------------------------------------------------------- /go-web-master/chapter-10/httptestbdd/lib/users_test.go: -------------------------------------------------------------------------------- 1 | package lib_test 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | "net/http" 7 | "net/http/httptest" 8 | "strings" 9 | 10 | "github.com/gorilla/mux" 11 | . "github.com/onsi/ginkgo" 12 | . "github.com/onsi/gomega" 13 | . "github.com/shijuvar/go-web/chapter-10/httptestbdd/lib" 14 | ) 15 | 16 | var _ = Describe("Users", func() { 17 | userRepository := NewFakeUserRepo() 18 | var r *mux.Router 19 | var w *httptest.ResponseRecorder 20 | 21 | BeforeEach(func() { 22 | r = mux.NewRouter() 23 | }) 24 | 25 | Describe("Get Users", func() { 26 | Context("Get all Users", func() { 27 | //providing mocked data of 3 users 28 | It("should get list of Users", func() { 29 | r.Handle("/users", GetUsers(userRepository)).Methods("GET") 30 | req, err := http.NewRequest("GET", "/users", nil) 31 | Expect(err).NotTo(HaveOccurred()) 32 | w = httptest.NewRecorder() 33 | r.ServeHTTP(w, req) 34 | Expect(w.Code).To(Equal(200)) 35 | var users []User 36 | json.Unmarshal(w.Body.Bytes(), &users) 37 | //Verifying mocked data of 3 users 38 | Expect(len(users)).To(Equal(3)) 39 | }) 40 | }) 41 | }) 42 | 43 | Describe("Post a new User", func() { 44 | Context("Provide a valid User data", func() { 45 | It("should create a new User and get HTTP Status: 201", func() { 46 | r.Handle("/users", CreateUser(userRepository)).Methods("POST") 47 | userJson := `{"firstname": "Alex", "lastname": "John", "email": "alex@xyz.com"}` 48 | 49 | req, err := http.NewRequest( 50 | "POST", 51 | "/users", 52 | strings.NewReader(userJson), 53 | ) 54 | Expect(err).NotTo(HaveOccurred()) 55 | w = httptest.NewRecorder() 56 | r.ServeHTTP(w, req) 57 | Expect(w.Code).To(Equal(201)) 58 | }) 59 | }) 60 | Context("Provide a User data that contains duplicate email id", func() { 61 | It("should get HTTP Status: 400", func() { 62 | r.Handle("/users", CreateUser(userRepository)).Methods("POST") 63 | userJson := `{"firstname": "Alex", "lastname": "John", "email": "alex@xyz.com"}` 64 | 65 | req, err := http.NewRequest( 66 | "POST", 67 | "/users", 68 | strings.NewReader(userJson), 69 | ) 70 | Expect(err).NotTo(HaveOccurred()) 71 | w = httptest.NewRecorder() 72 | r.ServeHTTP(w, req) 73 | Expect(w.Code).To(Equal(400)) 74 | }) 75 | }) 76 | }) 77 | }) 78 | 79 | type FakeUserRepository struct { 80 | DataStore []User 81 | } 82 | 83 | func (repo *FakeUserRepository) GetAll() []User { 84 | 85 | return repo.DataStore 86 | } 87 | func (repo *FakeUserRepository) Create(user User) error { 88 | err := repo.Validate(user) 89 | if err != nil { 90 | return err 91 | } 92 | repo.DataStore = append(repo.DataStore, user) 93 | return nil 94 | } 95 | func (repo *FakeUserRepository) Validate(user User) error { 96 | for _, u := range repo.DataStore { 97 | if u.Email == user.Email { 98 | return errors.New("The Email is already exists") 99 | } 100 | } 101 | return nil 102 | } 103 | func NewFakeUserRepo() *FakeUserRepository { 104 | return &FakeUserRepository{ 105 | DataStore: []User{ 106 | User{"Shiju", "Varghese", "shiju@xyz.com"}, 107 | User{"Rosmi", "Shiju", "rose@xyz.com"}, 108 | User{"Irene", "Rose", "irene@xyz.com"}, 109 | }, 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/gopkg.in/mgo.v2/internal/sasl/sspi_windows.h: -------------------------------------------------------------------------------- 1 | // Code adapted from the NodeJS kerberos library: 2 | // 3 | // https://github.com/christkv/kerberos/tree/master/lib/win32/kerberos_sspi.h 4 | // 5 | // Under the terms of the Apache License, Version 2.0: 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | #ifndef SSPI_WINDOWS_H 10 | #define SSPI_WINDOWS_H 11 | 12 | #define SECURITY_WIN32 1 13 | 14 | #include 15 | #include 16 | 17 | int load_secur32_dll(); 18 | 19 | SECURITY_STATUS SEC_ENTRY call_sspi_encrypt_message(PCtxtHandle phContext, unsigned long fQOP, PSecBufferDesc pMessage, unsigned long MessageSeqNo); 20 | 21 | typedef DWORD (WINAPI *encryptMessage_fn)(PCtxtHandle phContext, ULONG fQOP, PSecBufferDesc pMessage, ULONG MessageSeqNo); 22 | 23 | SECURITY_STATUS SEC_ENTRY call_sspi_acquire_credentials_handle( 24 | LPSTR pszPrincipal, // Name of principal 25 | LPSTR pszPackage, // Name of package 26 | unsigned long fCredentialUse, // Flags indicating use 27 | void *pvLogonId, // Pointer to logon ID 28 | void *pAuthData, // Package specific data 29 | SEC_GET_KEY_FN pGetKeyFn, // Pointer to GetKey() func 30 | void *pvGetKeyArgument, // Value to pass to GetKey() 31 | PCredHandle phCredential, // (out) Cred Handle 32 | PTimeStamp ptsExpiry // (out) Lifetime (optional) 33 | ); 34 | 35 | typedef DWORD (WINAPI *acquireCredentialsHandle_fn)( 36 | LPSTR pszPrincipal, LPSTR pszPackage, unsigned long fCredentialUse, 37 | void *pvLogonId, void *pAuthData, SEC_GET_KEY_FN pGetKeyFn, void *pvGetKeyArgument, 38 | PCredHandle phCredential, PTimeStamp ptsExpiry 39 | ); 40 | 41 | SECURITY_STATUS SEC_ENTRY call_sspi_initialize_security_context( 42 | PCredHandle phCredential, // Cred to base context 43 | PCtxtHandle phContext, // Existing context (OPT) 44 | LPSTR pszTargetName, // Name of target 45 | unsigned long fContextReq, // Context Requirements 46 | unsigned long Reserved1, // Reserved, MBZ 47 | unsigned long TargetDataRep, // Data rep of target 48 | PSecBufferDesc pInput, // Input Buffers 49 | unsigned long Reserved2, // Reserved, MBZ 50 | PCtxtHandle phNewContext, // (out) New Context handle 51 | PSecBufferDesc pOutput, // (inout) Output Buffers 52 | unsigned long *pfContextAttr, // (out) Context attrs 53 | PTimeStamp ptsExpiry // (out) Life span (OPT) 54 | ); 55 | 56 | typedef DWORD (WINAPI *initializeSecurityContext_fn)( 57 | PCredHandle phCredential, PCtxtHandle phContext, LPSTR pszTargetName, unsigned long fContextReq, 58 | unsigned long Reserved1, unsigned long TargetDataRep, PSecBufferDesc pInput, unsigned long Reserved2, 59 | PCtxtHandle phNewContext, PSecBufferDesc pOutput, unsigned long *pfContextAttr, PTimeStamp ptsExpiry); 60 | 61 | SECURITY_STATUS SEC_ENTRY call_sspi_query_context_attributes( 62 | PCtxtHandle phContext, // Context to query 63 | unsigned long ulAttribute, // Attribute to query 64 | void *pBuffer // Buffer for attributes 65 | ); 66 | 67 | typedef DWORD (WINAPI *queryContextAttributes_fn)( 68 | PCtxtHandle phContext, unsigned long ulAttribute, void *pBuffer); 69 | 70 | #endif // SSPI_WINDOWS_H 71 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/golang.org/x/crypto/blowfish/cipher.go: -------------------------------------------------------------------------------- 1 | // Copyright 2010 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Package blowfish implements Bruce Schneier's Blowfish encryption algorithm. 6 | package blowfish 7 | 8 | // The code is a port of Bruce Schneier's C implementation. 9 | // See http://www.schneier.com/blowfish.html. 10 | 11 | import "strconv" 12 | 13 | // The Blowfish block size in bytes. 14 | const BlockSize = 8 15 | 16 | // A Cipher is an instance of Blowfish encryption using a particular key. 17 | type Cipher struct { 18 | p [18]uint32 19 | s0, s1, s2, s3 [256]uint32 20 | } 21 | 22 | type KeySizeError int 23 | 24 | func (k KeySizeError) Error() string { 25 | return "crypto/blowfish: invalid key size " + strconv.Itoa(int(k)) 26 | } 27 | 28 | // NewCipher creates and returns a Cipher. 29 | // The key argument should be the Blowfish key, from 1 to 56 bytes. 30 | func NewCipher(key []byte) (*Cipher, error) { 31 | var result Cipher 32 | if k := len(key); k < 1 || k > 56 { 33 | return nil, KeySizeError(k) 34 | } 35 | initCipher(&result) 36 | ExpandKey(key, &result) 37 | return &result, nil 38 | } 39 | 40 | // NewSaltedCipher creates a returns a Cipher that folds a salt into its key 41 | // schedule. For most purposes, NewCipher, instead of NewSaltedCipher, is 42 | // sufficient and desirable. For bcrypt compatiblity, the key can be over 56 43 | // bytes. 44 | func NewSaltedCipher(key, salt []byte) (*Cipher, error) { 45 | if len(salt) == 0 { 46 | return NewCipher(key) 47 | } 48 | var result Cipher 49 | if k := len(key); k < 1 { 50 | return nil, KeySizeError(k) 51 | } 52 | initCipher(&result) 53 | expandKeyWithSalt(key, salt, &result) 54 | return &result, nil 55 | } 56 | 57 | // BlockSize returns the Blowfish block size, 8 bytes. 58 | // It is necessary to satisfy the Block interface in the 59 | // package "crypto/cipher". 60 | func (c *Cipher) BlockSize() int { return BlockSize } 61 | 62 | // Encrypt encrypts the 8-byte buffer src using the key k 63 | // and stores the result in dst. 64 | // Note that for amounts of data larger than a block, 65 | // it is not safe to just call Encrypt on successive blocks; 66 | // instead, use an encryption mode like CBC (see crypto/cipher/cbc.go). 67 | func (c *Cipher) Encrypt(dst, src []byte) { 68 | l := uint32(src[0])<<24 | uint32(src[1])<<16 | uint32(src[2])<<8 | uint32(src[3]) 69 | r := uint32(src[4])<<24 | uint32(src[5])<<16 | uint32(src[6])<<8 | uint32(src[7]) 70 | l, r = encryptBlock(l, r, c) 71 | dst[0], dst[1], dst[2], dst[3] = byte(l>>24), byte(l>>16), byte(l>>8), byte(l) 72 | dst[4], dst[5], dst[6], dst[7] = byte(r>>24), byte(r>>16), byte(r>>8), byte(r) 73 | } 74 | 75 | // Decrypt decrypts the 8-byte buffer src using the key k 76 | // and stores the result in dst. 77 | func (c *Cipher) Decrypt(dst, src []byte) { 78 | l := uint32(src[0])<<24 | uint32(src[1])<<16 | uint32(src[2])<<8 | uint32(src[3]) 79 | r := uint32(src[4])<<24 | uint32(src[5])<<16 | uint32(src[6])<<8 | uint32(src[7]) 80 | l, r = decryptBlock(l, r, c) 81 | dst[0], dst[1], dst[2], dst[3] = byte(l>>24), byte(l>>16), byte(l>>8), byte(l) 82 | dst[4], dst[5], dst[6], dst[7] = byte(r>>24), byte(r>>16), byte(r>>8), byte(r) 83 | } 84 | 85 | func initCipher(c *Cipher) { 86 | copy(c.p[0:], p[0:]) 87 | copy(c.s0[0:], s0[0:]) 88 | copy(c.s1[0:], s1[0:]) 89 | copy(c.s2[0:], s2[0:]) 90 | copy(c.s3[0:], s3[0:]) 91 | } 92 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/gopkg.in/mgo.v2/testdb/client.pem: -------------------------------------------------------------------------------- 1 | To regenerate the key: 2 | 3 | openssl req -newkey rsa:2048 -new -x509 -days 36500 -nodes -out server.crt -keyout server.key 4 | cat server.key server.crt > server.pem 5 | openssl genrsa -out client.key 2048 6 | openssl req -key client.key -new -out client.req 7 | openssl x509 -req -in client.req -CA server.crt -CAkey server.key -days 36500 -CAserial file.srl -out client.crt 8 | cat client.key client.crt > client.pem 9 | 10 | -----BEGIN RSA PRIVATE KEY----- 11 | MIIEogIBAAKCAQEAtFIkIZk/h+CCKq5/EjBEg873Jd68CJsFKESB5Zl5KLwiGQm7 12 | wQidZwLul+cyDfPRDzzo3za4GetesD4FVf2BEF6fg+/o0wLBObPCXqUVxXXnEXrJ 13 | r4f/tItg0riOEBbLslQDzNTtCAEORCoK9MHmWZrF+pYTw+LmHoVeA8QxNIv/GkwJ 14 | Q6DYEQgCa2BTIWq0Uw3WO20M3e2WGm/6Sv9w0pjisZfwBSfBJ5nI/cNW7L8tH4AI 15 | KBhAZwa7vND0RaRYqpO9kyZFzh8e83GBaXoLSj2wK3kwjKHWgp4z//37JAqeFya5 16 | Hx+ftNTXnl/69TnxG44BP8M88ZfDWlpzwpsTXwIDAQABAoIBADzCjOAxZkHfuZyu 17 | La0wTHXpkEfXdJ6ltagq5WY7P6MlOYwcRoK152vlhgXzZl9jL6ely4YjRwec0swq 18 | KdwezpV4fOGVPmuTuw45bx47HEnr/49ZQ4p9FgF9EYQPofbz53FQc/NaMACJcogv 19 | bn+osniw+VMFrOVNmGLiZ5p3Smk8zfXE7GRHO8CL5hpWLWO/aK236yytbfWOjM2f 20 | Pr76ICb26TPRNzYaYUEThU6DtgdLU8pLnJ6QKKaDsjn+zqQzRa+Nvc0c0K8gvWwA 21 | Afq7t0325+uMSwfpLgCOFldcaZQ5uvteJ0CAVRq1MvStnSHBmMzPlgS+NzsDm6lp 22 | QH5+rIkCgYEA5j3jrWsv7TueTNbk8Hr/Zwywc+fA2Ex0pBURBHlHyc6ahSXWSCqo 23 | DtvRGX0GDoK1lCfaIf1qb/DLlGaoHpkEeqcNhXQ+hHs+bZAxfbfBY9+ikit5ZTtl 24 | QN1tIlhaiyLDnwhkpi/hMw1tiouxJUf84Io61z0sCL4hyZSPCpjn0H0CgYEAyH6F 25 | Mwl+bCD3VDL/Dr5WSoOr2B/M3bF5SfvdStwy2IPcDJ716je1Ud/2qFCnKGgqvWhJ 26 | +HU15c7CjAWo7/pXq2/pEMD8fDKTYww4Hr4p6duEA7DpbOGkwcUX8u3eknxUWT9F 27 | jOSbTCvAxuDOC1K3AElyMxVVTNUrFFe8M84R9gsCgYBXmb6RkdG3WlKde7m5gaLB 28 | K4PLZabq5RQQBe/mmtpkfxYtiLrh1FEC7kG9h+MRDExX5V3KRugDVUOv3+shUSjy 29 | HbM4ToUm1NloyE78PTj4bfMl2CKlEJcyucy3H5S7kWuKi5/31wnA6d/+sa2huKUP 30 | Lai7kgu5+9VRJBPUfV7d5QKBgCnhk/13TDtWH5QtGu5/gBMMskbxTaA5xHZZ8H4E 31 | xXJJCRxx0Dje7jduK145itF8AQGT2W/XPC0HJciOHh4TE2EyfWMMjTF8dyFHmimB 32 | 28uIGWmT+Q7Pi9UWUMxkOAwtgIksGGE4F+CvexOQPjpLSwL6VKqrGCh2lwsm0J+Z 33 | ulLFAoGAKlC93c6XEj1A31c1+usdEhUe9BrmTqtSYLYpDNpeMLdZ3VctrAZuOQPZ 34 | 4A4gkkQkqqwZGBYYSEqwqiLU6MsBdHPPZ9u3JXLLOQuh1xGeaKylvHj7qx6iT0Xo 35 | I+FkJ6/3JeMgOina/+wlzD4oyQpqR4Mnh+TuLkDfQTgY+Lg0WPk= 36 | -----END RSA PRIVATE KEY----- 37 | -----BEGIN CERTIFICATE----- 38 | MIIDLjCCAhYCAQcwDQYJKoZIhvcNAQELBQAwXDELMAkGA1UEBhMCR08xDDAKBgNV 39 | BAgMA01HTzEMMAoGA1UEBwwDTUdPMQwwCgYDVQQKDANNR08xDzANBgNVBAsMBlNl 40 | cnZlcjESMBAGA1UEAwwJbG9jYWxob3N0MCAXDTE1MDkyOTA4NDAzMFoYDzIxMTUw 41 | OTA1MDg0MDMwWjBcMQswCQYDVQQGEwJHTzEMMAoGA1UECAwDTUdPMQwwCgYDVQQH 42 | DANNR08xDDAKBgNVBAoMA01HTzEPMA0GA1UECwwGQ2xpZW50MRIwEAYDVQQDDAls 43 | b2NhbGhvc3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC0UiQhmT+H 44 | 4IIqrn8SMESDzvcl3rwImwUoRIHlmXkovCIZCbvBCJ1nAu6X5zIN89EPPOjfNrgZ 45 | 616wPgVV/YEQXp+D7+jTAsE5s8JepRXFdecResmvh/+0i2DSuI4QFsuyVAPM1O0I 46 | AQ5EKgr0weZZmsX6lhPD4uYehV4DxDE0i/8aTAlDoNgRCAJrYFMharRTDdY7bQzd 47 | 7ZYab/pK/3DSmOKxl/AFJ8Enmcj9w1bsvy0fgAgoGEBnBru80PRFpFiqk72TJkXO 48 | Hx7zcYFpegtKPbAreTCModaCnjP//fskCp4XJrkfH5+01NeeX/r1OfEbjgE/wzzx 49 | l8NaWnPCmxNfAgMBAAEwDQYJKoZIhvcNAQELBQADggEBAFwYpje3dCLDOIHYjd+5 50 | CpFOEb+bJsS4ryqm/NblTjIhCLo58hNpMsBqdJHRbHAFRCOE8fvY8yiWtdHeFZcW 51 | DgVRAXfHONLtN7faZaZQnhy/YzOhLfC/8dUMB0gQA8KXhBCPZqQmexE28AfkEO47 52 | PwICAxIWINfjm5VnFMkA3b7bDNLHon/pev2m7HqVQ3pRUJQNK3XgFOdDgRrnuXpR 53 | OKAfHORHVGTh1gf1DVwc0oM+0gnkSiJ1VG0n5pE3zhZ24fmZxu6JQ6X515W7APQI 54 | /nKVH+f1Fo+ustyTNLt8Bwxi1XmwT7IXwnkVSE9Ff6VejppXRF01V0aaWsa3kU3r 55 | z3A= 56 | -----END CERTIFICATE----- 57 | 58 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/gopkg.in/mgo.v2/internal/sasl/sspi_windows.c: -------------------------------------------------------------------------------- 1 | // Code adapted from the NodeJS kerberos library: 2 | // 3 | // https://github.com/christkv/kerberos/tree/master/lib/win32/kerberos_sspi.c 4 | // 5 | // Under the terms of the Apache License, Version 2.0: 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | #include 10 | 11 | #include "sspi_windows.h" 12 | 13 | static HINSTANCE sspi_secur32_dll = NULL; 14 | 15 | int load_secur32_dll() 16 | { 17 | sspi_secur32_dll = LoadLibrary("secur32.dll"); 18 | if (sspi_secur32_dll == NULL) { 19 | return GetLastError(); 20 | } 21 | return 0; 22 | } 23 | 24 | SECURITY_STATUS SEC_ENTRY call_sspi_encrypt_message(PCtxtHandle phContext, unsigned long fQOP, PSecBufferDesc pMessage, unsigned long MessageSeqNo) 25 | { 26 | if (sspi_secur32_dll == NULL) { 27 | return -1; 28 | } 29 | encryptMessage_fn pfn_encryptMessage = (encryptMessage_fn) GetProcAddress(sspi_secur32_dll, "EncryptMessage"); 30 | if (!pfn_encryptMessage) { 31 | return -2; 32 | } 33 | return (*pfn_encryptMessage)(phContext, fQOP, pMessage, MessageSeqNo); 34 | } 35 | 36 | SECURITY_STATUS SEC_ENTRY call_sspi_acquire_credentials_handle( 37 | LPSTR pszPrincipal, LPSTR pszPackage, unsigned long fCredentialUse, 38 | void *pvLogonId, void *pAuthData, SEC_GET_KEY_FN pGetKeyFn, void *pvGetKeyArgument, 39 | PCredHandle phCredential, PTimeStamp ptsExpiry) 40 | { 41 | if (sspi_secur32_dll == NULL) { 42 | return -1; 43 | } 44 | acquireCredentialsHandle_fn pfn_acquireCredentialsHandle; 45 | #ifdef _UNICODE 46 | pfn_acquireCredentialsHandle = (acquireCredentialsHandle_fn) GetProcAddress(sspi_secur32_dll, "AcquireCredentialsHandleW"); 47 | #else 48 | pfn_acquireCredentialsHandle = (acquireCredentialsHandle_fn) GetProcAddress(sspi_secur32_dll, "AcquireCredentialsHandleA"); 49 | #endif 50 | if (!pfn_acquireCredentialsHandle) { 51 | return -2; 52 | } 53 | return (*pfn_acquireCredentialsHandle)( 54 | pszPrincipal, pszPackage, fCredentialUse, pvLogonId, pAuthData, 55 | pGetKeyFn, pvGetKeyArgument, phCredential, ptsExpiry); 56 | } 57 | 58 | SECURITY_STATUS SEC_ENTRY call_sspi_initialize_security_context( 59 | PCredHandle phCredential, PCtxtHandle phContext, LPSTR pszTargetName, 60 | unsigned long fContextReq, unsigned long Reserved1, unsigned long TargetDataRep, 61 | PSecBufferDesc pInput, unsigned long Reserved2, PCtxtHandle phNewContext, 62 | PSecBufferDesc pOutput, unsigned long *pfContextAttr, PTimeStamp ptsExpiry) 63 | { 64 | if (sspi_secur32_dll == NULL) { 65 | return -1; 66 | } 67 | initializeSecurityContext_fn pfn_initializeSecurityContext; 68 | #ifdef _UNICODE 69 | pfn_initializeSecurityContext = (initializeSecurityContext_fn) GetProcAddress(sspi_secur32_dll, "InitializeSecurityContextW"); 70 | #else 71 | pfn_initializeSecurityContext = (initializeSecurityContext_fn) GetProcAddress(sspi_secur32_dll, "InitializeSecurityContextA"); 72 | #endif 73 | if (!pfn_initializeSecurityContext) { 74 | return -2; 75 | } 76 | return (*pfn_initializeSecurityContext)( 77 | phCredential, phContext, pszTargetName, fContextReq, Reserved1, TargetDataRep, 78 | pInput, Reserved2, phNewContext, pOutput, pfContextAttr, ptsExpiry); 79 | } 80 | 81 | SECURITY_STATUS SEC_ENTRY call_sspi_query_context_attributes(PCtxtHandle phContext, unsigned long ulAttribute, void *pBuffer) 82 | { 83 | if (sspi_secur32_dll == NULL) { 84 | return -1; 85 | } 86 | queryContextAttributes_fn pfn_queryContextAttributes; 87 | #ifdef _UNICODE 88 | pfn_queryContextAttributes = (queryContextAttributes_fn) GetProcAddress(sspi_secur32_dll, "QueryContextAttributesW"); 89 | #else 90 | pfn_queryContextAttributes = (queryContextAttributes_fn) GetProcAddress(sspi_secur32_dll, "QueryContextAttributesA"); 91 | #endif 92 | if (!pfn_queryContextAttributes) { 93 | return -2; 94 | } 95 | return (*pfn_queryContextAttributes)(phContext, ulAttribute, pBuffer); 96 | } 97 | -------------------------------------------------------------------------------- /go-web-master/chapter-7/jwtauth/jwtmiddleware.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // using asymmetric crypto/RSA keys 4 | 5 | import ( 6 | "encoding/json" 7 | "fmt" 8 | "io/ioutil" 9 | "log" 10 | "net/http" 11 | "time" 12 | 13 | "github.com/auth0/go-jwt-middleware" 14 | "github.com/codegangsta/negroni" 15 | jwt "github.com/dgrijalva/jwt-go" 16 | "github.com/gorilla/mux" 17 | ) 18 | 19 | // location of the files used for signing and verification 20 | const ( 21 | privKeyPath = "keys/demo.rsa" // openssl genrsa -out app.rsa keysize 22 | pubKeyPath = "keys/demo.rsa.pub" // openssl rsa -in app.rsa -pubout > app.rsa.pub 23 | ) 24 | 25 | // keys are held in global variables 26 | var ( 27 | verifyKey, signKey []byte 28 | ) 29 | 30 | // read the key files before starting http handlers 31 | func init() { 32 | var err error 33 | 34 | signKey, err = ioutil.ReadFile(privKeyPath) 35 | if err != nil { 36 | log.Fatal("Error reading private key") 37 | return 38 | } 39 | 40 | verifyKey, err = ioutil.ReadFile(pubKeyPath) 41 | if err != nil { 42 | log.Fatal("Error reading private key") 43 | return 44 | } 45 | } 46 | 47 | // reads the login credentials, checks them and creates the JWT token 48 | func loginHandler(w http.ResponseWriter, r *http.Request) { 49 | 50 | var user User 51 | //decode into User struct 52 | err := json.NewDecoder(r.Body).Decode(&user) 53 | if err != nil { 54 | w.WriteHeader(http.StatusInternalServerError) 55 | fmt.Fprintln(w, "Error in request body") 56 | return 57 | } 58 | // validate user credentials 59 | if user.UserName != "shijuvar" && user.Password != "pass" { 60 | w.WriteHeader(http.StatusForbidden) 61 | fmt.Fprintln(w, "Wrong info") 62 | return 63 | } 64 | 65 | // create a signer for rsa 256 66 | t := jwt.New(jwt.GetSigningMethod("RS256")) 67 | 68 | // set our claims 69 | t.Claims["iss"] = "admin" 70 | t.Claims["CustomUserInfo"] = struct { 71 | Name string 72 | Role string 73 | }{user.UserName, "Member"} 74 | 75 | // set the expire time 76 | t.Claims["exp"] = time.Now().Add(time.Minute * 20).Unix() 77 | tokenString, err := t.SignedString(signKey) 78 | if err != nil { 79 | w.WriteHeader(http.StatusInternalServerError) 80 | fmt.Fprintln(w, "Sorry, error while Signing Token!") 81 | log.Printf("Token Signing error: %v\n", err) 82 | return 83 | } 84 | response := Token{tokenString} 85 | jsonResponse(response, w) 86 | } 87 | 88 | func adminHandler(w http.ResponseWriter, r *http.Request) { 89 | response := Response{"Welcome to Admin Area"} 90 | jsonResponse(response, w) 91 | } 92 | func authMiddleware(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) { 93 | // validate the token 94 | token, err := jwt.ParseFromRequest(r, func(token *jwt.Token) (interface{}, error) { 95 | return verifyKey, nil 96 | }) 97 | if err == nil && token.Valid { 98 | next(w, r) 99 | } else { 100 | w.WriteHeader(http.StatusUnauthorized) 101 | fmt.Fprint(w, "Authentication failed") 102 | } 103 | } 104 | 105 | type Response struct { 106 | Text string `json:"text"` 107 | } 108 | type Token struct { 109 | Token string `json:"token"` 110 | } 111 | 112 | func jsonResponse(response interface{}, w http.ResponseWriter) { 113 | json, err := json.Marshal(response) 114 | if err != nil { 115 | http.Error(w, err.Error(), http.StatusInternalServerError) 116 | return 117 | } 118 | 119 | w.WriteHeader(http.StatusOK) 120 | w.Header().Set("Content-Type", "application/json") 121 | w.Write(json) 122 | } 123 | 124 | //Entry point of the program 125 | func main() { 126 | 127 | r := mux.NewRouter() 128 | jwtMiddleware := jwtmiddleware.New(jwtmiddleware.Options{ 129 | ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) { 130 | return verifyKey, nil 131 | }, 132 | }) 133 | r.HandleFunc("/login", loginHandler).Methods("POST") 134 | r.Handle("/admin", negroni.New( 135 | negroni.HandlerFunc(jwtMiddleware.HandlerWithNext), 136 | negroni.Wrap(http.HandlerFunc(adminHandler)), 137 | )) 138 | http.Handle("/", r) 139 | log.Println("Listening...") 140 | http.ListenAndServe(":8080", nil) 141 | } 142 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/README.md: -------------------------------------------------------------------------------- 1 | A [go](http://www.golang.org) (or 'golang' for search engine friendliness) implementation of [JSON Web Tokens](http://self-issued.info/docs/draft-jones-json-web-token.html) 2 | 3 | **NOTICE:** A vulnerability in JWT was [recently published](https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/). As this library doesn't force users to validate the `alg` is what they expected, it's possible your usage is effected. There will be an update soon to remedy this, and it will likey require backwards-incompatible changes to the API. In the short term, please make sure your implementation verifies the `alg` is what you expect. 4 | 5 | ## What the heck is a JWT? 6 | 7 | In short, it's a signed JSON object that does something useful (for example, authentication). It's commonly used for `Bearer` tokens in Oauth 2. A token is made of three parts, separated by `.`'s. The first two parts are JSON objects, that have been [base64url](http://tools.ietf.org/html/rfc4648) encoded. The last part is the signature, encoded the same way. 8 | 9 | The first part is called the header. It contains the necessary information for verifying the last part, the signature. For example, which encryption method was used for signing and what key was used. 10 | 11 | The part in the middle is the interesting bit. It's called the Claims and contains the actual stuff you care about. Refer to [the RFC](http://self-issued.info/docs/draft-jones-json-web-token.html) for information about reserved keys and the proper way to add your own. 12 | 13 | ## What's in the box? 14 | 15 | This library supports the parsing and verification as well as the generation and signing of JWTs. Current supported signing algorithms are RSA256 and HMAC SHA256, though hooks are present for adding your own. 16 | 17 | ## Parse and Verify 18 | 19 | Parsing and verifying tokens is pretty straight forward. You pass in the token and a function for looking up the key. This is done as a callback since you may need to parse the token to find out what signing method and key was used. 20 | 21 | ```go 22 | token, err := jwt.Parse(myToken, func(token *jwt.Token) (interface{}, error) { 23 | // Don't forget to validate the alg is what you expect: 24 | if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok { 25 | return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) 26 | } 27 | return myLookupKey(token.Header["kid"]) 28 | }) 29 | 30 | if err == nil && token.Valid { 31 | deliverGoodness("!") 32 | } else { 33 | deliverUtterRejection(":(") 34 | } 35 | ``` 36 | 37 | ## Create a token 38 | 39 | ```go 40 | // Create the token 41 | token := jwt.New(jwt.SigningMethodHS256) 42 | // Set some claims 43 | token.Claims["foo"] = "bar" 44 | token.Claims["exp"] = time.Now().Add(time.Hour * 72).Unix() 45 | // Sign and get the complete encoded token as a string 46 | tokenString, err := token.SignedString(mySigningKey) 47 | ``` 48 | 49 | ## Project Status & Versioning 50 | 51 | This library is considered production ready. Feedback and feature requests are appreciated. The API should be considered stable. There should be very few backwards-incompatible changes outside of major version updates (and only with good reason). 52 | 53 | This project uses [Semantic Versioning 2.0.0](http://semver.org). Accepted pull requests will land on `master`. Periodically, versions will be tagged from `master`. You can find all the releases on [the project releases page](https://github.com/dgrijalva/jwt-go/releases). 54 | 55 | While we try to make it obvious when we make breaking changes, there isn't a great mechanism for pushing announcements out to users. You may want to use this alternative package include: `gopkg.in/dgrijalva/jwt-go.v2`. It will do the right thing WRT semantic versioning. 56 | 57 | ## More 58 | 59 | Documentation can be found [on godoc.org](http://godoc.org/github.com/dgrijalva/jwt-go). 60 | 61 | The command line utility included in this project (cmd/jwt) provides a straightforward example of token creation and parsing as well as a useful tool for debugging your own integration. For a more http centric example, see [this gist](https://gist.github.com/cryptix/45c33ecf0ae54828e63b). 62 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/gopkg.in/mgo.v2/internal/sasl/sasl.go: -------------------------------------------------------------------------------- 1 | // Package sasl is an implementation detail of the mgo package. 2 | // 3 | // This package is not meant to be used by itself. 4 | // 5 | 6 | // +build !windows 7 | 8 | package sasl 9 | 10 | // #cgo LDFLAGS: -lsasl2 11 | // 12 | // struct sasl_conn {}; 13 | // 14 | // #include 15 | // #include 16 | // 17 | // sasl_callback_t *mgo_sasl_callbacks(const char *username, const char *password); 18 | // 19 | import "C" 20 | 21 | import ( 22 | "fmt" 23 | "strings" 24 | "sync" 25 | "unsafe" 26 | ) 27 | 28 | type saslStepper interface { 29 | Step(serverData []byte) (clientData []byte, done bool, err error) 30 | Close() 31 | } 32 | 33 | type saslSession struct { 34 | conn *C.sasl_conn_t 35 | step int 36 | mech string 37 | 38 | cstrings []*C.char 39 | callbacks *C.sasl_callback_t 40 | } 41 | 42 | var initError error 43 | var initOnce sync.Once 44 | 45 | func initSASL() { 46 | rc := C.sasl_client_init(nil) 47 | if rc != C.SASL_OK { 48 | initError = saslError(rc, nil, "cannot initialize SASL library") 49 | } 50 | } 51 | 52 | func New(username, password, mechanism, service, host string) (saslStepper, error) { 53 | initOnce.Do(initSASL) 54 | if initError != nil { 55 | return nil, initError 56 | } 57 | 58 | ss := &saslSession{mech: mechanism} 59 | if service == "" { 60 | service = "mongodb" 61 | } 62 | if i := strings.Index(host, ":"); i >= 0 { 63 | host = host[:i] 64 | } 65 | ss.callbacks = C.mgo_sasl_callbacks(ss.cstr(username), ss.cstr(password)) 66 | rc := C.sasl_client_new(ss.cstr(service), ss.cstr(host), nil, nil, ss.callbacks, 0, &ss.conn) 67 | if rc != C.SASL_OK { 68 | ss.Close() 69 | return nil, saslError(rc, nil, "cannot create new SASL client") 70 | } 71 | return ss, nil 72 | } 73 | 74 | func (ss *saslSession) cstr(s string) *C.char { 75 | cstr := C.CString(s) 76 | ss.cstrings = append(ss.cstrings, cstr) 77 | return cstr 78 | } 79 | 80 | func (ss *saslSession) Close() { 81 | for _, cstr := range ss.cstrings { 82 | C.free(unsafe.Pointer(cstr)) 83 | } 84 | ss.cstrings = nil 85 | 86 | if ss.callbacks != nil { 87 | C.free(unsafe.Pointer(ss.callbacks)) 88 | } 89 | 90 | // The documentation of SASL dispose makes it clear that this should only 91 | // be done when the connection is done, not when the authentication phase 92 | // is done, because an encryption layer may have been negotiated. 93 | // Even then, we'll do this for now, because it's simpler and prevents 94 | // keeping track of this state for every socket. If it breaks, we'll fix it. 95 | C.sasl_dispose(&ss.conn) 96 | } 97 | 98 | func (ss *saslSession) Step(serverData []byte) (clientData []byte, done bool, err error) { 99 | ss.step++ 100 | if ss.step > 10 { 101 | return nil, false, fmt.Errorf("too many SASL steps without authentication") 102 | } 103 | var cclientData *C.char 104 | var cclientDataLen C.uint 105 | var rc C.int 106 | if ss.step == 1 { 107 | var mechanism *C.char // ignored - must match cred 108 | rc = C.sasl_client_start(ss.conn, ss.cstr(ss.mech), nil, &cclientData, &cclientDataLen, &mechanism) 109 | } else { 110 | var cserverData *C.char 111 | var cserverDataLen C.uint 112 | if len(serverData) > 0 { 113 | cserverData = (*C.char)(unsafe.Pointer(&serverData[0])) 114 | cserverDataLen = C.uint(len(serverData)) 115 | } 116 | rc = C.sasl_client_step(ss.conn, cserverData, cserverDataLen, nil, &cclientData, &cclientDataLen) 117 | } 118 | if cclientData != nil && cclientDataLen > 0 { 119 | clientData = C.GoBytes(unsafe.Pointer(cclientData), C.int(cclientDataLen)) 120 | } 121 | if rc == C.SASL_OK { 122 | return clientData, true, nil 123 | } 124 | if rc == C.SASL_CONTINUE { 125 | return clientData, false, nil 126 | } 127 | return nil, false, saslError(rc, ss.conn, "cannot establish SASL session") 128 | } 129 | 130 | func saslError(rc C.int, conn *C.sasl_conn_t, msg string) error { 131 | var detail string 132 | if conn == nil { 133 | detail = C.GoString(C.sasl_errstring(rc, nil, nil)) 134 | } else { 135 | detail = C.GoString(C.sasl_errdetail(conn)) 136 | } 137 | return fmt.Errorf(msg + ": " + detail) 138 | } 139 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/gopkg.in/mgo.v2/stats.go: -------------------------------------------------------------------------------- 1 | // mgo - MongoDB driver for Go 2 | // 3 | // Copyright (c) 2010-2012 - Gustavo Niemeyer 4 | // 5 | // All rights reserved. 6 | // 7 | // Redistribution and use in source and binary forms, with or without 8 | // modification, are permitted provided that the following conditions are met: 9 | // 10 | // 1. Redistributions of source code must retain the above copyright notice, this 11 | // list of conditions and the following disclaimer. 12 | // 2. Redistributions in binary form must reproduce the above copyright notice, 13 | // this list of conditions and the following disclaimer in the documentation 14 | // and/or other materials provided with the distribution. 15 | // 16 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 20 | // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | 27 | package mgo 28 | 29 | import ( 30 | "sync" 31 | ) 32 | 33 | var stats *Stats 34 | var statsMutex sync.Mutex 35 | 36 | func SetStats(enabled bool) { 37 | statsMutex.Lock() 38 | if enabled { 39 | if stats == nil { 40 | stats = &Stats{} 41 | } 42 | } else { 43 | stats = nil 44 | } 45 | statsMutex.Unlock() 46 | } 47 | 48 | func GetStats() (snapshot Stats) { 49 | statsMutex.Lock() 50 | snapshot = *stats 51 | statsMutex.Unlock() 52 | return 53 | } 54 | 55 | func ResetStats() { 56 | statsMutex.Lock() 57 | debug("Resetting stats") 58 | old := stats 59 | stats = &Stats{} 60 | // These are absolute values: 61 | stats.Clusters = old.Clusters 62 | stats.SocketsInUse = old.SocketsInUse 63 | stats.SocketsAlive = old.SocketsAlive 64 | stats.SocketRefs = old.SocketRefs 65 | statsMutex.Unlock() 66 | return 67 | } 68 | 69 | type Stats struct { 70 | Clusters int 71 | MasterConns int 72 | SlaveConns int 73 | SentOps int 74 | ReceivedOps int 75 | ReceivedDocs int 76 | SocketsAlive int 77 | SocketsInUse int 78 | SocketRefs int 79 | } 80 | 81 | func (stats *Stats) cluster(delta int) { 82 | if stats != nil { 83 | statsMutex.Lock() 84 | stats.Clusters += delta 85 | statsMutex.Unlock() 86 | } 87 | } 88 | 89 | func (stats *Stats) conn(delta int, master bool) { 90 | if stats != nil { 91 | statsMutex.Lock() 92 | if master { 93 | stats.MasterConns += delta 94 | } else { 95 | stats.SlaveConns += delta 96 | } 97 | statsMutex.Unlock() 98 | } 99 | } 100 | 101 | func (stats *Stats) sentOps(delta int) { 102 | if stats != nil { 103 | statsMutex.Lock() 104 | stats.SentOps += delta 105 | statsMutex.Unlock() 106 | } 107 | } 108 | 109 | func (stats *Stats) receivedOps(delta int) { 110 | if stats != nil { 111 | statsMutex.Lock() 112 | stats.ReceivedOps += delta 113 | statsMutex.Unlock() 114 | } 115 | } 116 | 117 | func (stats *Stats) receivedDocs(delta int) { 118 | if stats != nil { 119 | statsMutex.Lock() 120 | stats.ReceivedDocs += delta 121 | statsMutex.Unlock() 122 | } 123 | } 124 | 125 | func (stats *Stats) socketsInUse(delta int) { 126 | if stats != nil { 127 | statsMutex.Lock() 128 | stats.SocketsInUse += delta 129 | statsMutex.Unlock() 130 | } 131 | } 132 | 133 | func (stats *Stats) socketsAlive(delta int) { 134 | if stats != nil { 135 | statsMutex.Lock() 136 | stats.SocketsAlive += delta 137 | statsMutex.Unlock() 138 | } 139 | } 140 | 141 | func (stats *Stats) socketRefs(delta int) { 142 | if stats != nil { 143 | statsMutex.Lock() 144 | stats.SocketRefs += delta 145 | statsMutex.Unlock() 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/github.com/gorilla/context/context.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Gorilla Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package context 6 | 7 | import ( 8 | "net/http" 9 | "sync" 10 | "time" 11 | ) 12 | 13 | var ( 14 | mutex sync.RWMutex 15 | data = make(map[*http.Request]map[interface{}]interface{}) 16 | datat = make(map[*http.Request]int64) 17 | ) 18 | 19 | // Set stores a value for a given key in a given request. 20 | func Set(r *http.Request, key, val interface{}) { 21 | mutex.Lock() 22 | if data[r] == nil { 23 | data[r] = make(map[interface{}]interface{}) 24 | datat[r] = time.Now().Unix() 25 | } 26 | data[r][key] = val 27 | mutex.Unlock() 28 | } 29 | 30 | // Get returns a value stored for a given key in a given request. 31 | func Get(r *http.Request, key interface{}) interface{} { 32 | mutex.RLock() 33 | if ctx := data[r]; ctx != nil { 34 | value := ctx[key] 35 | mutex.RUnlock() 36 | return value 37 | } 38 | mutex.RUnlock() 39 | return nil 40 | } 41 | 42 | // GetOk returns stored value and presence state like multi-value return of map access. 43 | func GetOk(r *http.Request, key interface{}) (interface{}, bool) { 44 | mutex.RLock() 45 | if _, ok := data[r]; ok { 46 | value, ok := data[r][key] 47 | mutex.RUnlock() 48 | return value, ok 49 | } 50 | mutex.RUnlock() 51 | return nil, false 52 | } 53 | 54 | // GetAll returns all stored values for the request as a map. Nil is returned for invalid requests. 55 | func GetAll(r *http.Request) map[interface{}]interface{} { 56 | mutex.RLock() 57 | if context, ok := data[r]; ok { 58 | result := make(map[interface{}]interface{}, len(context)) 59 | for k, v := range context { 60 | result[k] = v 61 | } 62 | mutex.RUnlock() 63 | return result 64 | } 65 | mutex.RUnlock() 66 | return nil 67 | } 68 | 69 | // GetAllOk returns all stored values for the request as a map and a boolean value that indicates if 70 | // the request was registered. 71 | func GetAllOk(r *http.Request) (map[interface{}]interface{}, bool) { 72 | mutex.RLock() 73 | context, ok := data[r] 74 | result := make(map[interface{}]interface{}, len(context)) 75 | for k, v := range context { 76 | result[k] = v 77 | } 78 | mutex.RUnlock() 79 | return result, ok 80 | } 81 | 82 | // Delete removes a value stored for a given key in a given request. 83 | func Delete(r *http.Request, key interface{}) { 84 | mutex.Lock() 85 | if data[r] != nil { 86 | delete(data[r], key) 87 | } 88 | mutex.Unlock() 89 | } 90 | 91 | // Clear removes all values stored for a given request. 92 | // 93 | // This is usually called by a handler wrapper to clean up request 94 | // variables at the end of a request lifetime. See ClearHandler(). 95 | func Clear(r *http.Request) { 96 | mutex.Lock() 97 | clear(r) 98 | mutex.Unlock() 99 | } 100 | 101 | // clear is Clear without the lock. 102 | func clear(r *http.Request) { 103 | delete(data, r) 104 | delete(datat, r) 105 | } 106 | 107 | // Purge removes request data stored for longer than maxAge, in seconds. 108 | // It returns the amount of requests removed. 109 | // 110 | // If maxAge <= 0, all request data is removed. 111 | // 112 | // This is only used for sanity check: in case context cleaning was not 113 | // properly set some request data can be kept forever, consuming an increasing 114 | // amount of memory. In case this is detected, Purge() must be called 115 | // periodically until the problem is fixed. 116 | func Purge(maxAge int) int { 117 | mutex.Lock() 118 | count := 0 119 | if maxAge <= 0 { 120 | count = len(data) 121 | data = make(map[*http.Request]map[interface{}]interface{}) 122 | datat = make(map[*http.Request]int64) 123 | } else { 124 | min := time.Now().Unix() - int64(maxAge) 125 | for r := range data { 126 | if datat[r] < min { 127 | clear(r) 128 | count++ 129 | } 130 | } 131 | } 132 | mutex.Unlock() 133 | return count 134 | } 135 | 136 | // ClearHandler wraps an http.Handler and clears request values at the end 137 | // of a request lifetime. 138 | func ClearHandler(h http.Handler) http.Handler { 139 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 140 | defer Clear(r) 141 | h.ServeHTTP(w, r) 142 | }) 143 | } 144 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/gopkg.in/mgo.v2/internal/sasl/sasl_windows.go: -------------------------------------------------------------------------------- 1 | package sasl 2 | 3 | // #include "sasl_windows.h" 4 | import "C" 5 | 6 | import ( 7 | "fmt" 8 | "strings" 9 | "sync" 10 | "unsafe" 11 | ) 12 | 13 | type saslStepper interface { 14 | Step(serverData []byte) (clientData []byte, done bool, err error) 15 | Close() 16 | } 17 | 18 | type saslSession struct { 19 | // Credentials 20 | mech string 21 | service string 22 | host string 23 | userPlusRealm string 24 | target string 25 | domain string 26 | 27 | // Internal state 28 | authComplete bool 29 | errored bool 30 | step int 31 | 32 | // C internal state 33 | credHandle C.CredHandle 34 | context C.CtxtHandle 35 | hasContext C.int 36 | 37 | // Keep track of pointers we need to explicitly free 38 | stringsToFree []*C.char 39 | } 40 | 41 | var initError error 42 | var initOnce sync.Once 43 | 44 | func initSSPI() { 45 | rc := C.load_secur32_dll() 46 | if rc != 0 { 47 | initError = fmt.Errorf("Error loading libraries: %v", rc) 48 | } 49 | } 50 | 51 | func New(username, password, mechanism, service, host string) (saslStepper, error) { 52 | initOnce.Do(initSSPI) 53 | ss := &saslSession{mech: mechanism, hasContext: 0, userPlusRealm: username} 54 | if service == "" { 55 | service = "mongodb" 56 | } 57 | if i := strings.Index(host, ":"); i >= 0 { 58 | host = host[:i] 59 | } 60 | ss.service = service 61 | ss.host = host 62 | 63 | usernameComponents := strings.Split(username, "@") 64 | if len(usernameComponents) < 2 { 65 | return nil, fmt.Errorf("Username '%v' doesn't contain a realm!", username) 66 | } 67 | user := usernameComponents[0] 68 | ss.domain = usernameComponents[1] 69 | ss.target = fmt.Sprintf("%s/%s", ss.service, ss.host) 70 | 71 | var status C.SECURITY_STATUS 72 | // Step 0: call AcquireCredentialsHandle to get a nice SSPI CredHandle 73 | if len(password) > 0 { 74 | status = C.sspi_acquire_credentials_handle(&ss.credHandle, ss.cstr(user), ss.cstr(password), ss.cstr(ss.domain)) 75 | } else { 76 | status = C.sspi_acquire_credentials_handle(&ss.credHandle, ss.cstr(user), nil, ss.cstr(ss.domain)) 77 | } 78 | if status != C.SEC_E_OK { 79 | ss.errored = true 80 | return nil, fmt.Errorf("Couldn't create new SSPI client, error code %v", status) 81 | } 82 | return ss, nil 83 | } 84 | 85 | func (ss *saslSession) cstr(s string) *C.char { 86 | cstr := C.CString(s) 87 | ss.stringsToFree = append(ss.stringsToFree, cstr) 88 | return cstr 89 | } 90 | 91 | func (ss *saslSession) Close() { 92 | for _, cstr := range ss.stringsToFree { 93 | C.free(unsafe.Pointer(cstr)) 94 | } 95 | } 96 | 97 | func (ss *saslSession) Step(serverData []byte) (clientData []byte, done bool, err error) { 98 | ss.step++ 99 | if ss.step > 10 { 100 | return nil, false, fmt.Errorf("too many SSPI steps without authentication") 101 | } 102 | var buffer C.PVOID 103 | var bufferLength C.ULONG 104 | if len(serverData) > 0 { 105 | buffer = (C.PVOID)(unsafe.Pointer(&serverData[0])) 106 | bufferLength = C.ULONG(len(serverData)) 107 | } 108 | var status C.int 109 | if ss.authComplete { 110 | // Step 3: last bit of magic to use the correct server credentials 111 | status = C.sspi_send_client_authz_id(&ss.context, &buffer, &bufferLength, ss.cstr(ss.userPlusRealm)) 112 | } else { 113 | // Step 1 + Step 2: set up security context with the server and TGT 114 | status = C.sspi_step(&ss.credHandle, ss.hasContext, &ss.context, &buffer, &bufferLength, ss.cstr(ss.target)) 115 | } 116 | if buffer != C.PVOID(nil) { 117 | defer C.free(unsafe.Pointer(buffer)) 118 | } 119 | if status != C.SEC_E_OK && status != C.SEC_I_CONTINUE_NEEDED { 120 | ss.errored = true 121 | return nil, false, ss.handleSSPIErrorCode(status) 122 | } 123 | 124 | clientData = C.GoBytes(unsafe.Pointer(buffer), C.int(bufferLength)) 125 | if status == C.SEC_E_OK { 126 | ss.authComplete = true 127 | return clientData, true, nil 128 | } else { 129 | ss.hasContext = 1 130 | return clientData, false, nil 131 | } 132 | } 133 | 134 | func (ss *saslSession) handleSSPIErrorCode(code C.int) error { 135 | switch { 136 | case code == C.SEC_E_TARGET_UNKNOWN: 137 | return fmt.Errorf("Target %v@%v not found", ss.target, ss.domain) 138 | } 139 | return fmt.Errorf("Unknown error doing step %v, error code %v", ss.step, code) 140 | } 141 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/gopkg.in/mgo.v2/internal/sasl/sasl_windows.c: -------------------------------------------------------------------------------- 1 | #include "sasl_windows.h" 2 | 3 | static const LPSTR SSPI_PACKAGE_NAME = "kerberos"; 4 | 5 | SECURITY_STATUS SEC_ENTRY sspi_acquire_credentials_handle(CredHandle *cred_handle, char *username, char *password, char *domain) 6 | { 7 | SEC_WINNT_AUTH_IDENTITY auth_identity; 8 | SECURITY_INTEGER ignored; 9 | 10 | auth_identity.Flags = SEC_WINNT_AUTH_IDENTITY_ANSI; 11 | auth_identity.User = (LPSTR) username; 12 | auth_identity.UserLength = strlen(username); 13 | auth_identity.Password = (LPSTR) password; 14 | auth_identity.PasswordLength = strlen(password); 15 | auth_identity.Domain = (LPSTR) domain; 16 | auth_identity.DomainLength = strlen(domain); 17 | return call_sspi_acquire_credentials_handle(NULL, SSPI_PACKAGE_NAME, SECPKG_CRED_OUTBOUND, NULL, &auth_identity, NULL, NULL, cred_handle, &ignored); 18 | } 19 | 20 | int sspi_step(CredHandle *cred_handle, int has_context, CtxtHandle *context, PVOID *buffer, ULONG *buffer_length, char *target) 21 | { 22 | SecBufferDesc inbuf; 23 | SecBuffer in_bufs[1]; 24 | SecBufferDesc outbuf; 25 | SecBuffer out_bufs[1]; 26 | 27 | if (has_context > 0) { 28 | // If we already have a context, we now have data to send. 29 | // Put this data in an inbuf. 30 | inbuf.ulVersion = SECBUFFER_VERSION; 31 | inbuf.cBuffers = 1; 32 | inbuf.pBuffers = in_bufs; 33 | in_bufs[0].pvBuffer = *buffer; 34 | in_bufs[0].cbBuffer = *buffer_length; 35 | in_bufs[0].BufferType = SECBUFFER_TOKEN; 36 | } 37 | 38 | outbuf.ulVersion = SECBUFFER_VERSION; 39 | outbuf.cBuffers = 1; 40 | outbuf.pBuffers = out_bufs; 41 | out_bufs[0].pvBuffer = NULL; 42 | out_bufs[0].cbBuffer = 0; 43 | out_bufs[0].BufferType = SECBUFFER_TOKEN; 44 | 45 | ULONG context_attr = 0; 46 | 47 | int ret = call_sspi_initialize_security_context(cred_handle, 48 | has_context > 0 ? context : NULL, 49 | (LPSTR) target, 50 | ISC_REQ_ALLOCATE_MEMORY | ISC_REQ_MUTUAL_AUTH, 51 | 0, 52 | SECURITY_NETWORK_DREP, 53 | has_context > 0 ? &inbuf : NULL, 54 | 0, 55 | context, 56 | &outbuf, 57 | &context_attr, 58 | NULL); 59 | 60 | *buffer = malloc(out_bufs[0].cbBuffer); 61 | *buffer_length = out_bufs[0].cbBuffer; 62 | memcpy(*buffer, out_bufs[0].pvBuffer, *buffer_length); 63 | 64 | return ret; 65 | } 66 | 67 | int sspi_send_client_authz_id(CtxtHandle *context, PVOID *buffer, ULONG *buffer_length, char *user_plus_realm) 68 | { 69 | SecPkgContext_Sizes sizes; 70 | SECURITY_STATUS status = call_sspi_query_context_attributes(context, SECPKG_ATTR_SIZES, &sizes); 71 | 72 | if (status != SEC_E_OK) { 73 | return status; 74 | } 75 | 76 | size_t user_plus_realm_length = strlen(user_plus_realm); 77 | int msgSize = 4 + user_plus_realm_length; 78 | char *msg = malloc((sizes.cbSecurityTrailer + msgSize + sizes.cbBlockSize) * sizeof(char)); 79 | msg[sizes.cbSecurityTrailer + 0] = 1; 80 | msg[sizes.cbSecurityTrailer + 1] = 0; 81 | msg[sizes.cbSecurityTrailer + 2] = 0; 82 | msg[sizes.cbSecurityTrailer + 3] = 0; 83 | memcpy(&msg[sizes.cbSecurityTrailer + 4], user_plus_realm, user_plus_realm_length); 84 | 85 | SecBuffer wrapBufs[3]; 86 | SecBufferDesc wrapBufDesc; 87 | wrapBufDesc.cBuffers = 3; 88 | wrapBufDesc.pBuffers = wrapBufs; 89 | wrapBufDesc.ulVersion = SECBUFFER_VERSION; 90 | 91 | wrapBufs[0].cbBuffer = sizes.cbSecurityTrailer; 92 | wrapBufs[0].BufferType = SECBUFFER_TOKEN; 93 | wrapBufs[0].pvBuffer = msg; 94 | 95 | wrapBufs[1].cbBuffer = msgSize; 96 | wrapBufs[1].BufferType = SECBUFFER_DATA; 97 | wrapBufs[1].pvBuffer = msg + sizes.cbSecurityTrailer; 98 | 99 | wrapBufs[2].cbBuffer = sizes.cbBlockSize; 100 | wrapBufs[2].BufferType = SECBUFFER_PADDING; 101 | wrapBufs[2].pvBuffer = msg + sizes.cbSecurityTrailer + msgSize; 102 | 103 | status = call_sspi_encrypt_message(context, SECQOP_WRAP_NO_ENCRYPT, &wrapBufDesc, 0); 104 | if (status != SEC_E_OK) { 105 | free(msg); 106 | return status; 107 | } 108 | 109 | *buffer_length = wrapBufs[0].cbBuffer + wrapBufs[1].cbBuffer + wrapBufs[2].cbBuffer; 110 | *buffer = malloc(*buffer_length); 111 | 112 | memcpy(*buffer, wrapBufs[0].pvBuffer, wrapBufs[0].cbBuffer); 113 | memcpy(*buffer + wrapBufs[0].cbBuffer, wrapBufs[1].pvBuffer, wrapBufs[1].cbBuffer); 114 | memcpy(*buffer + wrapBufs[0].cbBuffer + wrapBufs[1].cbBuffer, wrapBufs[2].pvBuffer, wrapBufs[2].cbBuffer); 115 | 116 | free(msg); 117 | return SEC_E_OK; 118 | } 119 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/gopkg.in/mgo.v2/testdb/init.js: -------------------------------------------------------------------------------- 1 | //var settings = {heartbeatSleep: 0.05, heartbeatTimeout: 0.5} 2 | var settings = {}; 3 | 4 | // We know the master of the first set (pri=1), but not of the second. 5 | var rs1cfg = {_id: "rs1", 6 | members: [{_id: 1, host: "127.0.0.1:40011", priority: 1, tags: {rs1: "a"}}, 7 | {_id: 2, host: "127.0.0.1:40012", priority: 0, tags: {rs1: "b"}}, 8 | {_id: 3, host: "127.0.0.1:40013", priority: 0, tags: {rs1: "c"}}], 9 | settings: settings} 10 | var rs2cfg = {_id: "rs2", 11 | members: [{_id: 1, host: "127.0.0.1:40021", priority: 1, tags: {rs2: "a"}}, 12 | {_id: 2, host: "127.0.0.1:40022", priority: 1, tags: {rs2: "b"}}, 13 | {_id: 3, host: "127.0.0.1:40023", priority: 1, tags: {rs2: "c"}}], 14 | settings: settings} 15 | var rs3cfg = {_id: "rs3", 16 | members: [{_id: 1, host: "127.0.0.1:40031", priority: 1, tags: {rs3: "a"}}, 17 | {_id: 2, host: "127.0.0.1:40032", priority: 1, tags: {rs3: "b"}}, 18 | {_id: 3, host: "127.0.0.1:40033", priority: 1, tags: {rs3: "c"}}], 19 | settings: settings} 20 | 21 | for (var i = 0; i != 60; i++) { 22 | try { 23 | db1 = new Mongo("127.0.0.1:40001").getDB("admin") 24 | db2 = new Mongo("127.0.0.1:40002").getDB("admin") 25 | rs1a = new Mongo("127.0.0.1:40011").getDB("admin") 26 | rs2a = new Mongo("127.0.0.1:40021").getDB("admin") 27 | rs3a = new Mongo("127.0.0.1:40031").getDB("admin") 28 | break 29 | } catch(err) { 30 | print("Can't connect yet...") 31 | } 32 | sleep(1000) 33 | } 34 | 35 | function hasSSL() { 36 | return Boolean(db1.serverBuildInfo().OpenSSLVersion) 37 | } 38 | 39 | rs1a.runCommand({replSetInitiate: rs1cfg}) 40 | rs2a.runCommand({replSetInitiate: rs2cfg}) 41 | rs3a.runCommand({replSetInitiate: rs3cfg}) 42 | 43 | function configShards() { 44 | cfg1 = new Mongo("127.0.0.1:40201").getDB("admin") 45 | cfg1.runCommand({addshard: "127.0.0.1:40001"}) 46 | cfg1.runCommand({addshard: "rs1/127.0.0.1:40011"}) 47 | 48 | cfg2 = new Mongo("127.0.0.1:40202").getDB("admin") 49 | cfg2.runCommand({addshard: "rs2/127.0.0.1:40021"}) 50 | 51 | cfg3 = new Mongo("127.0.0.1:40203").getDB("admin") 52 | cfg3.runCommand({addshard: "rs3/127.0.0.1:40031"}) 53 | } 54 | 55 | function configAuth() { 56 | var addrs = ["127.0.0.1:40002", "127.0.0.1:40203", "127.0.0.1:40031"] 57 | if (hasSSL()) { 58 | addrs.push("127.0.0.1:40003") 59 | } 60 | for (var i in addrs) { 61 | var db = new Mongo(addrs[i]).getDB("admin") 62 | var v = db.serverBuildInfo().versionArray 63 | if (v < [2, 5]) { 64 | db.addUser("root", "rapadura") 65 | } else { 66 | db.createUser({user: "root", pwd: "rapadura", roles: ["root"]}) 67 | } 68 | db.auth("root", "rapadura") 69 | if (v >= [2, 6]) { 70 | db.createUser({user: "reader", pwd: "rapadura", roles: ["readAnyDatabase"]}) 71 | } else if (v >= [2, 4]) { 72 | db.addUser({user: "reader", pwd: "rapadura", roles: ["readAnyDatabase"]}) 73 | } else { 74 | db.addUser("reader", "rapadura", true) 75 | } 76 | } 77 | } 78 | 79 | function countHealthy(rs) { 80 | var status = rs.runCommand({replSetGetStatus: 1}) 81 | var count = 0 82 | var primary = 0 83 | if (typeof status.members != "undefined") { 84 | for (var i = 0; i != status.members.length; i++) { 85 | var m = status.members[i] 86 | if (m.health == 1 && (m.state == 1 || m.state == 2)) { 87 | count += 1 88 | if (m.state == 1) { 89 | primary = 1 90 | } 91 | } 92 | } 93 | } 94 | if (primary == 0) { 95 | count = 0 96 | } 97 | return count 98 | } 99 | 100 | var totalRSMembers = rs1cfg.members.length + rs2cfg.members.length + rs3cfg.members.length 101 | 102 | for (var i = 0; i != 60; i++) { 103 | var count = countHealthy(rs1a) + countHealthy(rs2a) + countHealthy(rs3a) 104 | print("Replica sets have", count, "healthy nodes.") 105 | if (count == totalRSMembers) { 106 | configShards() 107 | configAuth() 108 | quit(0) 109 | } 110 | sleep(1000) 111 | } 112 | 113 | print("Replica sets didn't sync up properly.") 114 | quit(12) 115 | 116 | // vim:ts=4:sw=4:et 117 | -------------------------------------------------------------------------------- /go-web-master/taskmanager/Godeps/_workspace/src/gopkg.in/mgo.v2/testdb/supervisord.conf: -------------------------------------------------------------------------------- 1 | [supervisord] 2 | logfile = %(here)s/supervisord.log 3 | pidfile = %(here)s/supervisord.pid 4 | directory = %(here)s 5 | #nodaemon = true 6 | 7 | [inet_http_server] 8 | port = 127.0.0.1:9001 9 | 10 | [supervisorctl] 11 | serverurl = http://127.0.0.1:9001 12 | 13 | [rpcinterface:supervisor] 14 | supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface 15 | 16 | [program:db1] 17 | command = mongod --nohttpinterface --noprealloc --nojournal --smallfiles --nssize=1 --oplogSize=1 --shardsvr --dbpath %(here)s/db1 --bind_ip=127.0.0.1,::1 --port 40001 --ipv6 18 | 19 | [program:db2] 20 | command = mongod --nohttpinterface --noprealloc --nojournal --smallfiles --nssize=1 --oplogSize=1 --shardsvr --dbpath %(here)s/db2 --bind_ip=127.0.0.1 --port 40002 --auth 21 | 22 | [program:db3] 23 | command = mongod --nohttpinterface --noprealloc --nojournal --smallfiles --nssize=1 --oplogSize=1 --dbpath %(here)s/db3 --bind_ip=127.0.0.1 --port 40003 --auth --sslMode preferSSL --sslCAFile %(here)s/server.pem --sslPEMKeyFile %(here)s/server.pem 24 | 25 | [program:rs1a] 26 | command = mongod --nohttpinterface --noprealloc --nojournal --smallfiles --nssize=1 --oplogSize=1 --shardsvr --replSet rs1 --dbpath %(here)s/rs1a --bind_ip=127.0.0.1 --port 40011 27 | [program:rs1b] 28 | command = mongod --nohttpinterface --noprealloc --nojournal --smallfiles --nssize=1 --oplogSize=1 --shardsvr --replSet rs1 --dbpath %(here)s/rs1b --bind_ip=127.0.0.1 --port 40012 29 | [program:rs1c] 30 | command = mongod --nohttpinterface --noprealloc --nojournal --smallfiles --nssize=1 --oplogSize=1 --shardsvr --replSet rs1 --dbpath %(here)s/rs1c --bind_ip=127.0.0.1 --port 40013 31 | 32 | [program:rs2a] 33 | command = mongod --nohttpinterface --noprealloc --nojournal --smallfiles --nssize=1 --oplogSize=1 --shardsvr --replSet rs2 --dbpath %(here)s/rs2a --bind_ip=127.0.0.1 --port 40021 34 | [program:rs2b] 35 | command = mongod --nohttpinterface --noprealloc --nojournal --smallfiles --nssize=1 --oplogSize=1 --shardsvr --replSet rs2 --dbpath %(here)s/rs2b --bind_ip=127.0.0.1 --port 40022 36 | [program:rs2c] 37 | command = mongod --nohttpinterface --noprealloc --nojournal --smallfiles --nssize=1 --oplogSize=1 --shardsvr --replSet rs2 --dbpath %(here)s/rs2c --bind_ip=127.0.0.1 --port 40023 38 | 39 | [program:rs3a] 40 | command = mongod --nohttpinterface --noprealloc --nojournal --smallfiles --nssize=1 --oplogSize=1 --shardsvr --replSet rs3 --dbpath %(here)s/rs3a --bind_ip=127.0.0.1 --port 40031 --auth --keyFile=%(here)s/keyfile 41 | [program:rs3b] 42 | command = mongod --nohttpinterface --noprealloc --nojournal --smallfiles --nssize=1 --oplogSize=1 --shardsvr --replSet rs3 --dbpath %(here)s/rs3b --bind_ip=127.0.0.1 --port 40032 --auth --keyFile=%(here)s/keyfile 43 | [program:rs3c] 44 | command = mongod --nohttpinterface --noprealloc --nojournal --smallfiles --nssize=1 --oplogSize=1 --shardsvr --replSet rs3 --dbpath %(here)s/rs3c --bind_ip=127.0.0.1 --port 40033 --auth --keyFile=%(here)s/keyfile 45 | 46 | [program:rs4a] 47 | command = mongod --nohttpinterface --noprealloc --nojournal --smallfiles --nssize=1 --oplogSize=1 --shardsvr --replSet rs4 --dbpath %(here)s/rs4a --bind_ip=127.0.0.1 --port 40041 48 | 49 | [program:cfg1] 50 | command = mongod --nohttpinterface --noprealloc --nojournal --smallfiles --nssize=1 --oplogSize=1 --configsvr --dbpath %(here)s/cfg1 --bind_ip=127.0.0.1 --port 40101 51 | 52 | [program:cfg2] 53 | command = mongod --nohttpinterface --noprealloc --nojournal --smallfiles --nssize=1 --oplogSize=1 --configsvr --dbpath %(here)s/cfg2 --bind_ip=127.0.0.1 --port 40102 54 | 55 | [program:cfg3] 56 | command = mongod --nohttpinterface --noprealloc --nojournal --smallfiles --nssize=1 --oplogSize=1 --configsvr --dbpath %(here)s/cfg3 --bind_ip=127.0.0.1 --port 40103 --auth --keyFile=%(here)s/keyfile 57 | 58 | [program:s1] 59 | command = mongos --configdb 127.0.0.1:40101 --bind_ip=127.0.0.1 --port 40201 --chunkSize 1 60 | 61 | [program:s2] 62 | command = mongos --configdb 127.0.0.1:40102 --bind_ip=127.0.0.1 --port 40202 --chunkSize 1 63 | 64 | [program:s3] 65 | command = mongos --configdb 127.0.0.1:40103 --bind_ip=127.0.0.1 --port 40203 --chunkSize 1 --keyFile=%(here)s/keyfile 66 | --------------------------------------------------------------------------------