diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json index f1e8334..cfd109c 100644 --- a/Godeps/Godeps.json +++ b/Godeps/Godeps.json @@ -5,6 +5,16 @@ "./..." ], "Deps": [ + { + "ImportPath": "github.com/codegangsta/inject", + "Comment": "v1.0-rc1-10-g33e0aa1", + "Rev": "33e0aa1cb7c019ccc3fbe049a8262a6403d30504" + }, + { + "ImportPath": "github.com/go-martini/martini", + "Comment": "v1.0-117-g2047b73", + "Rev": "2047b7394d319aa3feb49db1452202336fb66fb6" + }, { "ImportPath": "github.com/jtolds/gls", "Rev": "f1ac7f4f24f50328e6bc838ca4437d1612a0243c" @@ -35,10 +45,6 @@ "ImportPath": "github.com/smartystreets/goconvey/convey", "Comment": "1.5.0-379-g01b2fc9", "Rev": "01b2fc9c34e7acc187a4f4218ed695dd7f76c361" - }, - { - "ImportPath": "github.com/zenazn/goji", - "Rev": "17b9035bcd162f59e1a1247d4a755124c37052c5" } ] } diff --git a/Godeps/_workspace/src/github.com/codegangsta/inject/.gitignore b/Godeps/_workspace/src/github.com/codegangsta/inject/.gitignore new file mode 100644 index 0000000..df3df8a --- /dev/null +++ b/Godeps/_workspace/src/github.com/codegangsta/inject/.gitignore @@ -0,0 +1,2 @@ +inject +inject.test diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/LICENSE b/Godeps/_workspace/src/github.com/codegangsta/inject/LICENSE similarity index 94% rename from Godeps/_workspace/src/github.com/zenazn/goji/LICENSE rename to Godeps/_workspace/src/github.com/codegangsta/inject/LICENSE index 777b8f4..eb68a0e 100644 --- a/Godeps/_workspace/src/github.com/zenazn/goji/LICENSE +++ b/Godeps/_workspace/src/github.com/codegangsta/inject/LICENSE @@ -1,6 +1,6 @@ -Copyright (c) 2014 Carl Jackson (carl@avtok.com) +The MIT License (MIT) -MIT License +Copyright (c) 2013 Jeremy Saenz 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 diff --git a/Godeps/_workspace/src/github.com/codegangsta/inject/README.md b/Godeps/_workspace/src/github.com/codegangsta/inject/README.md new file mode 100644 index 0000000..679abe0 --- /dev/null +++ b/Godeps/_workspace/src/github.com/codegangsta/inject/README.md @@ -0,0 +1,92 @@ +# inject +-- + import "github.com/codegangsta/inject" + +Package inject provides utilities for mapping and injecting dependencies in +various ways. + +Language Translations: +* [简体中文](translations/README_zh_cn.md) + +## Usage + +#### func InterfaceOf + +```go +func InterfaceOf(value interface{}) reflect.Type +``` +InterfaceOf dereferences a pointer to an Interface type. It panics if value is +not an pointer to an interface. + +#### type Applicator + +```go +type Applicator interface { + // Maps dependencies in the Type map to each field in the struct + // that is tagged with 'inject'. Returns an error if the injection + // fails. + Apply(interface{}) error +} +``` + +Applicator represents an interface for mapping dependencies to a struct. + +#### type Injector + +```go +type Injector interface { + Applicator + Invoker + TypeMapper + // SetParent sets the parent of the injector. If the injector cannot find a + // dependency in its Type map it will check its parent before returning an + // error. + SetParent(Injector) +} +``` + +Injector represents an interface for mapping and injecting dependencies into +structs and function arguments. + +#### func New + +```go +func New() Injector +``` +New returns a new Injector. + +#### type Invoker + +```go +type Invoker interface { + // Invoke attempts to call the interface{} provided as a function, + // providing dependencies for function arguments based on Type. Returns + // a slice of reflect.Value representing the returned values of the function. + // Returns an error if the injection fails. + Invoke(interface{}) ([]reflect.Value, error) +} +``` + +Invoker represents an interface for calling functions via reflection. + +#### type TypeMapper + +```go +type TypeMapper interface { + // Maps the interface{} value based on its immediate type from reflect.TypeOf. + Map(interface{}) TypeMapper + // Maps the interface{} value based on the pointer of an Interface provided. + // This is really only useful for mapping a value as an interface, as interfaces + // cannot at this time be referenced directly without a pointer. + MapTo(interface{}, interface{}) TypeMapper + // Provides a possibility to directly insert a mapping based on type and value. + // This makes it possible to directly map type arguments not possible to instantiate + // with reflect like unidirectional channels. + Set(reflect.Type, reflect.Value) TypeMapper + // Returns the Value that is mapped to the current type. Returns a zeroed Value if + // the Type has not been mapped. + Get(reflect.Type) reflect.Value +} +``` + +TypeMapper represents an interface for mapping interface{} values based on type. diff --git a/Godeps/_workspace/src/github.com/codegangsta/inject/inject.go b/Godeps/_workspace/src/github.com/codegangsta/inject/inject.go new file mode 100644 index 0000000..3ff713c --- /dev/null +++ b/Godeps/_workspace/src/github.com/codegangsta/inject/inject.go @@ -0,0 +1,187 @@ +// Package inject provides utilities for mapping and injecting dependencies in various ways. +package inject + +import ( + "fmt" + "reflect" +) + +// Injector represents an interface for mapping and injecting dependencies into structs +// and function arguments. +type Injector interface { + Applicator + Invoker + TypeMapper + // SetParent sets the parent of the injector. If the injector cannot find a + // dependency in its Type map it will check its parent before returning an + // error. + SetParent(Injector) +} + +// Applicator represents an interface for mapping dependencies to a struct. +type Applicator interface { + // Maps dependencies in the Type map to each field in the struct + // that is tagged with 'inject'. Returns an error if the injection + // fails. + Apply(interface{}) error +} + +// Invoker represents an interface for calling functions via reflection. +type Invoker interface { + // Invoke attempts to call the interface{} provided as a function, + // providing dependencies for function arguments based on Type. Returns + // a slice of reflect.Value representing the returned values of the function. + // Returns an error if the injection fails. + Invoke(interface{}) ([]reflect.Value, error) +} + +// TypeMapper represents an interface for mapping interface{} values based on type. +type TypeMapper interface { + // Maps the interface{} value based on its immediate type from reflect.TypeOf. + Map(interface{}) TypeMapper + // Maps the interface{} value based on the pointer of an Interface provided. + // This is really only useful for mapping a value as an interface, as interfaces + // cannot at this time be referenced directly without a pointer. + MapTo(interface{}, interface{}) TypeMapper + // Provides a possibility to directly insert a mapping based on type and value. + // This makes it possible to directly map type arguments not possible to instantiate + // with reflect like unidirectional channels. + Set(reflect.Type, reflect.Value) TypeMapper + // Returns the Value that is mapped to the current type. Returns a zeroed Value if + // the Type has not been mapped. + Get(reflect.Type) reflect.Value +} + +type injector struct { + values map[reflect.Type]reflect.Value + parent Injector +} + +// InterfaceOf dereferences a pointer to an Interface type. +// It panics if value is not an pointer to an interface. +func InterfaceOf(value interface{}) reflect.Type { + t := reflect.TypeOf(value) + + for t.Kind() == reflect.Ptr { + t = t.Elem() + } + + if t.Kind() != reflect.Interface { + panic("Called inject.InterfaceOf with a value that is not a pointer to an interface. (*MyInterface)(nil)") + } + + return t +} + +// New returns a new Injector. +func New() Injector { + return &injector{ + values: make(map[reflect.Type]reflect.Value), + } +} + +// Invoke attempts to call the interface{} provided as a function, +// providing dependencies for function arguments based on Type. +// Returns a slice of reflect.Value representing the returned values of the function. +// Returns an error if the injection fails. +// It panics if f is not a function +func (inj *injector) Invoke(f interface{}) ([]reflect.Value, error) { + t := reflect.TypeOf(f) + + var in = make([]reflect.Value, t.NumIn()) //Panic if t is not kind of Func + for i := 0; i < t.NumIn(); i++ { + argType := t.In(i) + val := inj.Get(argType) + if !val.IsValid() { + return nil, fmt.Errorf("Value not found for type %v", argType) + } + + in[i] = val + } + + return reflect.ValueOf(f).Call(in), nil +} + +// Maps dependencies in the Type map to each field in the struct +// that is tagged with 'inject'. +// Returns an error if the injection fails. +func (inj *injector) Apply(val interface{}) error { + v := reflect.ValueOf(val) + + for v.Kind() == reflect.Ptr { + v = v.Elem() + } + + if v.Kind() != reflect.Struct { + return nil // Should not panic here ? + } + + t := v.Type() + + for i := 0; i < v.NumField(); i++ { + f := v.Field(i) + structField := t.Field(i) + if f.CanSet() && (structField.Tag == "inject" || structField.Tag.Get("inject") != "") { + ft := f.Type() + v := inj.Get(ft) + if !v.IsValid() { + return fmt.Errorf("Value not found for type %v", ft) + } + + f.Set(v) + } + + } + + return nil +} + +// Maps the concrete value of val to its dynamic type using reflect.TypeOf, +// It returns the TypeMapper registered in. +func (i *injector) Map(val interface{}) TypeMapper { + i.values[reflect.TypeOf(val)] = reflect.ValueOf(val) + return i +} + +func (i *injector) MapTo(val interface{}, ifacePtr interface{}) TypeMapper { + i.values[InterfaceOf(ifacePtr)] = reflect.ValueOf(val) + return i +} + +// Maps the given reflect.Type to the given reflect.Value and returns +// the Typemapper the mapping has been registered in. +func (i *injector) Set(typ reflect.Type, val reflect.Value) TypeMapper { + i.values[typ] = val + return i +} + +func (i *injector) Get(t reflect.Type) reflect.Value { + val := i.values[t] + + if val.IsValid() { + return val + } + + // no concrete types found, try to find implementors + // if t is an interface + if t.Kind() == reflect.Interface { + for k, v := range i.values { + if k.Implements(t) { + val = v + break + } + } + } + + // Still no type found, try to look it up on the parent + if !val.IsValid() && i.parent != nil { + val = i.parent.Get(t) + } + + return val + +} + +func (i *injector) SetParent(parent Injector) { + i.parent = parent +} diff --git a/Godeps/_workspace/src/github.com/codegangsta/inject/inject_test.go b/Godeps/_workspace/src/github.com/codegangsta/inject/inject_test.go new file mode 100644 index 0000000..edcc94d --- /dev/null +++ b/Godeps/_workspace/src/github.com/codegangsta/inject/inject_test.go @@ -0,0 +1,159 @@ +package inject_test + +import ( + "fmt" + "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/codegangsta/inject" + "reflect" + "testing" +) + +type SpecialString interface { +} + +type TestStruct struct { + Dep1 string `inject:"t" json:"-"` + Dep2 SpecialString `inject` + Dep3 string +} + +type Greeter struct { + Name string +} + +func (g *Greeter) String() string { + return "Hello, My name is" + g.Name +} + +/* Test Helpers */ +func expect(t *testing.T, a interface{}, b interface{}) { + if a != b { + t.Errorf("Expected %v (type %v) - Got %v (type %v)", b, reflect.TypeOf(b), a, reflect.TypeOf(a)) + } +} + +func refute(t *testing.T, a interface{}, b interface{}) { + if a == b { + t.Errorf("Did not expect %v (type %v) - Got %v (type %v)", b, reflect.TypeOf(b), a, reflect.TypeOf(a)) + } +} + +func Test_InjectorInvoke(t *testing.T) { + injector := inject.New() + expect(t, injector == nil, false) + + dep := "some dependency" + injector.Map(dep) + dep2 := "another dep" + injector.MapTo(dep2, (*SpecialString)(nil)) + dep3 := make(chan *SpecialString) + dep4 := make(chan *SpecialString) + typRecv := reflect.ChanOf(reflect.RecvDir, reflect.TypeOf(dep3).Elem()) + typSend := reflect.ChanOf(reflect.SendDir, reflect.TypeOf(dep4).Elem()) + injector.Set(typRecv, reflect.ValueOf(dep3)) + injector.Set(typSend, reflect.ValueOf(dep4)) + + _, err := injector.Invoke(func(d1 string, d2 SpecialString, d3 <-chan *SpecialString, d4 chan<- *SpecialString) { + expect(t, d1, dep) + expect(t, d2, dep2) + expect(t, reflect.TypeOf(d3).Elem(), reflect.TypeOf(dep3).Elem()) + expect(t, reflect.TypeOf(d4).Elem(), reflect.TypeOf(dep4).Elem()) + expect(t, reflect.TypeOf(d3).ChanDir(), reflect.RecvDir) + expect(t, reflect.TypeOf(d4).ChanDir(), reflect.SendDir) + }) + + expect(t, err, nil) +} + +func Test_InjectorInvokeReturnValues(t *testing.T) { + injector := inject.New() + expect(t, injector == nil, false) + + dep := "some dependency" + injector.Map(dep) + dep2 := "another dep" + injector.MapTo(dep2, (*SpecialString)(nil)) + + result, err := injector.Invoke(func(d1 string, d2 SpecialString) string { + expect(t, d1, dep) + expect(t, d2, dep2) + return "Hello world" + }) + + expect(t, result[0].String(), "Hello world") + expect(t, err, nil) +} + +func Test_InjectorApply(t *testing.T) { + injector := inject.New() + + injector.Map("a dep").MapTo("another dep", (*SpecialString)(nil)) + + s := TestStruct{} + err := injector.Apply(&s) + expect(t, err, nil) + + expect(t, s.Dep1, "a dep") + expect(t, s.Dep2, "another dep") + expect(t, s.Dep3, "") +} + +func Test_InterfaceOf(t *testing.T) { + iType := inject.InterfaceOf((*SpecialString)(nil)) + expect(t, iType.Kind(), reflect.Interface) + + iType = inject.InterfaceOf((**SpecialString)(nil)) + expect(t, iType.Kind(), reflect.Interface) + + // Expecting nil + defer func() { + rec := recover() + refute(t, rec, nil) + }() + iType = inject.InterfaceOf((*testing.T)(nil)) +} + +func Test_InjectorSet(t *testing.T) { + injector := inject.New() + typ := reflect.TypeOf("string") + typSend := reflect.ChanOf(reflect.SendDir, typ) + typRecv := reflect.ChanOf(reflect.RecvDir, typ) + + // instantiating unidirectional channels is not possible using reflect + // http://golang.org/src/pkg/reflect/value.go?s=60463:60504#L2064 + chanRecv := reflect.MakeChan(reflect.ChanOf(reflect.BothDir, typ), 0) + chanSend := reflect.MakeChan(reflect.ChanOf(reflect.BothDir, typ), 0) + + injector.Set(typSend, chanSend) + injector.Set(typRecv, chanRecv) + + expect(t, injector.Get(typSend).IsValid(), true) + expect(t, injector.Get(typRecv).IsValid(), true) + expect(t, injector.Get(chanSend.Type()).IsValid(), false) +} + +func Test_InjectorGet(t *testing.T) { + injector := inject.New() + + injector.Map("some dependency") + + expect(t, injector.Get(reflect.TypeOf("string")).IsValid(), true) + expect(t, injector.Get(reflect.TypeOf(11)).IsValid(), false) +} + +func Test_InjectorSetParent(t *testing.T) { + injector := inject.New() + injector.MapTo("another dep", (*SpecialString)(nil)) + + injector2 := inject.New() + injector2.SetParent(injector) + + expect(t, injector2.Get(inject.InterfaceOf((*SpecialString)(nil))).IsValid(), true) +} + +func TestInjectImplementors(t *testing.T) { + injector := inject.New() + g := &Greeter{"Jeremy"} + injector.Map(g) + + expect(t, injector.Get(inject.InterfaceOf((*fmt.Stringer)(nil))).IsValid(), true) +} diff --git a/Godeps/_workspace/src/github.com/codegangsta/inject/translations/README_zh_cn.md b/Godeps/_workspace/src/github.com/codegangsta/inject/translations/README_zh_cn.md new file mode 100644 index 0000000..0ac3d3f --- /dev/null +++ b/Godeps/_workspace/src/github.com/codegangsta/inject/translations/README_zh_cn.md @@ -0,0 +1,85 @@ +# inject +-- + import "github.com/codegangsta/inject" + +inject包提供了多种对实体的映射和依赖注入方式。 + +## 用法 + +#### func InterfaceOf + +```go +func InterfaceOf(value interface{}) reflect.Type +``` +函数InterfaceOf返回指向接口类型的指针。如果传入的value值不是指向接口的指针,将抛出一个panic异常。 + +#### type Applicator + +```go +type Applicator interface { + // 在Type map中维持对结构体中每个域的引用并用'inject'来标记 + // 如果注入失败将会返回一个error. + Apply(interface{}) error +} +``` + +Applicator接口表示到结构体的依赖映射关系。 + +#### type Injector + +```go +type Injector interface { + Applicator + Invoker + TypeMapper + // SetParent用来设置父injector. 如果在当前injector的Type map中找不到依赖, + // 将会继续从它的父injector中找,直到返回error. + SetParent(Injector) +} +``` + +Injector接口表示对结构体、函数参数的映射和依赖注入。 + +#### func New + +```go +func New() Injector +``` +New创建并返回一个Injector. + +#### type Invoker + +```go +type Invoker interface { + // Invoke尝试将interface{}作为一个函数来调用,并基于Type为函数提供参数。 + // 它将返回reflect.Value的切片,其中存放原函数的返回值。 + // 如果注入失败则返回error. + Invoke(interface{}) ([]reflect.Value, error) +} +``` + +Invoker接口表示通过反射进行函数调用。 + +#### type TypeMapper + +```go +type TypeMapper interface { + // 基于调用reflect.TypeOf得到的类型映射interface{}的值。 + Map(interface{}) TypeMapper + // 基于提供的接口的指针映射interface{}的值。 + // 该函数仅用来将一个值映射为接口,因为接口无法不通过指针而直接引用到。 + MapTo(interface{}, interface{}) TypeMapper + // 为直接插入基于类型和值的map提供一种可能性。 + // 它使得这一类直接映射成为可能:无法通过反射直接实例化的类型参数,如单向管道。 + Set(reflect.Type, reflect.Value) TypeMapper + // 返回映射到当前类型的Value. 如果Type没被映射,将返回对应的零值。 + Get(reflect.Type) reflect.Value +} +``` + +TypeMapper接口用来表示基于类型到接口值的映射。 + + +## 译者 + +张强 (qqbunny@yeah.net) \ No newline at end of file diff --git a/Godeps/_workspace/src/github.com/codegangsta/inject/update_readme.sh b/Godeps/_workspace/src/github.com/codegangsta/inject/update_readme.sh new file mode 100644 index 0000000..497f9a5 --- /dev/null +++ b/Godeps/_workspace/src/github.com/codegangsta/inject/update_readme.sh @@ -0,0 +1,3 @@ +#!/bin/bash +go get github.com/robertkrimen/godocdown/godocdown +godocdown > README.md diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/.gitignore b/Godeps/_workspace/src/github.com/go-martini/martini/.gitignore new file mode 100644 index 0000000..bb78b21 --- /dev/null +++ b/Godeps/_workspace/src/github.com/go-martini/martini/.gitignore @@ -0,0 +1,26 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test + +/.godeps +/.envrc diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/Godeps b/Godeps/_workspace/src/github.com/go-martini/martini/Godeps new file mode 100644 index 0000000..c988ca4 --- /dev/null +++ b/Godeps/_workspace/src/github.com/go-martini/martini/Godeps @@ -0,0 +1 @@ +github.com/codegangsta/inject master diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/LICENSE b/Godeps/_workspace/src/github.com/go-martini/martini/LICENSE new file mode 100644 index 0000000..d3fefb8 --- /dev/null +++ b/Godeps/_workspace/src/github.com/go-martini/martini/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2015 Jeremy Saenz + +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: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +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. diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/README.md b/Godeps/_workspace/src/github.com/go-martini/martini/README.md new file mode 100644 index 0000000..17fc8c3 --- /dev/null +++ b/Godeps/_workspace/src/github.com/go-martini/martini/README.md @@ -0,0 +1,385 @@ +# Martini [![wercker status](https://app.wercker.com/status/9b7dbc6e2654b604cd694d191c3d5487/s/master "wercker status")](https://app.wercker.com/project/bykey/9b7dbc6e2654b604cd694d191c3d5487)[![GoDoc](https://godoc.org/github.com/go-martini/martini?status.png)](http://godoc.org/github.com/go-martini/martini) + +Martini is a powerful package for quickly writing modular web applications/services in Golang. + +Language Translations: +* [繁體中文](translations/README_zh_tw.md) +* [简体中文](translations/README_zh_cn.md) +* [Português Brasileiro (pt_BR)](translations/README_pt_br.md) +* [Español](translations/README_es_ES.md) +* [한국어 번역](translations/README_ko_kr.md) +* [Русский](translations/README_ru_RU.md) +* [日本語](translations/README_ja_JP.md) +* [French](translations/README_fr_FR.md) +* [Turkish](translations/README_tr_TR.md) +* [German](translations/README_de_DE.md) + +## Getting Started + +After installing Go and setting up your [GOPATH](http://golang.org/doc/code.html#GOPATH), create your first `.go` file. We'll call it `server.go`. + +~~~ go +package main + +import "github.com/go-martini/martini" + +func main() { + m := martini.Classic() + m.Get("/", func() string { + return "Hello world!" + }) + m.Run() +} +~~~ + +Then install the Martini package (**go 1.1** or greater is required): +~~~ +go get github.com/go-martini/martini +~~~ + +Then run your server: +~~~ +go run server.go +~~~ + +You will now have a Martini webserver running on `localhost:3000`. + +## Getting Help + +Join the [Mailing list](https://groups.google.com/forum/#!forum/martini-go) + +Watch the [Demo Video](http://martini.codegangsta.io/#demo) + +Ask questions on Stackoverflow using the [martini tag](http://stackoverflow.com/questions/tagged/martini) + +GoDoc [documentation](http://godoc.org/github.com/go-martini/martini) + + +## Features +* Extremely simple to use. +* Non-intrusive design. +* Plays nice with other Golang packages. +* Awesome path matching and routing. +* Modular design - Easy to add functionality, easy to rip stuff out. +* Lots of good handlers/middlewares to use. +* Great 'out of the box' feature set. +* **Fully compatible with the [http.HandlerFunc](http://godoc.org/net/http#HandlerFunc) interface.** +* Default document serving (e.g., for serving AngularJS apps in HTML5 mode). + +## More Middleware +For more middleware and functionality, check out the repositories in the [martini-contrib](https://github.com/martini-contrib) organization. + +## Table of Contents +* [Classic Martini](#classic-martini) + * [Handlers](#handlers) + * [Routing](#routing) + * [Services](#services) + * [Serving Static Files](#serving-static-files) +* [Middleware Handlers](#middleware-handlers) + * [Next()](#next) +* [Martini Env](#martini-env) +* [FAQ](#faq) + +## Classic Martini +To get up and running quickly, [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) provides some reasonable defaults that work well for most web applications: +~~~ go + m := martini.Classic() + // ... middleware and routing goes here + m.Run() +~~~ + +Below is some of the functionality [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) pulls in automatically: + * Request/Response Logging - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger) + * Panic Recovery - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery) + * Static File serving - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) + * Routing - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router) + +### Handlers +Handlers are the heart and soul of Martini. A handler is basically any kind of callable function: +~~~ go +m.Get("/", func() { + println("hello world") +}) +~~~ + +#### Return Values +If a handler returns something, Martini will write the result to the current [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) as a string: +~~~ go +m.Get("/", func() string { + return "hello world" // HTTP 200 : "hello world" +}) +~~~ + +You can also optionally return a status code: +~~~ go +m.Get("/", func() (int, string) { + return 418, "i'm a teapot" // HTTP 418 : "i'm a teapot" +}) +~~~ + +#### Service Injection +Handlers are invoked via reflection. Martini makes use of *Dependency Injection* to resolve dependencies in a Handlers argument list. **This makes Martini completely compatible with golang's `http.HandlerFunc` interface.** + +If you add an argument to your Handler, Martini will search its list of services and attempt to resolve the dependency via type assertion: +~~~ go +m.Get("/", func(res http.ResponseWriter, req *http.Request) { // res and req are injected by Martini + res.WriteHeader(200) // HTTP 200 +}) +~~~ + +The following services are included with [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic): + * [*log.Logger](http://godoc.org/log#Logger) - Global logger for Martini. + * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http request context. + * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string` of named params found by route matching. + * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Route helper service. + * [martini.Route](http://godoc.org/github.com/go-martini/martini#Route) - Current active route. + * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http Response writer interface. + * [*http.Request](http://godoc.org/net/http/#Request) - http Request. + +### Routing +In Martini, a route is an HTTP method paired with a URL-matching pattern. +Each route can take one or more handler methods: +~~~ go +m.Get("/", func() { + // show something +}) + +m.Patch("/", func() { + // update something +}) + +m.Post("/", func() { + // create something +}) + +m.Put("/", func() { + // replace something +}) + +m.Delete("/", func() { + // destroy something +}) + +m.Options("/", func() { + // http options +}) + +m.NotFound(func() { + // handle 404 +}) +~~~ + +Routes are matched in the order they are defined. The first route that +matches the request is invoked. + +Route patterns may include named parameters, accessible via the [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) service: +~~~ go +m.Get("/hello/:name", func(params martini.Params) string { + return "Hello " + params["name"] +}) +~~~ + +Routes can be matched with globs: +~~~ go +m.Get("/hello/**", func(params martini.Params) string { + return "Hello " + params["_1"] +}) +~~~ + +Regular expressions can be used as well: +~~~go +m.Get("/hello/(?P[a-zA-Z]+)", func(params martini.Params) string { + return fmt.Sprintf ("Hello %s", params["name"]) +}) +~~~ +Take a look at the [Go documentation](http://golang.org/pkg/regexp/syntax/) for more info about regular expressions syntax . + +Route handlers can be stacked on top of each other, which is useful for things like authentication and authorization: +~~~ go +m.Get("/secret", authorize, func() { + // this will execute as long as authorize doesn't write a response +}) +~~~ + +Route groups can be added too using the Group method. +~~~ go +m.Group("/books", func(r martini.Router) { + r.Get("/:id", GetBooks) + r.Post("/new", NewBook) + r.Put("/update/:id", UpdateBook) + r.Delete("/delete/:id", DeleteBook) +}) +~~~ + +Just like you can pass middlewares to a handler you can pass middlewares to groups. +~~~ go +m.Group("/books", func(r martini.Router) { + r.Get("/:id", GetBooks) + r.Post("/new", NewBook) + r.Put("/update/:id", UpdateBook) + r.Delete("/delete/:id", DeleteBook) +}, MyMiddleware1, MyMiddleware2) +~~~ + +### Services +Services are objects that are available to be injected into a Handler's argument list. You can map a service on a *Global* or *Request* level. + +#### Global Mapping +A Martini instance implements the inject.Injector interface, so mapping a service is easy: +~~~ go +db := &MyDatabase{} +m := martini.Classic() +m.Map(db) // the service will be available to all handlers as *MyDatabase +// ... +m.Run() +~~~ + +#### Request-Level Mapping +Mapping on the request level can be done in a handler via [martini.Context](http://godoc.org/github.com/go-martini/martini#Context): +~~~ go +func MyCustomLoggerHandler(c martini.Context, req *http.Request) { + logger := &MyCustomLogger{req} + c.Map(logger) // mapped as *MyCustomLogger +} +~~~ + +#### Mapping values to Interfaces +One of the most powerful parts about services is the ability to map a service to an interface. For instance, if you wanted to override the [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) with an object that wrapped it and performed extra operations, you can write the following handler: +~~~ go +func WrapResponseWriter(res http.ResponseWriter, c martini.Context) { + rw := NewSpecialResponseWriter(res) + c.MapTo(rw, (*http.ResponseWriter)(nil)) // override ResponseWriter with our wrapper ResponseWriter +} +~~~ + +### Serving Static Files +A [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) instance automatically serves static files from the "public" directory in the root of your server. +You can serve from more directories by adding more [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) handlers. +~~~ go +m.Use(martini.Static("assets")) // serve from the "assets" directory as well +~~~ + +#### Serving a Default Document +You can specify the URL of a local file to serve when the requested URL is not +found. You can also specify an exclusion prefix so that certain URLs are ignored. +This is useful for servers that serve both static files and have additional +handlers defined (e.g., REST API). When doing so, it's useful to define the +static handler as a part of the NotFound chain. + +The following example serves the `/index.html` file whenever any URL is +requested that does not match any local file and does not start with `/api/v`: +~~~ go +static := martini.Static("assets", martini.StaticOptions{Fallback: "/index.html", Exclude: "/api/v"}) +m.NotFound(static, http.NotFound) +~~~ + +## Middleware Handlers +Middleware Handlers sit between the incoming http request and the router. In essence they are no different than any other Handler in Martini. You can add a middleware handler to the stack like so: +~~~ go +m.Use(func() { + // do some middleware stuff +}) +~~~ + +You can have full control over the middleware stack with the `Handlers` function. This will replace any handlers that have been previously set: +~~~ go +m.Handlers( + Middleware1, + Middleware2, + Middleware3, +) +~~~ + +Middleware Handlers work really well for things like logging, authorization, authentication, sessions, gzipping, error pages and any other operations that must happen before or after an http request: +~~~ go +// validate an api key +m.Use(func(res http.ResponseWriter, req *http.Request) { + if req.Header.Get("X-API-KEY") != "secret123" { + res.WriteHeader(http.StatusUnauthorized) + } +}) +~~~ + +### Next() +[Context.Next()](http://godoc.org/github.com/go-martini/martini#Context) is an optional function that Middleware Handlers can call to yield the until after the other Handlers have been executed. This works really well for any operations that must happen after an http request: +~~~ go +// log before and after a request +m.Use(func(c martini.Context, log *log.Logger){ + log.Println("before a request") + + c.Next() + + log.Println("after a request") +}) +~~~ + +## Martini Env + +Some Martini handlers make use of the `martini.Env` global variable to provide special functionality for development environments vs production environments. It is recommended that the `MARTINI_ENV=production` environment variable to be set when deploying a Martini server into a production environment. + +## FAQ + +### Where do I find middleware X? + +Start by looking in the [martini-contrib](https://github.com/martini-contrib) projects. If it is not there feel free to contact a martini-contrib team member about adding a new repo to the organization. + +* [auth](https://github.com/martini-contrib/auth) - Handlers for authentication. +* [binding](https://github.com/martini-contrib/binding) - Handler for mapping/validating a raw request into a structure. +* [gzip](https://github.com/martini-contrib/gzip) - Handler for adding gzip compress to requests +* [render](https://github.com/martini-contrib/render) - Handler that provides a service for easily rendering JSON and HTML templates. +* [acceptlang](https://github.com/martini-contrib/acceptlang) - Handler for parsing the `Accept-Language` HTTP header. +* [sessions](https://github.com/martini-contrib/sessions) - Handler that provides a Session service. +* [strip](https://github.com/martini-contrib/strip) - URL Prefix stripping. +* [method](https://github.com/martini-contrib/method) - HTTP method overriding via Header or form fields. +* [secure](https://github.com/martini-contrib/secure) - Implements a few quick security wins. +* [encoder](https://github.com/martini-contrib/encoder) - Encoder service for rendering data in several formats and content negotiation. +* [cors](https://github.com/martini-contrib/cors) - Handler that enables CORS support. +* [oauth2](https://github.com/martini-contrib/oauth2) - Handler that provides OAuth 2.0 login for Martini apps. Google Sign-in, Facebook Connect and Github login is supported. +* [vauth](https://github.com/rafecolton/vauth) - Handlers for vender webhook authentication (currently GitHub and TravisCI) +* [permissions2](https://github.com/xyproto/permissions2) - Handler for keeping track of users, login states and permissions. + +### How do I integrate with existing servers? + +A Martini instance implements `http.Handler`, so it can easily be used to serve subtrees +on existing Go servers. For example this is a working Martini app for Google App Engine: + +~~~ go +package hello + +import ( + "net/http" + "github.com/go-martini/martini" +) + +func init() { + m := martini.Classic() + m.Get("/", func() string { + return "Hello world!" + }) + http.Handle("/", m) +} +~~~ + +### How do I change the port/host? + +Martini's `Run` function looks for the PORT and HOST environment variables and uses those. Otherwise Martini will default to localhost:3000. +To have more flexibility over port and host, use the `martini.RunOnAddr` function instead. + +~~~ go + m := martini.Classic() + // ... + log.Fatal(m.RunOnAddr(":8080")) +~~~ + +### Live code reload? + +[gin](https://github.com/codegangsta/gin) and [fresh](https://github.com/pilu/fresh) both live reload martini apps. + +## Contributing +Martini is meant to be kept tiny and clean. Most contributions should end up in a repository in the [martini-contrib](https://github.com/martini-contrib) organization. If you do have a contribution for the core of Martini feel free to put up a Pull Request. + +## About + +Inspired by [express](https://github.com/visionmedia/express) and [sinatra](https://github.com/sinatra/sinatra) + +Martini is obsessively designed by none other than the [Code Gangsta](http://codegangsta.io/) diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/env.go b/Godeps/_workspace/src/github.com/go-martini/martini/env.go new file mode 100644 index 0000000..54d5857 --- /dev/null +++ b/Godeps/_workspace/src/github.com/go-martini/martini/env.go @@ -0,0 +1,31 @@ +package martini + +import ( + "os" +) + +// Envs +const ( + Dev string = "development" + Prod string = "production" + Test string = "test" +) + +// Env is the environment that Martini is executing in. The MARTINI_ENV is read on initialization to set this variable. +var Env = Dev +var Root string + +func setENV(e string) { + if len(e) > 0 { + Env = e + } +} + +func init() { + setENV(os.Getenv("MARTINI_ENV")) + var err error + Root, err = os.Getwd() + if err != nil { + panic(err) + } +} diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/env_test.go b/Godeps/_workspace/src/github.com/go-martini/martini/env_test.go new file mode 100644 index 0000000..d82351e --- /dev/null +++ b/Godeps/_workspace/src/github.com/go-martini/martini/env_test.go @@ -0,0 +1,28 @@ +package martini + +import ( + "testing" +) + +func Test_SetENV(t *testing.T) { + tests := []struct { + in string + out string + }{ + {"", "development"}, + {"not_development", "not_development"}, + } + + for _, test := range tests { + setENV(test.in) + if Env != test.out { + expect(t, Env, test.out) + } + } +} + +func Test_Root(t *testing.T) { + if len(Root) == 0 { + t.Errorf("Expected root path will be set") + } +} diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/go_version.go b/Godeps/_workspace/src/github.com/go-martini/martini/go_version.go new file mode 100644 index 0000000..bd271a8 --- /dev/null +++ b/Godeps/_workspace/src/github.com/go-martini/martini/go_version.go @@ -0,0 +1,7 @@ +// +build !go1.1 + +package martini + +func MartiniDoesNotSupportGo1Point0() { + "Martini requires Go 1.1 or greater." +} diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/logger.go b/Godeps/_workspace/src/github.com/go-martini/martini/logger.go new file mode 100644 index 0000000..d01107c --- /dev/null +++ b/Godeps/_workspace/src/github.com/go-martini/martini/logger.go @@ -0,0 +1,29 @@ +package martini + +import ( + "log" + "net/http" + "time" +) + +// Logger returns a middleware handler that logs the request as it goes in and the response as it goes out. +func Logger() Handler { + return func(res http.ResponseWriter, req *http.Request, c Context, log *log.Logger) { + start := time.Now() + + addr := req.Header.Get("X-Real-IP") + if addr == "" { + addr = req.Header.Get("X-Forwarded-For") + if addr == "" { + addr = req.RemoteAddr + } + } + + log.Printf("Started %s %s for %s", req.Method, req.URL.Path, addr) + + rw := res.(ResponseWriter) + c.Next() + + log.Printf("Completed %v %s in %v\n", rw.Status(), http.StatusText(rw.Status()), time.Since(start)) + } +} diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/logger_test.go b/Godeps/_workspace/src/github.com/go-martini/martini/logger_test.go new file mode 100644 index 0000000..156b149 --- /dev/null +++ b/Godeps/_workspace/src/github.com/go-martini/martini/logger_test.go @@ -0,0 +1,31 @@ +package martini + +import ( + "bytes" + "log" + "net/http" + "net/http/httptest" + "testing" +) + +func Test_Logger(t *testing.T) { + buff := bytes.NewBufferString("") + recorder := httptest.NewRecorder() + + m := New() + // replace log for testing + m.Map(log.New(buff, "[martini] ", 0)) + m.Use(Logger()) + m.Use(func(res http.ResponseWriter) { + res.WriteHeader(http.StatusNotFound) + }) + + req, err := http.NewRequest("GET", "http://localhost:3000/foobar", nil) + if err != nil { + t.Error(err) + } + + m.ServeHTTP(recorder, req) + expect(t, recorder.Code, http.StatusNotFound) + refute(t, len(buff.String()), 0) +} diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/martini.go b/Godeps/_workspace/src/github.com/go-martini/martini/martini.go new file mode 100644 index 0000000..d9bd41f --- /dev/null +++ b/Godeps/_workspace/src/github.com/go-martini/martini/martini.go @@ -0,0 +1,183 @@ +// Package martini is a powerful package for quickly writing modular web applications/services in Golang. +// +// For a full guide visit http://github.com/go-martini/martini +// +// package main +// +// import "github.com/go-martini/martini" +// +// func main() { +// m := martini.Classic() +// +// m.Get("/", func() string { +// return "Hello world!" +// }) +// +// m.Run() +// } +package martini + +import ( + "log" + "net/http" + "os" + "reflect" + + "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/codegangsta/inject" +) + +// Martini represents the top level web application. inject.Injector methods can be invoked to map services on a global level. +type Martini struct { + inject.Injector + handlers []Handler + action Handler + logger *log.Logger +} + +// New creates a bare bones Martini instance. Use this method if you want to have full control over the middleware that is used. +func New() *Martini { + m := &Martini{Injector: inject.New(), action: func() {}, logger: log.New(os.Stdout, "[martini] ", 0)} + m.Map(m.logger) + m.Map(defaultReturnHandler()) + return m +} + +// Handlers sets the entire middleware stack with the given Handlers. This will clear any current middleware handlers. +// Will panic if any of the handlers is not a callable function +func (m *Martini) Handlers(handlers ...Handler) { + m.handlers = make([]Handler, 0) + for _, handler := range handlers { + m.Use(handler) + } +} + +// Action sets the handler that will be called after all the middleware has been invoked. This is set to martini.Router in a martini.Classic(). +func (m *Martini) Action(handler Handler) { + validateHandler(handler) + m.action = handler +} + +// Use adds a middleware Handler to the stack. Will panic if the handler is not a callable func. Middleware Handlers are invoked in the order that they are added. +func (m *Martini) Use(handler Handler) { + validateHandler(handler) + + m.handlers = append(m.handlers, handler) +} + +// ServeHTTP is the HTTP Entry point for a Martini instance. Useful if you want to control your own HTTP server. +func (m *Martini) ServeHTTP(res http.ResponseWriter, req *http.Request) { + m.createContext(res, req).run() +} + +// Run the http server on a given host and port. +func (m *Martini) RunOnAddr(addr string) { + // TODO: Should probably be implemented using a new instance of http.Server in place of + // calling http.ListenAndServer directly, so that it could be stored in the martini struct for later use. + // This would also allow to improve testing when a custom host and port are passed. + + logger := m.Injector.Get(reflect.TypeOf(m.logger)).Interface().(*log.Logger) + logger.Printf("listening on %s (%s)\n", addr, Env) + logger.Fatalln(http.ListenAndServe(addr, m)) +} + +// Run the http server. Listening on os.GetEnv("PORT") or 3000 by default. +func (m *Martini) Run() { + port := os.Getenv("PORT") + if len(port) == 0 { + port = "3000" + } + + host := os.Getenv("HOST") + + m.RunOnAddr(host + ":" + port) +} + +func (m *Martini) createContext(res http.ResponseWriter, req *http.Request) *context { + c := &context{inject.New(), m.handlers, m.action, NewResponseWriter(res), 0} + c.SetParent(m) + c.MapTo(c, (*Context)(nil)) + c.MapTo(c.rw, (*http.ResponseWriter)(nil)) + c.Map(req) + return c +} + +// ClassicMartini represents a Martini with some reasonable defaults. Embeds the router functions for convenience. +type ClassicMartini struct { + *Martini + Router +} + +// Classic creates a classic Martini with some basic default middleware - martini.Logger, martini.Recovery and martini.Static. +// Classic also maps martini.Routes as a service. +func Classic() *ClassicMartini { + r := NewRouter() + m := New() + m.Use(Logger()) + m.Use(Recovery()) + m.Use(Static("public")) + m.MapTo(r, (*Routes)(nil)) + m.Action(r.Handle) + return &ClassicMartini{m, r} +} + +// Handler can be any callable function. Martini attempts to inject services into the handler's argument list. +// Martini will panic if an argument could not be fullfilled via dependency injection. +type Handler interface{} + +func validateHandler(handler Handler) { + if reflect.TypeOf(handler).Kind() != reflect.Func { + panic("martini handler must be a callable func") + } +} + +// Context represents a request context. Services can be mapped on the request level from this interface. +type Context interface { + inject.Injector + // Next is an optional function that Middleware Handlers can call to yield the until after + // the other Handlers have been executed. This works really well for any operations that must + // happen after an http request + Next() + // Written returns whether or not the response for this context has been written. + Written() bool +} + +type context struct { + inject.Injector + handlers []Handler + action Handler + rw ResponseWriter + index int +} + +func (c *context) handler() Handler { + if c.index < len(c.handlers) { + return c.handlers[c.index] + } + if c.index == len(c.handlers) { + return c.action + } + panic("invalid index for context handler") +} + +func (c *context) Next() { + c.index += 1 + c.run() +} + +func (c *context) Written() bool { + return c.rw.Written() +} + +func (c *context) run() { + for c.index <= len(c.handlers) { + _, err := c.Invoke(c.handler()) + if err != nil { + panic(err) + } + c.index += 1 + + if c.Written() { + return + } + } +} diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/martini_test.go b/Godeps/_workspace/src/github.com/go-martini/martini/martini_test.go new file mode 100644 index 0000000..f16bf3e --- /dev/null +++ b/Godeps/_workspace/src/github.com/go-martini/martini/martini_test.go @@ -0,0 +1,145 @@ +package martini + +import ( + "net/http" + "net/http/httptest" + "reflect" + "testing" +) + +/* Test Helpers */ +func expect(t *testing.T, a interface{}, b interface{}) { + if a != b { + t.Errorf("Expected %v (type %v) - Got %v (type %v)", b, reflect.TypeOf(b), a, reflect.TypeOf(a)) + } +} + +func refute(t *testing.T, a interface{}, b interface{}) { + if a == b { + t.Errorf("Did not expect %v (type %v) - Got %v (type %v)", b, reflect.TypeOf(b), a, reflect.TypeOf(a)) + } +} + +func Test_New(t *testing.T) { + m := New() + if m == nil { + t.Error("martini.New() cannot return nil") + } +} + +func Test_Martini_RunOnAddr(t *testing.T) { + // just test that Run doesn't bomb + go New().RunOnAddr("127.0.0.1:8080") +} + +func Test_Martini_Run(t *testing.T) { + go New().Run() +} + +func Test_Martini_ServeHTTP(t *testing.T) { + result := "" + response := httptest.NewRecorder() + + m := New() + m.Use(func(c Context) { + result += "foo" + c.Next() + result += "ban" + }) + m.Use(func(c Context) { + result += "bar" + c.Next() + result += "baz" + }) + m.Action(func(res http.ResponseWriter, req *http.Request) { + result += "bat" + res.WriteHeader(http.StatusBadRequest) + }) + + m.ServeHTTP(response, (*http.Request)(nil)) + + expect(t, result, "foobarbatbazban") + expect(t, response.Code, http.StatusBadRequest) +} + +func Test_Martini_Handlers(t *testing.T) { + result := "" + response := httptest.NewRecorder() + + batman := func(c Context) { + result += "batman!" + } + + m := New() + m.Use(func(c Context) { + result += "foo" + c.Next() + result += "ban" + }) + m.Handlers( + batman, + batman, + batman, + ) + m.Action(func(res http.ResponseWriter, req *http.Request) { + result += "bat" + res.WriteHeader(http.StatusBadRequest) + }) + + m.ServeHTTP(response, (*http.Request)(nil)) + + expect(t, result, "batman!batman!batman!bat") + expect(t, response.Code, http.StatusBadRequest) +} + +func Test_Martini_EarlyWrite(t *testing.T) { + result := "" + response := httptest.NewRecorder() + + m := New() + m.Use(func(res http.ResponseWriter) { + result += "foobar" + res.Write([]byte("Hello world")) + }) + m.Use(func() { + result += "bat" + }) + m.Action(func(res http.ResponseWriter) { + result += "baz" + res.WriteHeader(http.StatusBadRequest) + }) + + m.ServeHTTP(response, (*http.Request)(nil)) + + expect(t, result, "foobar") + expect(t, response.Code, http.StatusOK) +} + +func Test_Martini_Written(t *testing.T) { + response := httptest.NewRecorder() + + m := New() + m.Handlers(func(res http.ResponseWriter) { + res.WriteHeader(http.StatusOK) + }) + + ctx := m.createContext(response, (*http.Request)(nil)) + expect(t, ctx.Written(), false) + + ctx.run() + expect(t, ctx.Written(), true) +} + +func Test_Martini_Basic_NoRace(t *testing.T) { + m := New() + handlers := []Handler{func() {}, func() {}} + // Ensure append will not realloc to trigger the race condition + m.handlers = handlers[:1] + req, _ := http.NewRequest("GET", "/", nil) + for i := 0; i < 2; i++ { + go func() { + response := httptest.NewRecorder() + m.ServeHTTP(response, req) + }() + } +} diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/recovery.go b/Godeps/_workspace/src/github.com/go-martini/martini/recovery.go new file mode 100644 index 0000000..4d0ee3f --- /dev/null +++ b/Godeps/_workspace/src/github.com/go-martini/martini/recovery.go @@ -0,0 +1,144 @@ +package martini + +import ( + "bytes" + "fmt" + "io/ioutil" + "log" + "net/http" + "runtime" + + "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/codegangsta/inject" +) + +const ( + panicHtml = ` +PANIC: %s + + +

PANIC

+
%s
+
%s
+ +` +) + +var ( + dunno = []byte("???") + centerDot = []byte("·") + dot = []byte(".") + slash = []byte("/") +) + +// stack returns a nicely formated stack frame, skipping skip frames +func stack(skip int) []byte { + buf := new(bytes.Buffer) // the returned data + // As we loop, we open files and read them. These variables record the currently + // loaded file. + var lines [][]byte + var lastFile string + for i := skip; ; i++ { // Skip the expected number of frames + pc, file, line, ok := runtime.Caller(i) + if !ok { + break + } + // Print this much at least. If we can't find the source, it won't show. + fmt.Fprintf(buf, "%s:%d (0x%x)\n", file, line, pc) + if file != lastFile { + data, err := ioutil.ReadFile(file) + if err != nil { + continue + } + lines = bytes.Split(data, []byte{'\n'}) + lastFile = file + } + fmt.Fprintf(buf, "\t%s: %s\n", function(pc), source(lines, line)) + } + return buf.Bytes() +} + +// source returns a space-trimmed slice of the n'th line. +func source(lines [][]byte, n int) []byte { + n-- // in stack trace, lines are 1-indexed but our array is 0-indexed + if n < 0 || n >= len(lines) { + return dunno + } + return bytes.TrimSpace(lines[n]) +} + +// function returns, if possible, the name of the function containing the PC. +func function(pc uintptr) []byte { + fn := runtime.FuncForPC(pc) + if fn == nil { + return dunno + } + name := []byte(fn.Name()) + // The name includes the path name to the package, which is unnecessary + // since the file name is already included. Plus, it has center dots. + // That is, we see + // runtime/debug.*T·ptrmethod + // and want + // *T.ptrmethod + // Also the package path might contains dot (e.g. code.google.com/...), + // so first eliminate the path prefix + if lastslash := bytes.LastIndex(name, slash); lastslash >= 0 { + name = name[lastslash+1:] + } + if period := bytes.Index(name, dot); period >= 0 { + name = name[period+1:] + } + name = bytes.Replace(name, centerDot, dot, -1) + return name +} + +// Recovery returns a middleware that recovers from any panics and writes a 500 if there was one. +// While Martini is in development mode, Recovery will also output the panic as HTML. +func Recovery() Handler { + return func(c Context, log *log.Logger) { + defer func() { + if err := recover(); err != nil { + stack := stack(3) + log.Printf("PANIC: %s\n%s", err, stack) + + // Lookup the current responsewriter + val := c.Get(inject.InterfaceOf((*http.ResponseWriter)(nil))) + res := val.Interface().(http.ResponseWriter) + + // respond with panic message while in development mode + var body []byte + if Env == Dev { + res.Header().Set("Content-Type", "text/html") + body = []byte(fmt.Sprintf(panicHtml, err, err, stack)) + } else { + body = []byte("500 Internal Server Error") + } + + res.WriteHeader(http.StatusInternalServerError) + if nil != body { + res.Write(body) + } + } + }() + + c.Next() + } +} diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/recovery_test.go b/Godeps/_workspace/src/github.com/go-martini/martini/recovery_test.go new file mode 100644 index 0000000..17e2e01 --- /dev/null +++ b/Godeps/_workspace/src/github.com/go-martini/martini/recovery_test.go @@ -0,0 +1,49 @@ +package martini + +import ( + "bytes" + "log" + "net/http" + "net/http/httptest" + "testing" +) + +func Test_Recovery(t *testing.T) { + buff := bytes.NewBufferString("") + recorder := httptest.NewRecorder() + + setENV(Dev) + m := New() + // replace log for testing + m.Map(log.New(buff, "[martini] ", 0)) + m.Use(func(res http.ResponseWriter, req *http.Request) { + res.Header().Set("Content-Type", "unpredictable") + }) + m.Use(Recovery()) + m.Use(func(res http.ResponseWriter, req *http.Request) { + panic("here is a panic!") + }) + m.ServeHTTP(recorder, (*http.Request)(nil)) + expect(t, recorder.Code, http.StatusInternalServerError) + expect(t, recorder.HeaderMap.Get("Content-Type"), "text/html") + refute(t, recorder.Body.Len(), 0) + refute(t, len(buff.String()), 0) +} + +func Test_Recovery_ResponseWriter(t *testing.T) { + recorder := httptest.NewRecorder() + recorder2 := httptest.NewRecorder() + + setENV(Dev) + m := New() + m.Use(Recovery()) + m.Use(func(c Context) { + c.MapTo(recorder2, (*http.ResponseWriter)(nil)) + panic("here is a panic!") + }) + m.ServeHTTP(recorder, (*http.Request)(nil)) + + expect(t, recorder2.Code, http.StatusInternalServerError) + expect(t, recorder2.HeaderMap.Get("Content-Type"), "text/html") + refute(t, recorder2.Body.Len(), 0) +} diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/response_writer.go b/Godeps/_workspace/src/github.com/go-martini/martini/response_writer.go new file mode 100644 index 0000000..8bef0bc --- /dev/null +++ b/Godeps/_workspace/src/github.com/go-martini/martini/response_writer.go @@ -0,0 +1,98 @@ +package martini + +import ( + "bufio" + "fmt" + "net" + "net/http" +) + +// ResponseWriter is a wrapper around http.ResponseWriter that provides extra information about +// the response. It is recommended that middleware handlers use this construct to wrap a responsewriter +// if the functionality calls for it. +type ResponseWriter interface { + http.ResponseWriter + http.Flusher + http.Hijacker + // Status returns the status code of the response or 0 if the response has not been written. + Status() int + // Written returns whether or not the ResponseWriter has been written. + Written() bool + // Size returns the size of the response body. + Size() int + // Before allows for a function to be called before the ResponseWriter has been written to. This is + // useful for setting headers or any other operations that must happen before a response has been written. + Before(BeforeFunc) +} + +// BeforeFunc is a function that is called before the ResponseWriter has been written to. +type BeforeFunc func(ResponseWriter) + +// NewResponseWriter creates a ResponseWriter that wraps an http.ResponseWriter +func NewResponseWriter(rw http.ResponseWriter) ResponseWriter { + return &responseWriter{rw, 0, 0, nil} +} + +type responseWriter struct { + http.ResponseWriter + status int + size int + beforeFuncs []BeforeFunc +} + +func (rw *responseWriter) WriteHeader(s int) { + rw.callBefore() + rw.ResponseWriter.WriteHeader(s) + rw.status = s +} + +func (rw *responseWriter) Write(b []byte) (int, error) { + if !rw.Written() { + // The status will be StatusOK if WriteHeader has not been called yet + rw.WriteHeader(http.StatusOK) + } + size, err := rw.ResponseWriter.Write(b) + rw.size += size + return size, err +} + +func (rw *responseWriter) Status() int { + return rw.status +} + +func (rw *responseWriter) Size() int { + return rw.size +} + +func (rw *responseWriter) Written() bool { + return rw.status != 0 +} + +func (rw *responseWriter) Before(before BeforeFunc) { + rw.beforeFuncs = append(rw.beforeFuncs, before) +} + +func (rw *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { + hijacker, ok := rw.ResponseWriter.(http.Hijacker) + if !ok { + return nil, nil, fmt.Errorf("the ResponseWriter doesn't support the Hijacker interface") + } + return hijacker.Hijack() +} + +func (rw *responseWriter) CloseNotify() <-chan bool { + return rw.ResponseWriter.(http.CloseNotifier).CloseNotify() +} + +func (rw *responseWriter) callBefore() { + for i := len(rw.beforeFuncs) - 1; i >= 0; i-- { + rw.beforeFuncs[i](rw) + } +} + +func (rw *responseWriter) Flush() { + flusher, ok := rw.ResponseWriter.(http.Flusher) + if ok { + flusher.Flush() + } +} diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/response_writer_test.go b/Godeps/_workspace/src/github.com/go-martini/martini/response_writer_test.go new file mode 100644 index 0000000..6ccb9e0 --- /dev/null +++ b/Godeps/_workspace/src/github.com/go-martini/martini/response_writer_test.go @@ -0,0 +1,188 @@ +package martini + +import ( + "bufio" + "io" + "net" + "net/http" + "net/http/httptest" + "testing" + "time" +) + +type closeNotifyingRecorder struct { + *httptest.ResponseRecorder + closed chan bool +} + +func newCloseNotifyingRecorder() *closeNotifyingRecorder { + return &closeNotifyingRecorder{ + httptest.NewRecorder(), + make(chan bool, 1), + } +} + +func (c *closeNotifyingRecorder) close() { + c.closed <- true +} + +func (c *closeNotifyingRecorder) CloseNotify() <-chan bool { + return c.closed +} + +type hijackableResponse struct { + Hijacked bool +} + +func newHijackableResponse() *hijackableResponse { + return &hijackableResponse{} +} + +func (h *hijackableResponse) Header() http.Header { return nil } +func (h *hijackableResponse) Write(buf []byte) (int, error) { return 0, nil } +func (h *hijackableResponse) WriteHeader(code int) {} +func (h *hijackableResponse) Flush() {} +func (h *hijackableResponse) Hijack() (net.Conn, *bufio.ReadWriter, error) { + h.Hijacked = true + return nil, nil, nil +} + +func Test_ResponseWriter_WritingString(t *testing.T) { + rec := httptest.NewRecorder() + rw := NewResponseWriter(rec) + + rw.Write([]byte("Hello world")) + + expect(t, rec.Code, rw.Status()) + expect(t, rec.Body.String(), "Hello world") + expect(t, rw.Status(), http.StatusOK) + expect(t, rw.Size(), 11) + expect(t, rw.Written(), true) +} + +func Test_ResponseWriter_WritingStrings(t *testing.T) { + rec := httptest.NewRecorder() + rw := NewResponseWriter(rec) + + rw.Write([]byte("Hello world")) + rw.Write([]byte("foo bar bat baz")) + + expect(t, rec.Code, rw.Status()) + expect(t, rec.Body.String(), "Hello worldfoo bar bat baz") + expect(t, rw.Status(), http.StatusOK) + expect(t, rw.Size(), 26) +} + +func Test_ResponseWriter_WritingHeader(t *testing.T) { + rec := httptest.NewRecorder() + rw := NewResponseWriter(rec) + + rw.WriteHeader(http.StatusNotFound) + + expect(t, rec.Code, rw.Status()) + expect(t, rec.Body.String(), "") + expect(t, rw.Status(), http.StatusNotFound) + expect(t, rw.Size(), 0) +} + +func Test_ResponseWriter_Before(t *testing.T) { + rec := httptest.NewRecorder() + rw := NewResponseWriter(rec) + result := "" + + rw.Before(func(ResponseWriter) { + result += "foo" + }) + rw.Before(func(ResponseWriter) { + result += "bar" + }) + + rw.WriteHeader(http.StatusNotFound) + + expect(t, rec.Code, rw.Status()) + expect(t, rec.Body.String(), "") + expect(t, rw.Status(), http.StatusNotFound) + expect(t, rw.Size(), 0) + expect(t, result, "barfoo") +} + +func Test_ResponseWriter_Hijack(t *testing.T) { + hijackable := newHijackableResponse() + rw := NewResponseWriter(hijackable) + hijacker, ok := rw.(http.Hijacker) + expect(t, ok, true) + _, _, err := hijacker.Hijack() + if err != nil { + t.Error(err) + } + expect(t, hijackable.Hijacked, true) +} + +func Test_ResponseWrite_Hijack_NotOK(t *testing.T) { + hijackable := new(http.ResponseWriter) + rw := NewResponseWriter(*hijackable) + hijacker, ok := rw.(http.Hijacker) + expect(t, ok, true) + _, _, err := hijacker.Hijack() + + refute(t, err, nil) +} + +func Test_ResponseWriter_CloseNotify(t *testing.T) { + rec := newCloseNotifyingRecorder() + rw := NewResponseWriter(rec) + closed := false + notifier := rw.(http.CloseNotifier).CloseNotify() + rec.close() + select { + case <-notifier: + closed = true + case <-time.After(time.Second): + } + expect(t, closed, true) +} + +func Test_ResponseWriter_Flusher(t *testing.T) { + + rec := httptest.NewRecorder() + rw := NewResponseWriter(rec) + + _, ok := rw.(http.Flusher) + expect(t, ok, true) +} + +func Test_ResponseWriter_FlusherHandler(t *testing.T) { + + // New martini instance + m := Classic() + + m.Get("/events", func(w http.ResponseWriter, r *http.Request) { + + f, ok := w.(http.Flusher) + expect(t, ok, true) + + w.Header().Set("Content-Type", "text/event-stream") + w.Header().Set("Cache-Control", "no-cache") + w.Header().Set("Connection", "keep-alive") + + for i := 0; i < 2; i++ { + time.Sleep(10 * time.Millisecond) + io.WriteString(w, "data: Hello\n\n") + f.Flush() + } + + }) + + recorder := httptest.NewRecorder() + r, _ := http.NewRequest("GET", "/events", nil) + m.ServeHTTP(recorder, r) + + if recorder.Code != 200 { + t.Error("Response not 200") + } + + if recorder.Body.String() != "data: Hello\n\ndata: Hello\n\n" { + t.Error("Didn't receive correct body, got:", recorder.Body.String()) + } + +} diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/return_handler.go b/Godeps/_workspace/src/github.com/go-martini/martini/return_handler.go new file mode 100644 index 0000000..8301753 --- /dev/null +++ b/Godeps/_workspace/src/github.com/go-martini/martini/return_handler.go @@ -0,0 +1,43 @@ +package martini + +import ( + "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/codegangsta/inject" + "net/http" + "reflect" +) + +// ReturnHandler is a service that Martini provides that is called +// when a route handler returns something. The ReturnHandler is +// responsible for writing to the ResponseWriter based on the values +// that are passed into this function. +type ReturnHandler func(Context, []reflect.Value) + +func defaultReturnHandler() ReturnHandler { + return func(ctx Context, vals []reflect.Value) { + rv := ctx.Get(inject.InterfaceOf((*http.ResponseWriter)(nil))) + res := rv.Interface().(http.ResponseWriter) + var responseVal reflect.Value + if len(vals) > 1 && vals[0].Kind() == reflect.Int { + res.WriteHeader(int(vals[0].Int())) + responseVal = vals[1] + } else if len(vals) > 0 { + responseVal = vals[0] + } + if canDeref(responseVal) { + responseVal = responseVal.Elem() + } + if isByteSlice(responseVal) { + res.Write(responseVal.Bytes()) + } else { + res.Write([]byte(responseVal.String())) + } + } +} + +func isByteSlice(val reflect.Value) bool { + return val.Kind() == reflect.Slice && val.Type().Elem().Kind() == reflect.Uint8 +} + +func canDeref(val reflect.Value) bool { + return val.Kind() == reflect.Interface || val.Kind() == reflect.Ptr +} diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/router.go b/Godeps/_workspace/src/github.com/go-martini/martini/router.go new file mode 100644 index 0000000..d89ed8d --- /dev/null +++ b/Godeps/_workspace/src/github.com/go-martini/martini/router.go @@ -0,0 +1,390 @@ +package martini + +import ( + "fmt" + "net/http" + "reflect" + "regexp" + "strconv" + "sync" +) + +// Params is a map of name/value pairs for named routes. An instance of martini.Params is available to be injected into any route handler. +type Params map[string]string + +// Router is Martini's de-facto routing interface. Supports HTTP verbs, stacked handlers, and dependency injection. +type Router interface { + Routes + + // Group adds a group where related routes can be added. + Group(string, func(Router), ...Handler) + // Get adds a route for a HTTP GET request to the specified matching pattern. + Get(string, ...Handler) Route + // Patch adds a route for a HTTP PATCH request to the specified matching pattern. + Patch(string, ...Handler) Route + // Post adds a route for a HTTP POST request to the specified matching pattern. + Post(string, ...Handler) Route + // Put adds a route for a HTTP PUT request to the specified matching pattern. + Put(string, ...Handler) Route + // Delete adds a route for a HTTP DELETE request to the specified matching pattern. + Delete(string, ...Handler) Route + // Options adds a route for a HTTP OPTIONS request to the specified matching pattern. + Options(string, ...Handler) Route + // Head adds a route for a HTTP HEAD request to the specified matching pattern. + Head(string, ...Handler) Route + // Any adds a route for any HTTP method request to the specified matching pattern. + Any(string, ...Handler) Route + // AddRoute adds a route for a given HTTP method request to the specified matching pattern. + AddRoute(string, string, ...Handler) Route + + // NotFound sets the handlers that are called when a no route matches a request. Throws a basic 404 by default. + NotFound(...Handler) + + // Handle is the entry point for routing. This is used as a martini.Handler + Handle(http.ResponseWriter, *http.Request, Context) +} + +type router struct { + routes []*route + notFounds []Handler + groups []group + routesLock sync.RWMutex +} + +type group struct { + pattern string + handlers []Handler +} + +// NewRouter creates a new Router instance. +// If you aren't using ClassicMartini, then you can add Routes as a +// service with: +// +// m := martini.New() +// r := martini.NewRouter() +// m.MapTo(r, (*martini.Routes)(nil)) +// +// If you are using ClassicMartini, then this is done for you. +func NewRouter() Router { + return &router{notFounds: []Handler{http.NotFound}, groups: make([]group, 0)} +} + +func (r *router) Group(pattern string, fn func(Router), h ...Handler) { + r.groups = append(r.groups, group{pattern, h}) + fn(r) + r.groups = r.groups[:len(r.groups)-1] +} + +func (r *router) Get(pattern string, h ...Handler) Route { + return r.addRoute("GET", pattern, h) +} + +func (r *router) Patch(pattern string, h ...Handler) Route { + return r.addRoute("PATCH", pattern, h) +} + +func (r *router) Post(pattern string, h ...Handler) Route { + return r.addRoute("POST", pattern, h) +} + +func (r *router) Put(pattern string, h ...Handler) Route { + return r.addRoute("PUT", pattern, h) +} + +func (r *router) Delete(pattern string, h ...Handler) Route { + return r.addRoute("DELETE", pattern, h) +} + +func (r *router) Options(pattern string, h ...Handler) Route { + return r.addRoute("OPTIONS", pattern, h) +} + +func (r *router) Head(pattern string, h ...Handler) Route { + return r.addRoute("HEAD", pattern, h) +} + +func (r *router) Any(pattern string, h ...Handler) Route { + return r.addRoute("*", pattern, h) +} + +func (r *router) AddRoute(method, pattern string, h ...Handler) Route { + return r.addRoute(method, pattern, h) +} + +func (r *router) Handle(res http.ResponseWriter, req *http.Request, context Context) { + for _, route := range r.getRoutes() { + ok, vals := route.Match(req.Method, req.URL.Path) + if ok { + params := Params(vals) + context.Map(params) + route.Handle(context, res) + return + } + } + + // no routes exist, 404 + c := &routeContext{context, 0, r.notFounds} + context.MapTo(c, (*Context)(nil)) + c.run() +} + +func (r *router) NotFound(handler ...Handler) { + r.notFounds = handler +} + +func (r *router) addRoute(method string, pattern string, handlers []Handler) *route { + if len(r.groups) > 0 { + groupPattern := "" + h := make([]Handler, 0) + for _, g := range r.groups { + groupPattern += g.pattern + h = append(h, g.handlers...) + } + + pattern = groupPattern + pattern + h = append(h, handlers...) + handlers = h + } + + route := newRoute(method, pattern, handlers) + route.Validate() + r.appendRoute(route) + return route +} + +func (r *router) appendRoute(rt *route) { + r.routesLock.Lock() + defer r.routesLock.Unlock() + r.routes = append(r.routes, rt) +} + +func (r *router) getRoutes() []*route { + r.routesLock.RLock() + defer r.routesLock.RUnlock() + return r.routes[:] +} + +func (r *router) findRoute(name string) *route { + for _, route := range r.getRoutes() { + if route.name == name { + return route + } + } + + return nil +} + +// Route is an interface representing a Route in Martini's routing layer. +type Route interface { + // URLWith returns a rendering of the Route's url with the given string params. + URLWith([]string) string + // Name sets a name for the route. + Name(string) + // GetName returns the name of the route. + GetName() string + // Pattern returns the pattern of the route. + Pattern() string + // Method returns the method of the route. + Method() string +} + +type route struct { + method string + regex *regexp.Regexp + handlers []Handler + pattern string + name string +} + +var routeReg1 = regexp.MustCompile(`:[^/#?()\.\\]+`) +var routeReg2 = regexp.MustCompile(`\*\*`) + +func newRoute(method string, pattern string, handlers []Handler) *route { + route := route{method, nil, handlers, pattern, ""} + pattern = routeReg1.ReplaceAllStringFunc(pattern, func(m string) string { + return fmt.Sprintf(`(?P<%s>[^/#?]+)`, m[1:]) + }) + var index int + pattern = routeReg2.ReplaceAllStringFunc(pattern, func(m string) string { + index++ + return fmt.Sprintf(`(?P<_%d>[^#?]*)`, index) + }) + pattern += `\/?` + route.regex = regexp.MustCompile(pattern) + return &route +} + +func (r route) MatchMethod(method string) bool { + return r.method == "*" || method == r.method || (method == "HEAD" && r.method == "GET") +} + +func (r route) Match(method string, path string) (bool, map[string]string) { + // add Any method matching support + if !r.MatchMethod(method) { + return false, nil + } + + matches := r.regex.FindStringSubmatch(path) + if len(matches) > 0 && matches[0] == path { + params := make(map[string]string) + for i, name := range r.regex.SubexpNames() { + if len(name) > 0 { + params[name] = matches[i] + } + } + return true, params + } + return false, nil +} + +func (r *route) Validate() { + for _, handler := range r.handlers { + validateHandler(handler) + } +} + +func (r *route) Handle(c Context, res http.ResponseWriter) { + context := &routeContext{c, 0, r.handlers} + c.MapTo(context, (*Context)(nil)) + c.MapTo(r, (*Route)(nil)) + context.run() +} + +var urlReg = regexp.MustCompile(`:[^/#?()\.\\]+|\(\?P<[a-zA-Z0-9]+>.*\)`) + +// URLWith returns the url pattern replacing the parameters for its values +func (r *route) URLWith(args []string) string { + if len(args) > 0 { + argCount := len(args) + i := 0 + url := urlReg.ReplaceAllStringFunc(r.pattern, func(m string) string { + var val interface{} + if i < argCount { + val = args[i] + } else { + val = m + } + i += 1 + return fmt.Sprintf(`%v`, val) + }) + + return url + } + return r.pattern +} + +func (r *route) Name(name string) { + r.name = name +} + +func (r *route) GetName() string { + return r.name +} + +func (r *route) Pattern() string { + return r.pattern +} + +func (r *route) Method() string { + return r.method +} + +// Routes is a helper service for Martini's routing layer. +type Routes interface { + // URLFor returns a rendered URL for the given route. Optional params can be passed to fulfill named parameters in the route. + URLFor(name string, params ...interface{}) string + // MethodsFor returns an array of methods available for the path + MethodsFor(path string) []string + // All returns an array with all the routes in the router. + All() []Route +} + +// URLFor returns the url for the given route name. +func (r *router) URLFor(name string, params ...interface{}) string { + route := r.findRoute(name) + + if route == nil { + panic("route not found") + } + + var args []string + for _, param := range params { + switch v := param.(type) { + case int: + args = append(args, strconv.FormatInt(int64(v), 10)) + case string: + args = append(args, v) + default: + if v != nil { + panic("Arguments passed to URLFor must be integers or strings") + } + } + } + + return route.URLWith(args) +} + +func (r *router) All() []Route { + routes := r.getRoutes() + var ri = make([]Route, len(routes)) + + for i, route := range routes { + ri[i] = Route(route) + } + + return ri +} + +func hasMethod(methods []string, method string) bool { + for _, v := range methods { + if v == method { + return true + } + } + return false +} + +// MethodsFor returns all methods available for path +func (r *router) MethodsFor(path string) []string { + methods := []string{} + for _, route := range r.getRoutes() { + matches := route.regex.FindStringSubmatch(path) + if len(matches) > 0 && matches[0] == path && !hasMethod(methods, route.method) { + methods = append(methods, route.method) + } + } + return methods +} + +type routeContext struct { + Context + index int + handlers []Handler +} + +func (r *routeContext) Next() { + r.index += 1 + r.run() +} + +func (r *routeContext) run() { + for r.index < len(r.handlers) { + handler := r.handlers[r.index] + vals, err := r.Invoke(handler) + if err != nil { + panic(err) + } + r.index += 1 + + // if the handler returned something, write it to the http response + if len(vals) > 0 { + ev := r.Get(reflect.TypeOf(ReturnHandler(nil))) + handleReturn := ev.Interface().(ReturnHandler) + handleReturn(r, vals) + } + + if r.Written() { + return + } + } +} diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/router_test.go b/Godeps/_workspace/src/github.com/go-martini/martini/router_test.go new file mode 100644 index 0000000..eb80b7a --- /dev/null +++ b/Godeps/_workspace/src/github.com/go-martini/martini/router_test.go @@ -0,0 +1,468 @@ +package martini + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func Test_Routing(t *testing.T) { + router := NewRouter() + recorder := httptest.NewRecorder() + + req, _ := http.NewRequest("GET", "http://localhost:3000/foo", nil) + context := New().createContext(recorder, req) + + req2, _ := http.NewRequest("POST", "http://localhost:3000/bar/bat", nil) + context2 := New().createContext(recorder, req2) + + req3, _ := http.NewRequest("DELETE", "http://localhost:3000/baz", nil) + context3 := New().createContext(recorder, req3) + + req4, _ := http.NewRequest("PATCH", "http://localhost:3000/bar/foo", nil) + context4 := New().createContext(recorder, req4) + + req5, _ := http.NewRequest("GET", "http://localhost:3000/fez/this/should/match", nil) + context5 := New().createContext(recorder, req5) + + req6, _ := http.NewRequest("PUT", "http://localhost:3000/pop/blah/blah/blah/bap/foo/", nil) + context6 := New().createContext(recorder, req6) + + req7, _ := http.NewRequest("DELETE", "http://localhost:3000/wap//pow", nil) + context7 := New().createContext(recorder, req7) + + req8, _ := http.NewRequest("HEAD", "http://localhost:3000/wap//pow", nil) + context8 := New().createContext(recorder, req8) + + req9, _ := http.NewRequest("OPTIONS", "http://localhost:3000/opts", nil) + context9 := New().createContext(recorder, req9) + + req10, _ := http.NewRequest("HEAD", "http://localhost:3000/foo", nil) + context10 := New().createContext(recorder, req10) + + req11, _ := http.NewRequest("GET", "http://localhost:3000/bazz/inga", nil) + context11 := New().createContext(recorder, req11) + + req12, _ := http.NewRequest("POST", "http://localhost:3000/bazz/inga", nil) + context12 := New().createContext(recorder, req12) + + req13, _ := http.NewRequest("GET", "http://localhost:3000/bazz/in/ga", nil) + context13 := New().createContext(recorder, req13) + + req14, _ := http.NewRequest("GET", "http://localhost:3000/bzz", nil) + context14 := New().createContext(recorder, req14) + + result := "" + router.Get("/foo", func(req *http.Request) { + result += "foo" + }) + router.Patch("/bar/:id", func(params Params) { + expect(t, params["id"], "foo") + result += "barfoo" + }) + router.Post("/bar/:id", func(params Params) { + expect(t, params["id"], "bat") + result += "barbat" + }) + router.Put("/fizzbuzz", func() { + result += "fizzbuzz" + }) + router.Delete("/bazzer", func(c Context) { + result += "baz" + }) + router.Get("/fez/**", func(params Params) { + expect(t, params["_1"], "this/should/match") + result += "fez" + }) + router.Put("/pop/**/bap/:id/**", func(params Params) { + expect(t, params["id"], "foo") + expect(t, params["_1"], "blah/blah/blah") + expect(t, params["_2"], "") + result += "popbap" + }) + router.Delete("/wap/**/pow", func(params Params) { + expect(t, params["_1"], "") + result += "wappow" + }) + router.Options("/opts", func() { + result += "opts" + }) + router.Head("/wap/**/pow", func(params Params) { + expect(t, params["_1"], "") + result += "wappow" + }) + router.Group("/bazz", func(r Router) { + r.Get("/inga", func() { + result += "get" + }) + + r.Post("/inga", func() { + result += "post" + }) + + r.Group("/in", func(r Router) { + r.Get("/ga", func() { + result += "ception" + }) + }, func() { + result += "group" + }) + }, func() { + result += "bazz" + }, func() { + result += "inga" + }) + router.AddRoute("GET", "/bzz", func(c Context) { + result += "bzz" + }) + + router.Handle(recorder, req, context) + router.Handle(recorder, req2, context2) + router.Handle(recorder, req3, context3) + router.Handle(recorder, req4, context4) + router.Handle(recorder, req5, context5) + router.Handle(recorder, req6, context6) + router.Handle(recorder, req7, context7) + router.Handle(recorder, req8, context8) + router.Handle(recorder, req9, context9) + router.Handle(recorder, req10, context10) + router.Handle(recorder, req11, context11) + router.Handle(recorder, req12, context12) + router.Handle(recorder, req13, context13) + router.Handle(recorder, req14, context14) + expect(t, result, "foobarbatbarfoofezpopbapwappowwappowoptsfoobazzingagetbazzingapostbazzingagroupceptionbzz") + expect(t, recorder.Code, http.StatusNotFound) + expect(t, recorder.Body.String(), "404 page not found\n") +} + +func Test_RouterHandlerStatusCode(t *testing.T) { + router := NewRouter() + router.Get("/foo", func() string { + return "foo" + }) + router.Get("/bar", func() (int, string) { + return http.StatusForbidden, "bar" + }) + router.Get("/baz", func() (string, string) { + return "baz", "BAZ!" + }) + router.Get("/bytes", func() []byte { + return []byte("Bytes!") + }) + router.Get("/interface", func() interface{} { + return "Interface!" + }) + + // code should be 200 if none is returned from the handler + recorder := httptest.NewRecorder() + req, _ := http.NewRequest("GET", "http://localhost:3000/foo", nil) + context := New().createContext(recorder, req) + router.Handle(recorder, req, context) + expect(t, recorder.Code, http.StatusOK) + expect(t, recorder.Body.String(), "foo") + + // if a status code is returned, it should be used + recorder = httptest.NewRecorder() + req, _ = http.NewRequest("GET", "http://localhost:3000/bar", nil) + context = New().createContext(recorder, req) + router.Handle(recorder, req, context) + expect(t, recorder.Code, http.StatusForbidden) + expect(t, recorder.Body.String(), "bar") + + // shouldn't use the first returned value as a status code if not an integer + recorder = httptest.NewRecorder() + req, _ = http.NewRequest("GET", "http://localhost:3000/baz", nil) + context = New().createContext(recorder, req) + router.Handle(recorder, req, context) + expect(t, recorder.Code, http.StatusOK) + expect(t, recorder.Body.String(), "baz") + + // Should render bytes as a return value as well. + recorder = httptest.NewRecorder() + req, _ = http.NewRequest("GET", "http://localhost:3000/bytes", nil) + context = New().createContext(recorder, req) + router.Handle(recorder, req, context) + expect(t, recorder.Code, http.StatusOK) + expect(t, recorder.Body.String(), "Bytes!") + + // Should render interface{} values. + recorder = httptest.NewRecorder() + req, _ = http.NewRequest("GET", "http://localhost:3000/interface", nil) + context = New().createContext(recorder, req) + router.Handle(recorder, req, context) + expect(t, recorder.Code, http.StatusOK) + expect(t, recorder.Body.String(), "Interface!") +} + +func Test_RouterHandlerStacking(t *testing.T) { + router := NewRouter() + recorder := httptest.NewRecorder() + + req, _ := http.NewRequest("GET", "http://localhost:3000/foo", nil) + context := New().createContext(recorder, req) + + result := "" + + f1 := func() { + result += "foo" + } + + f2 := func(c Context) { + result += "bar" + c.Next() + result += "bing" + } + + f3 := func() string { + result += "bat" + return "Hello world" + } + + f4 := func() { + result += "baz" + } + + router.Get("/foo", f1, f2, f3, f4) + + router.Handle(recorder, req, context) + expect(t, result, "foobarbatbing") + expect(t, recorder.Body.String(), "Hello world") +} + +var routeTests = []struct { + // in + method string + path string + + // out + ok bool + params map[string]string +}{ + {"GET", "/foo/123/bat/321", true, map[string]string{"bar": "123", "baz": "321"}}, + {"POST", "/foo/123/bat/321", false, map[string]string{}}, + {"GET", "/foo/hello/bat/world", true, map[string]string{"bar": "hello", "baz": "world"}}, + {"GET", "foo/hello/bat/world", false, map[string]string{}}, + {"GET", "/foo/123/bat/321/", true, map[string]string{"bar": "123", "baz": "321"}}, + {"GET", "/foo/123/bat/321//", false, map[string]string{}}, + {"GET", "/foo/123//bat/321/", false, map[string]string{}}, +} + +func Test_RouteMatching(t *testing.T) { + route := newRoute("GET", "/foo/:bar/bat/:baz", nil) + for _, tt := range routeTests { + ok, params := route.Match(tt.method, tt.path) + if ok != tt.ok || params["bar"] != tt.params["bar"] || params["baz"] != tt.params["baz"] { + t.Errorf("expected: (%v, %v) got: (%v, %v)", tt.ok, tt.params, ok, params) + } + } +} + +func Test_MethodsFor(t *testing.T) { + router := NewRouter() + recorder := httptest.NewRecorder() + + req, _ := http.NewRequest("POST", "http://localhost:3000/foo", nil) + context := New().createContext(recorder, req) + context.MapTo(router, (*Routes)(nil)) + router.Post("/foo/bar", func() { + }) + + router.Post("/fo", func() { + }) + + router.Get("/foo", func() { + }) + + router.Put("/foo", func() { + }) + + router.NotFound(func(routes Routes, w http.ResponseWriter, r *http.Request) { + methods := routes.MethodsFor(r.URL.Path) + if len(methods) != 0 { + w.Header().Set("Allow", strings.Join(methods, ",")) + w.WriteHeader(http.StatusMethodNotAllowed) + } + }) + router.Handle(recorder, req, context) + expect(t, recorder.Code, http.StatusMethodNotAllowed) + expect(t, recorder.Header().Get("Allow"), "GET,PUT") +} + +func Test_NotFound(t *testing.T) { + router := NewRouter() + recorder := httptest.NewRecorder() + + req, _ := http.NewRequest("GET", "http://localhost:3000/foo", nil) + context := New().createContext(recorder, req) + + router.NotFound(func(res http.ResponseWriter) { + http.Error(res, "Nope", http.StatusNotFound) + }) + + router.Handle(recorder, req, context) + expect(t, recorder.Code, http.StatusNotFound) + expect(t, recorder.Body.String(), "Nope\n") +} + +func Test_NotFoundAsHandler(t *testing.T) { + router := NewRouter() + recorder := httptest.NewRecorder() + + req, _ := http.NewRequest("GET", "http://localhost:3000/foo", nil) + context := New().createContext(recorder, req) + + router.NotFound(func() string { + return "not found" + }) + + router.Handle(recorder, req, context) + expect(t, recorder.Code, http.StatusOK) + expect(t, recorder.Body.String(), "not found") + + recorder = httptest.NewRecorder() + + context = New().createContext(recorder, req) + + router.NotFound(func() (int, string) { + return 404, "not found" + }) + + router.Handle(recorder, req, context) + expect(t, recorder.Code, http.StatusNotFound) + expect(t, recorder.Body.String(), "not found") + + recorder = httptest.NewRecorder() + + context = New().createContext(recorder, req) + + router.NotFound(func() (int, string) { + return 200, "" + }) + + router.Handle(recorder, req, context) + expect(t, recorder.Code, http.StatusOK) + expect(t, recorder.Body.String(), "") +} + +func Test_NotFoundStacking(t *testing.T) { + router := NewRouter() + recorder := httptest.NewRecorder() + + req, _ := http.NewRequest("GET", "http://localhost:3000/foo", nil) + context := New().createContext(recorder, req) + + result := "" + + f1 := func() { + result += "foo" + } + + f2 := func(c Context) { + result += "bar" + c.Next() + result += "bing" + } + + f3 := func() string { + result += "bat" + return "Not Found" + } + + f4 := func() { + result += "baz" + } + + router.NotFound(f1, f2, f3, f4) + + router.Handle(recorder, req, context) + expect(t, result, "foobarbatbing") + expect(t, recorder.Body.String(), "Not Found") +} + +func Test_Any(t *testing.T) { + router := NewRouter() + router.Any("/foo", func(res http.ResponseWriter) { + http.Error(res, "Nope", http.StatusNotFound) + }) + + recorder := httptest.NewRecorder() + req, _ := http.NewRequest("GET", "http://localhost:3000/foo", nil) + context := New().createContext(recorder, req) + router.Handle(recorder, req, context) + + expect(t, recorder.Code, http.StatusNotFound) + expect(t, recorder.Body.String(), "Nope\n") + + recorder = httptest.NewRecorder() + req, _ = http.NewRequest("PUT", "http://localhost:3000/foo", nil) + context = New().createContext(recorder, req) + router.Handle(recorder, req, context) + + expect(t, recorder.Code, http.StatusNotFound) + expect(t, recorder.Body.String(), "Nope\n") +} + +func Test_URLFor(t *testing.T) { + router := NewRouter() + + router.Get("/foo", func() { + // Nothing + }).Name("foo") + + router.Post("/bar/:id", func(params Params) { + // Nothing + }).Name("bar") + + router.Get("/baz/:id/(?P[a-z]*)", func(params Params, routes Routes) { + // Nothing + }).Name("baz_id") + + router.Get("/bar/:id/:name", func(params Params, routes Routes) { + expect(t, routes.URLFor("foo", nil), "/foo") + expect(t, routes.URLFor("bar", 5), "/bar/5") + expect(t, routes.URLFor("baz_id", 5, "john"), "/baz/5/john") + expect(t, routes.URLFor("bar_id", 5, "john"), "/bar/5/john") + }).Name("bar_id") + + // code should be 200 if none is returned from the handler + recorder := httptest.NewRecorder() + req, _ := http.NewRequest("GET", "http://localhost:3000/bar/foo/bar", nil) + context := New().createContext(recorder, req) + context.MapTo(router, (*Routes)(nil)) + router.Handle(recorder, req, context) +} + +func Test_AllRoutes(t *testing.T) { + router := NewRouter() + + patterns := []string{"/foo", "/fee", "/fii"} + methods := []string{"GET", "POST", "DELETE"} + names := []string{"foo", "fee", "fii"} + + router.Get("/foo", func() {}).Name("foo") + router.Post("/fee", func() {}).Name("fee") + router.Delete("/fii", func() {}).Name("fii") + + for i, r := range router.All() { + expect(t, r.Pattern(), patterns[i]) + expect(t, r.Method(), methods[i]) + expect(t, r.GetName(), names[i]) + } +} + +func Test_ActiveRoute(t *testing.T) { + router := NewRouter() + + router.Get("/foo", func(r Route) { + expect(t, r.Pattern(), "/foo") + expect(t, r.GetName(), "foo") + }).Name("foo") + + // code should be 200 if none is returned from the handler + recorder := httptest.NewRecorder() + req, _ := http.NewRequest("GET", "http://localhost:3000/foo", nil) + context := New().createContext(recorder, req) + context.MapTo(router, (*Routes)(nil)) + router.Handle(recorder, req, context) +} diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/static.go b/Godeps/_workspace/src/github.com/go-martini/martini/static.go new file mode 100644 index 0000000..51af6cf --- /dev/null +++ b/Godeps/_workspace/src/github.com/go-martini/martini/static.go @@ -0,0 +1,135 @@ +package martini + +import ( + "log" + "net/http" + "net/url" + "path" + "path/filepath" + "strings" +) + +// StaticOptions is a struct for specifying configuration options for the martini.Static middleware. +type StaticOptions struct { + // Prefix is the optional prefix used to serve the static directory content + Prefix string + // SkipLogging will disable [Static] log messages when a static file is served. + SkipLogging bool + // IndexFile defines which file to serve as index if it exists. + IndexFile string + // Expires defines which user-defined function to use for producing a HTTP Expires Header + // https://developers.google.com/speed/docs/insights/LeverageBrowserCaching + Expires func() string + // Fallback defines a default URL to serve when the requested resource was + // not found. + Fallback string + // Exclude defines a pattern for URLs this handler should never process. + Exclude string +} + +func prepareStaticOptions(options []StaticOptions) StaticOptions { + var opt StaticOptions + if len(options) > 0 { + opt = options[0] + } + + // Defaults + if len(opt.IndexFile) == 0 { + opt.IndexFile = "index.html" + } + // Normalize the prefix if provided + if opt.Prefix != "" { + // Ensure we have a leading '/' + if opt.Prefix[0] != '/' { + opt.Prefix = "/" + opt.Prefix + } + // Remove any trailing '/' + opt.Prefix = strings.TrimRight(opt.Prefix, "/") + } + return opt +} + +// Static returns a middleware handler that serves static files in the given directory. +func Static(directory string, staticOpt ...StaticOptions) Handler { + if !filepath.IsAbs(directory) { + directory = filepath.Join(Root, directory) + } + dir := http.Dir(directory) + opt := prepareStaticOptions(staticOpt) + + return func(res http.ResponseWriter, req *http.Request, log *log.Logger) { + if req.Method != "GET" && req.Method != "HEAD" { + return + } + if opt.Exclude != "" && strings.HasPrefix(req.URL.Path, opt.Exclude) { + return + } + file := req.URL.Path + // if we have a prefix, filter requests by stripping the prefix + if opt.Prefix != "" { + if !strings.HasPrefix(file, opt.Prefix) { + return + } + file = file[len(opt.Prefix):] + if file != "" && file[0] != '/' { + return + } + } + f, err := dir.Open(file) + if err != nil { + // try any fallback before giving up + if opt.Fallback != "" { + file = opt.Fallback // so that logging stays true + f, err = dir.Open(opt.Fallback) + } + + if err != nil { + // discard the error? + return + } + } + defer f.Close() + + fi, err := f.Stat() + if err != nil { + return + } + + // try to serve index file + if fi.IsDir() { + // redirect if missing trailing slash + if !strings.HasSuffix(req.URL.Path, "/") { + dest := url.URL{ + Path: req.URL.Path + "/", + RawQuery: req.URL.RawQuery, + Fragment: req.URL.Fragment, + } + http.Redirect(res, req, dest.String(), http.StatusFound) + return + } + + file = path.Join(file, opt.IndexFile) + f, err = dir.Open(file) + if err != nil { + return + } + defer f.Close() + + fi, err = f.Stat() + if err != nil || fi.IsDir() { + return + } + } + + if !opt.SkipLogging { + log.Println("[Static] Serving " + file) + } + + // Add an Expires header to the static content + if opt.Expires != nil { + res.Header().Set("Expires", opt.Expires()) + } + + http.ServeContent(res, req, file, fi.ModTime(), f) + } +} diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/static_test.go b/Godeps/_workspace/src/github.com/go-martini/martini/static_test.go new file mode 100644 index 0000000..4d7613c --- /dev/null +++ b/Godeps/_workspace/src/github.com/go-martini/martini/static_test.go @@ -0,0 +1,254 @@ +package martini + +import ( + "bytes" + "io/ioutil" + "log" + "net/http" + "net/http/httptest" + "os" + "path" + "testing" + + "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/codegangsta/inject" +) + +var currentRoot, _ = os.Getwd() + +func Test_Static(t *testing.T) { + response := httptest.NewRecorder() + response.Body = new(bytes.Buffer) + + m := New() + r := NewRouter() + + m.Use(Static(currentRoot)) + m.Action(r.Handle) + + req, err := http.NewRequest("GET", "http://localhost:3000/martini.go", nil) + if err != nil { + t.Error(err) + } + m.ServeHTTP(response, req) + expect(t, response.Code, http.StatusOK) + expect(t, response.Header().Get("Expires"), "") + if response.Body.Len() == 0 { + t.Errorf("Got empty body for GET request") + } +} + +func Test_Static_Local_Path(t *testing.T) { + Root = os.TempDir() + response := httptest.NewRecorder() + response.Body = new(bytes.Buffer) + + m := New() + r := NewRouter() + + m.Use(Static(".")) + f, err := ioutil.TempFile(Root, "static_content") + if err != nil { + t.Error(err) + } + f.WriteString("Expected Content") + f.Close() + m.Action(r.Handle) + + req, err := http.NewRequest("GET", "http://localhost:3000/"+path.Base(f.Name()), nil) + if err != nil { + t.Error(err) + } + m.ServeHTTP(response, req) + expect(t, response.Code, http.StatusOK) + expect(t, response.Header().Get("Expires"), "") + expect(t, response.Body.String(), "Expected Content") +} + +func Test_Static_Head(t *testing.T) { + response := httptest.NewRecorder() + response.Body = new(bytes.Buffer) + + m := New() + r := NewRouter() + + m.Use(Static(currentRoot)) + m.Action(r.Handle) + + req, err := http.NewRequest("HEAD", "http://localhost:3000/martini.go", nil) + if err != nil { + t.Error(err) + } + + m.ServeHTTP(response, req) + expect(t, response.Code, http.StatusOK) + if response.Body.Len() != 0 { + t.Errorf("Got non-empty body for HEAD request") + } +} + +func Test_Static_As_Post(t *testing.T) { + response := httptest.NewRecorder() + + m := New() + r := NewRouter() + + m.Use(Static(currentRoot)) + m.Action(r.Handle) + + req, err := http.NewRequest("POST", "http://localhost:3000/martini.go", nil) + if err != nil { + t.Error(err) + } + + m.ServeHTTP(response, req) + expect(t, response.Code, http.StatusNotFound) +} + +func Test_Static_BadDir(t *testing.T) { + response := httptest.NewRecorder() + + m := Classic() + + req, err := http.NewRequest("GET", "http://localhost:3000/martini.go", nil) + if err != nil { + t.Error(err) + } + + m.ServeHTTP(response, req) + refute(t, response.Code, http.StatusOK) +} + +func Test_Static_Options_Logging(t *testing.T) { + response := httptest.NewRecorder() + + var buffer bytes.Buffer + m := &Martini{Injector: inject.New(), action: func() {}, logger: log.New(&buffer, "[martini] ", 0)} + m.Map(m.logger) + m.Map(defaultReturnHandler()) + + opt := StaticOptions{} + m.Use(Static(currentRoot, opt)) + + req, err := http.NewRequest("GET", "http://localhost:3000/martini.go", nil) + if err != nil { + t.Error(err) + } + + m.ServeHTTP(response, req) + expect(t, response.Code, http.StatusOK) + expect(t, buffer.String(), "[martini] [Static] Serving /martini.go\n") + + // Now without logging + m.Handlers() + buffer.Reset() + + // This should disable logging + opt.SkipLogging = true + m.Use(Static(currentRoot, opt)) + + m.ServeHTTP(response, req) + expect(t, response.Code, http.StatusOK) + expect(t, buffer.String(), "") +} + +func Test_Static_Options_ServeIndex(t *testing.T) { + response := httptest.NewRecorder() + + var buffer bytes.Buffer + m := &Martini{Injector: inject.New(), action: func() {}, logger: log.New(&buffer, "[martini] ", 0)} + m.Map(m.logger) + m.Map(defaultReturnHandler()) + + opt := StaticOptions{IndexFile: "martini.go"} // Define martini.go as index file + m.Use(Static(currentRoot, opt)) + + req, err := http.NewRequest("GET", "http://localhost:3000/", nil) + if err != nil { + t.Error(err) + } + + m.ServeHTTP(response, req) + expect(t, response.Code, http.StatusOK) + expect(t, buffer.String(), "[martini] [Static] Serving /martini.go\n") +} + +func Test_Static_Options_Prefix(t *testing.T) { + response := httptest.NewRecorder() + + var buffer bytes.Buffer + m := &Martini{Injector: inject.New(), action: func() {}, logger: log.New(&buffer, "[martini] ", 0)} + m.Map(m.logger) + m.Map(defaultReturnHandler()) + + // Serve current directory under /public + m.Use(Static(currentRoot, StaticOptions{Prefix: "/public"})) + + // Check file content behaviour + req, err := http.NewRequest("GET", "http://localhost:3000/public/martini.go", nil) + if err != nil { + t.Error(err) + } + + m.ServeHTTP(response, req) + expect(t, response.Code, http.StatusOK) + expect(t, buffer.String(), "[martini] [Static] Serving /martini.go\n") +} + +func Test_Static_Options_Expires(t *testing.T) { + response := httptest.NewRecorder() + + var buffer bytes.Buffer + m := &Martini{Injector: inject.New(), action: func() {}, logger: log.New(&buffer, "[martini] ", 0)} + m.Map(m.logger) + m.Map(defaultReturnHandler()) + + // Serve current directory under /public + m.Use(Static(currentRoot, StaticOptions{Expires: func() string { return "46" }})) + + // Check file content behaviour + req, err := http.NewRequest("GET", "http://localhost:3000/martini.go", nil) + if err != nil { + t.Error(err) + } + + m.ServeHTTP(response, req) + expect(t, response.Header().Get("Expires"), "46") +} + +func Test_Static_Options_Fallback(t *testing.T) { + response := httptest.NewRecorder() + + var buffer bytes.Buffer + m := &Martini{Injector: inject.New(), action: func() {}, logger: log.New(&buffer, "[martini] ", 0)} + m.Map(m.logger) + m.Map(defaultReturnHandler()) + + // Serve current directory under /public + m.Use(Static(currentRoot, StaticOptions{Fallback: "/martini.go"})) + + // Check file content behaviour + req, err := http.NewRequest("GET", "http://localhost:3000/initram.go", nil) + if err != nil { + t.Error(err) + } + + m.ServeHTTP(response, req) + expect(t, response.Code, http.StatusOK) + expect(t, buffer.String(), "[martini] [Static] Serving /martini.go\n") +} + +func Test_Static_Redirect(t *testing.T) { + response := httptest.NewRecorder() + + m := New() + m.Use(Static(currentRoot, StaticOptions{Prefix: "/public"})) + + req, err := http.NewRequest("GET", "http://localhost:3000/public?param=foo#bar", nil) + if err != nil { + t.Error(err) + } + + m.ServeHTTP(response, req) + expect(t, response.Code, http.StatusFound) + expect(t, response.Header().Get("Location"), "/public/?param=foo#bar") +} diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_de_DE.md b/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_de_DE.md new file mode 100644 index 0000000..7a6e6eb --- /dev/null +++ b/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_de_DE.md @@ -0,0 +1,369 @@ +# Martini [![wercker status](https://app.wercker.com/status/9b7dbc6e2654b604cd694d191c3d5487/s/master "wercker status")](https://app.wercker.com/project/bykey/9b7dbc6e2654b604cd694d191c3d5487)[![GoDoc](https://godoc.org/github.com/go-martini/martini?status.png)](http://godoc.org/github.com/go-martini/martini) + +Martini ist eine mächtiges Package zur schnellen Entwicklung von modularen Webanwendungen und -services in Golang. + +## Ein Projekt starten + +Nach der Installation von Go und dem Einrichten des [GOPATH](http://golang.org/doc/code.html#GOPATH), erstelle Deine erste `.go`-Datei. Speichere sie unter `server.go`. + +~~~ go +package main + +import "github.com/go-martini/martini" + +func main() { + m := martini.Classic() + m.Get("/", func() string { + return "Hallo Welt!" + }) + m.Run() +} +~~~ + +Installiere anschließend das Martini Package (**Go 1.1** oder höher wird vorausgesetzt): +~~~ +go get github.com/go-martini/martini +~~~ + +Starte den Server: +~~~ +go run server.go +~~~ + +Der Martini-Webserver ist nun unter `localhost:3000` erreichbar. + +## Hilfe + +Aboniere den [Emailverteiler](https://groups.google.com/forum/#!forum/martini-go) + +Schaue das [Demovideo](http://martini.codegangsta.io/#demo) + +Stelle Fragen auf Stackoverflow mit dem [Martini-Tag](http://stackoverflow.com/questions/tagged/martini) + +GoDoc [Dokumentation](http://godoc.org/github.com/go-martini/martini) + + +## Eigenschaften +* Sehr einfach nutzbar +* Nicht-intrusives Design +* Leicht kombinierbar mit anderen Golang Packages +* Ausgezeichnetes Path Matching und Routing +* Modulares Design - einfaches Hinzufügen und Entfernen von Funktionen +* Eine Vielzahl von guten Handlern/Middlewares nutzbar +* Großer Funktionsumfang mitgeliefert +* **Voll kompatibel mit dem [http.HandlerFunc](http://godoc.org/net/http#HandlerFunc) Interface.** +* Standardmäßges ausliefern von Dateien (z.B. von AngularJS-Apps im HTML5-Modus) + +## Mehr Middleware +Mehr Informationen zur Middleware und Funktionalität findest Du in den Repositories der [martini-contrib](https://github.com/martini-contrib) Gruppe. + +## Inhaltsverzeichnis +* [Classic Martini](#classic-martini) + * [Handler](#handler) + * [Routing](#routing) + * [Services](#services) + * [Statische Dateien bereitstellen](#statische-dateien-bereitstellen) +* [Middleware Handler](#middleware-handler) + * [Next()](#next) +* [Martini Env](#martini-env) +* [FAQ](#faq) + +## Classic Martini +Einen schnellen Start in ein Projekt ermöglicht [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic), dessen Voreinstellungen sich für die meisten Webanwendungen eignen: +~~~ go + m := martini.Classic() + // ... Middleware und Routing hier einfügen + m.Run() +~~~ + +Aufgelistet findest Du einige Aspekte, die [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) automatich berücksichtigt: + + * Request/Response Logging - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger) + * Panic Recovery - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery) + * Static File serving - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) + * Routing - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router) + +### Handler +Handler sind das Herz und die Seele von Martini. Ein Handler ist grundsätzlich jede Art von aufrufbaren Funktionen: +~~~ go +m.Get("/", func() { + println("Hallo Welt") +}) +~~~ + +#### Rückgabewerte +Wenn ein Handler Rückgabewerte beinhaltet, übergibt Martini diese an den aktuellen [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) in Form eines String: +~~~ go +m.Get("/", func() string { + return "Hallo Welt" // HTTP 200 : "Hallo Welt" +}) +~~~ + +Die Rückgabe eines Statuscode ist optional: +~~~ go +m.Get("/", func() (int, string) { + return 418, "Ich bin eine Teekanne" // HTTP 418 : "Ich bin eine Teekanne" +}) +~~~ + +#### Service Injection +Handler werden per Reflection aufgerufen. Martini macht Gebrauch von *Dependency Injection*, um Abhängigkeiten in der Argumentliste von Handlern aufzulösen. **Dies macht Martini komplett inkompatibel mit Golangs `http.HandlerFunc` Interface.** + +Fügst Du einem Handler ein Argument hinzu, sucht Martini in seiner Liste von Services und versucht, die Abhängigkeiten via Type Assertion aufzulösen. +~~~ go +m.Get("/", func(res http.ResponseWriter, req *http.Request) { // res und req wurden von Martini injiziert + res.WriteHeader(200) // HTTP 200 +}) +~~~ + +Die Folgenden Services sind Bestandteil von [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic): + + * [*log.Logger](http://godoc.org/log#Logger) - Globaler Logger für Martini. + * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http request context. + * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string` von benannten Parametern, welche durch Route Matching gefunden wurden. + * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Routen Hilfeservice. + * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http Response writer interface. + * [*http.Request](http://godoc.org/net/http/#Request) - http Request. + +### Routing +Eine Route ist in Martini eine HTTP-Methode gepaart mit einem URL-Matching-Pattern. Jede Route kann eine oder mehrere Handler-Methoden übernehmen: +~~~ go +m.Get("/", func() { + // zeige etwas an +}) + +m.Patch("/", func() { + // aktualisiere etwas +}) + +m.Post("/", func() { + // erstelle etwas +}) + +m.Put("/", func() { + // ersetzte etwas +}) + +m.Delete("/", func() { + // lösche etwas +}) + +m.Options("/", func() { + // HTTP Optionen +}) + +m.NotFound(func() { + // bearbeite 404-Fehler +}) +~~~ + +Routen werden in der Reihenfolge, in welcher sie definiert wurden, zugeordnet. Die bei einer Anfrage zuerst zugeordnete Route wird daraufhin aufgerufen. + +Routenmuster enhalten ggf. benannte Parameter, die über den [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) Service abrufbar sind: +~~~ go +m.Get("/hello/:name", func(params martini.Params) string { + return "Hallo " + params["name"] +}) +~~~ + +Routen können mit Globs versehen werden: +~~~ go +m.Get("/hello/**", func(params martini.Params) string { + return "Hallo " + params["_1"] +}) +~~~ + +Reguläre Ausdrücke sind ebenfalls möglich: +~~~go +m.Get("/hello/(?P[a-zA-Z]+)", func(params martini.Params) string { + return fmt.Sprintf ("Hallo %s", params["name"]) +}) +~~~ +Weitere Informationen zum Syntax regulärer Ausdrücke findest Du in der [Go Dokumentation](http://golang.org/pkg/regexp/syntax/). + +Routen-Handler können auch in einander verschachtelt werden. Dies ist bei der Authentifizierung und Berechtigungen nützlich. +~~~ go +m.Get("/secret", authorize, func() { + // wird ausgeführt, solange authorize nichts zurückgibt +}) +~~~ + +Routengruppen können durch die Group-Methode hinzugefügt werden. +~~~ go +m.Group("/books", func(r martini.Router) { + r.Get("/:id", GetBooks) + r.Post("/new", NewBook) + r.Put("/update/:id", UpdateBook) + r.Delete("/delete/:id", DeleteBook) +}) +~~~ + +Sowohl Handlern als auch Middlewares können Gruppen übergeben werden. +~~~ go +m.Group("/books", func(r martini.Router) { + r.Get("/:id", GetBooks) + r.Post("/new", NewBook) + r.Put("/update/:id", UpdateBook) + r.Delete("/delete/:id", DeleteBook) +}, MyMiddleware1, MyMiddleware2) +~~~ + +### Services +Services sind Okjekte, welche der Argumentliste von Handlern beigefügt werden können. +Du kannst einem Service der *Global* oder *Request* Ebene zuordnen. + +#### Global Mapping +Eine Martini-Instanz implementiert das inject.Injector Interface, sodass ein Service leicht zugeordnet werden kann: +~~~ go +db := &MyDatabase{} +m := martini.Classic() +m.Map(db) // der Service ist allen Handlern unter *MyDatabase verfügbar +// ... +m.Run() +~~~ + +#### Request-Level Mapping +Das Zuordnen auf der Request-Ebene kann in einem Handler via [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) realisiert werden: +~~~ go +func MyCustomLoggerHandler(c martini.Context, req *http.Request) { + logger := &MyCustomLogger{req} + c.Map(logger) // zugeordnet als *MyCustomLogger +} +~~~ + +#### Werten einem Interface zuordnen +Einer der mächtigsten Aspekte von Services ist dessen Fähigkeit, einen Service einem Interface zuzuordnen. Möchtest Du den [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) mit einem Decorator (Objekt) und dessen Zusatzfunktionen überschreiben, definiere den Handler wie folgt: +~~~ go +func WrapResponseWriter(res http.ResponseWriter, c martini.Context) { + rw := NewSpecialResponseWriter(res) + c.MapTo(rw, (*http.ResponseWriter)(nil)) // überschribe ResponseWriter mit dem ResponseWriter Decorator +} +~~~ + +### Statische Dateien bereitstellen +Eine [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) Instanz übertragt automatisch statische Dateien aus dem "public"-Ordner im Stammverzeichnis Deines Servers. Dieses Verhalten lässt sich durch weitere [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) Handler auf andere Verzeichnisse übertragen. +~~~ go +m.Use(martini.Static("assets")) // überträgt auch vom "assets"-Verzeichnis +~~~ + +#### Eine voreingestelle Datei übertragen +Du kannst die URL zu einer lokalen Datei angeben, sollte die URL einer Anfrage nicht gefunden werden. Durch einen Präfix können bestimmte URLs ignoriert werden. +Dies ist für Server nützlich, welche statische Dateien übertragen und ggf. zusätzliche Handler defineren (z.B. eine REST-API). Ist dies der Fall, so ist das Anlegen eines Handlers in der NotFound-Reihe nützlich. + +Das gezeigte Beispiel zeigt die `/index.html` immer an, wenn die angefrage URL keiner lokalen Datei zugeordnet werden kann bzw. wenn sie nicht mit `/api/v` beginnt: +~~~ go +static := martini.Static("assets", martini.StaticOptions{Fallback: "/index.html", Exclude: "/api/v"}) +m.NotFound(static, http.NotFound) +~~~ + +## Middleware Handler +Middleware-Handler befinden sich logisch zwischen einer Anfrage via HTTP und dem Router. Im wesentlichen unterscheiden sie sich nicht von anderen Handlern in Martini. +Du kannst einen Middleware-Handler dem Stack folgendermaßen anfügen: +~~~ go +m.Use(func() { + // durchlaufe die Middleware +}) +~~~ + +Volle Kontrolle über den Middleware Stack erlangst Du mit der `Handlers`-Funktion. +Sie ersetzt jeden zuvor definierten Handler: +~~~ go +m.Handlers( + Middleware1, + Middleware2, + Middleware3, +) +~~~ + +Middleware Handler arbeiten gut mit Aspekten wie Logging, Berechtigungen, Authentifizierung, Sessions, Komprimierung durch gzip, Fehlerseiten und anderen Operationen zusammen, die vor oder nach einer Anfrage passieren. +~~~ go +// überprüfe einen API-Schlüssel +m.Use(func(res http.ResponseWriter, req *http.Request) { + if req.Header.Get("X-API-KEY") != "secret123" { + res.WriteHeader(http.StatusUnauthorized) + } +}) +~~~ + +### Next() +[Context.Next()](http://godoc.org/github.com/go-martini/martini#Context) ist eine optionale Funktion, die Middleware-Handler aufrufen können, um sie nach dem Beenden der anderen Handler auszuführen. Dies funktioniert besonders gut, wenn Operationen nach einer HTTP-Anfrage ausgeführt werden müssen. +~~~ go +// protokolliere vor und nach einer Anfrage +m.Use(func(c martini.Context, log *log.Logger){ + log.Println("vor einer Anfrage") + + c.Next() + + log.Println("nach einer Anfrage") +}) +~~~ + +## Martini Env + +Einige Martini-Handler machen von der globalen `martini.Env` Variable gebrauch, die der Entwicklungsumgebung erweiterte Funktionen bietet, welche die Produktivumgebung nicht enthält. Es wird empfohlen, die `MARTINI_ENV=production` Umgebungsvariable zu setzen, sobald der Martini-Server in den Live-Betrieb übergeht. + +## FAQ + +### Wo finde ich eine bestimmte Middleware? + +Starte die Suche mit einem Blick in die Projekte von [martini-contrib](https://github.com/martini-contrib). Solltest Du nicht fündig werden, kontaktiere ein Mitglied des martini-contrib Teams, um eine neue Repository anzulegen. + +* [auth](https://github.com/martini-contrib/auth) - Handler zur Authentifizierung. +* [binding](https://github.com/martini-contrib/binding) - Handler zum Zuordnen/Validieren einer Anfrage zu einem Struct. +* [gzip](https://github.com/martini-contrib/gzip) - Handler zum Ermöglichen von gzip-Kompression bei Anfragen. +* [render](https://github.com/martini-contrib/render) - Handler der einen einfachen Service zum Rendern von JSON und HTML Templates bereitstellt. +* [acceptlang](https://github.com/martini-contrib/acceptlang) - Handler zum Parsen des `Accept-Language` HTTP-Header. +* [sessions](https://github.com/martini-contrib/sessions) - Handler mit einem Session service. +* [strip](https://github.com/martini-contrib/strip) - URL Prefix stripping. +* [method](https://github.com/martini-contrib/method) - Überschreibe eine HTTP-Method via Header oder Formularfelder. +* [secure](https://github.com/martini-contrib/secure) - Implementation von Sicherheitsfunktionen +* [encoder](https://github.com/martini-contrib/encoder) - Encoderservice zum Datenrendering in den verschiedensten Formaten. +* [cors](https://github.com/martini-contrib/cors) - Handler der CORS ermöglicht. +* [oauth2](https://github.com/martini-contrib/oauth2) - Handler der den Login mit OAuth 2.0 in Martinianwendungen ermöglicht. Google Sign-in, Facebook Connect und Github werden ebenfalls unterstützt. +* [vauth](https://github.com/rafecolton/vauth) - Handlers zur Webhook Authentifizierung (momentan nur GitHub und TravisCI) + +### Wie integriere ich in bestehende Systeme? + +Eine Martiniinstanz implementiert `http.Handler`, sodass Subrouten in bestehenden Servern einfach genutzt werden können. Hier ist eine funktionierende Martinianwendungen für die Google App Engine: + +~~~ go +package hello + +import ( + "net/http" + "github.com/go-martini/martini" +) + +func init() { + m := martini.Classic() + m.Get("/", func() string { + return "Hallo Welt!" + }) + http.Handle("/", m) +} +~~~ + +### Wie ändere ich den Port/Host? + +Martinis `Run` Funktion sucht automatisch nach den PORT und HOST Umgebungsvariablen, um diese zu nutzen. Andernfalls ist localhost:3000 voreingestellt. +Für mehr Flexibilität über den Port und den Host nutze stattdessen die `martini.RunOnAddr` Funktion. + +~~~ go + m := martini.Classic() + // ... + log.Fatal(m.RunOnAddr(":8080")) +~~~ + +### Automatisches Aktualisieren? + +[Gin](https://github.com/codegangsta/gin) und [Fresh](https://github.com/pilu/fresh) aktualisieren Martini-Apps live. + +## Bei Martini mitwirken + +Martinis Maxime ist Minimalismus und sauberer Code. Die meisten Beiträge sollten sich in den Repositories der [martini-contrib](https://github.com/martini-contrib) Gruppe wiederfinden. Beinhaltet Dein Beitrag Veränderungen am Kern von Martini, zögere nicht, einen Pull Request zu machen. + +## Über das Projekt + +Inspiriert von [Express](https://github.com/visionmedia/express) und [Sinatra](https://github.com/sinatra/sinatra) + +Martini wird leidenschaftlich von Niemand gerigeren als dem [Code Gangsta](http://codegangsta.io/) entwickelt diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_es_ES.md b/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_es_ES.md new file mode 100644 index 0000000..3a76a66 --- /dev/null +++ b/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_es_ES.md @@ -0,0 +1,353 @@ +# Martini [![wercker status](https://app.wercker.com/status/9b7dbc6e2654b604cd694d191c3d5487/s/master "wercker status")](https://app.wercker.com/project/bykey/9b7dbc6e2654b604cd694d191c3d5487)[![GoDoc](https://godoc.org/github.com/go-martini/martini?status.png)](http://godoc.org/github.com/go-martini/martini) + +Martini es un poderoso paquete para escribir rápidamente aplicaciones/servicios web modulares en Golang. + + +## Vamos a iniciar + +Antes de instalar Go y de configurar su [GOPATH](http://golang.org/doc/code.html#GOPATH), cree su primer archivo `.go`. Vamos a llamar a este `server.go`. + +~~~ go +package main + +import "github.com/go-martini/martini" + +func main() { + m := martini.Classic() + m.Get("/", func() string { + return "Hola Mundo!" + }) + m.Run() +} +~~~ + +Luego instale el paquete Martini (Es necesario **go 1.1** o superior): +~~~ +go get github.com/go-martini/martini +~~~ + +Después corra su servidor: +~~~ +go run server.go +~~~ + +Ahora tendrá un webserver Martini corriendo en el puerto `localhost:3000`. + +## Obtenga ayuda + +Suscribase a la [Lista de email](https://groups.google.com/forum/#!forum/martini-go) + +Observe el [Video demostrativo](http://martini.codegangsta.io/#demo) + +Use la etiqueta [martini](http://stackoverflow.com/questions/tagged/martini) para preguntas en Stackoverflow + +GoDoc [documentation](http://godoc.org/github.com/go-martini/martini) + + +## Caracteríticas +* Extremadamente simple de usar. +* Diseño no intrusivo. +* Buena integración con otros paquetes Golang. +* Enrutamiento impresionante. +* Diseño modular - Fácil de añadir y remover funcionalidades. +* Muy buen uso de handlers/middlewares. +* Grandes características innovadoras. +* **Compatibilidad total con la interface [http.HandlerFunc](http://godoc.org/net/http#HandlerFunc).** + +## Más Middlewares +Para más middlewares y funcionalidades, revisar los repositorios en [martini-contrib](https://github.com/martini-contrib). + +## Lista de contenidos +* [Classic Martini](#classic-martini) + * [Handlers](#handlers) + * [Routing](#routing) + * [Services](#services) + * [Serving Static Files](#serving-static-files) +* [Middleware Handlers](#middleware-handlers) + * [Next()](#next) +* [Martini Env](#martini-env) +* [FAQ](#faq) + +## Classic Martini +Para iniciar rápidamente, [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) prevee algunas herramientas que funcionan bien para la mayoría de aplicaciones web: +~~~ go + m := martini.Classic() + // middlewares y rutas aquí + m.Run() +~~~ + +Algunas funcionalidades que [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) ofrece automáticamente son: + * Request/Response Logging - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger) + * Panic Recovery - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery) + * Static File serving - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) + * Routing - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router) + +### Handlers +Handlers son el corazón y el alma de Martini. Un handler es básicamente cualquier tipo de función que puede ser llamada. +~~~ go +m.Get("/", func() { + println("hola mundo") +}) +~~~ + +#### Retorno de Valores +Si un handler retorna cualquier cosa, Martini escribirá el valor retornado como una cadena [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter): +~~~ go +m.Get("/", func() string { + return "hola mundo" // HTTP 200 : "hola mundo" +}) +~~~ + +Usted también puede retornar un código de estado: +~~~ go +m.Get("/", func() (int, string) { + return 418, "soy una tetera" // HTTP 418 : "soy una tetera" +}) +~~~ + +#### Inyección de Servicios +Handlers son invocados vía reflexión. Martini utiliza *Inyección de Dependencia* para resolver dependencias en la lista de argumentos Handlers. **Esto hace que Martini sea completamente compatible con la interface `http.HandlerFunc` de golang.** + +Si agrega un argumento a su Handler, Martini buscará en su lista de servicios e intentará resolver su dependencia vía su tipo de aserción: +~~~ go +m.Get("/", func(res http.ResponseWriter, req *http.Request) { // res e req son inyectados por Martini + res.WriteHeader(200) // HTTP 200 +}) +~~~ + +Los siguientes servicios son incluidos con [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic): + * [*log.Logger](http://godoc.org/log#Logger) - Log Global para Martini. + * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http request context. + * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string` de nombres de los parámetros buscados por la ruta. + * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Servicio de ayuda para las Rutas. + * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http Response escribe la interfaz. + * [*http.Request](http://godoc.org/net/http/#Request) - http Request. + +### Rutas +En Martini, una ruta es un método HTTP emparejado con un patrón URL. Cada ruta puede tener uno o más métodos handler: +~~~ go +m.Get("/", func() { + // mostrar algo +}) + +m.Patch("/", func() { + // actualizar algo +}) + +m.Post("/", func() { + // crear algo +}) + +m.Put("/", func() { + // reemplazar algo +}) + +m.Delete("/", func() { + // destruir algo +}) + +m.Options("/", func() { + // opciones HTTP +}) + +m.NotFound(func() { + // manipula 404 +}) +~~~ + +Las rutas son emparejadas en el orden en que son definidas. La primera ruta que coincide con la solicitud es invocada. + +Los patrones de rutas puede incluir nombres como parámetros accesibles vía el servicio [martini.Params](http://godoc.org/github.com/go-martini/martini#Params): +~~~ go +m.Get("/hello/:name", func(params martini.Params) string { + return "Hello " + params["name"] +}) +~~~ + +Las rutas se pueden combinar con globs: +~~~ go +m.Get("/hello/**", func(params martini.Params) string { + return "Hello " + params["_1"] +}) +~~~ + +Las expresiones regulares puede ser usadas también: +~~~go +m.Get("/hello/(?P[a-zA-Z]+)", func(params martini.Params) string { + return fmt.Sprintf ("Hello %s", params["name"]) +}) +~~~ +Observe la [documentación](http://golang.org/pkg/regexp/syntax/) para mayor información sobre la sintaxis de expresiones regulares. + + +Handlers de ruta pueden ser empilados en la cima de otros, la cual es útil para cosas como autenticación y autorización: +~~~ go +m.Get("/secret", authorize, func() { + // será ejecutado cuando autorice escribir una respuesta +}) +~~~ + +Grupos de rutas puede ser añadidas usando el método Group. +~~~ go +m.Group("/books", func(r martini.Router) { + r.Get("/:id", GetBooks) + r.Post("/new", NewBook) + r.Put("/update/:id", UpdateBook) + r.Delete("/delete/:id", DeleteBook) +}) +~~~ + +Igualmente como puede pasar middlewares para un handler, usted puede pasar middlewares para grupos. +~~~ go +m.Group("/books", func(r martini.Router) { + r.Get("/:id", GetBooks) + r.Post("/new", NewBook) + r.Put("/update/:id", UpdateBook) + r.Delete("/delete/:id", DeleteBook) +}, MyMiddleware1, MyMiddleware2) +~~~ + +### Servicios +Servicios son objetos que están disponibles para ser inyectados en una lista de argumentos Handler. Usted puede mapear un servicios a nivel *Global* o *Request*. + +#### Mapeamento Global +Una instancia de Martini implementa la interface inject.Injector, entonces un mapeamiento de un servicio es fácil: +~~~ go +db := &MyDatabase{} +m := martini.Classic() +m.Map(db) // el servicio estará disponible para todos los handlers como *MyDatabase. +// ... +m.Run() +~~~ + +#### Mapeamiento por Request +Mapeamiento a nivel de request se puede realizar un handler vía [martini.Context](http://godoc.org/github.com/go-martini/martini#Context): +~~~ go +func MyCustomLoggerHandler(c martini.Context, req *http.Request) { + logger := &MyCustomLogger{req} + c.Map(logger) // mapeado como *MyCustomLogger +} +~~~ + +#### Valores de Mapeamiento para Interfaces +Una de las partes mas poderosas sobre servicios es la capadidad de mapear un servicio para una interface. Por ejemplo, si desea sobreescribir [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) con un objeto que envuelva y realice operaciones extra, puede escribir el siguiente handler: +~~~ go +func WrapResponseWriter(res http.ResponseWriter, c martini.Context) { + rw := NewSpecialResponseWriter(res) + c.MapTo(rw, (*http.ResponseWriter)(nil)) // sobreescribir ResponseWriter con nuestro ResponseWriter +} +~~~ + +### Sirviendo Archivos Estáticos +Una instancia de [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) sirve automáticamente archivos estáticos del directorio "public" en la raíz de su servidor. +Usted puede servir más directorios, añadiendo más [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) handlers. +~~~ go +m.Use(martini.Static("assets")) // sirviendo los archivos del directorio "assets" +~~~ + +## Middleware Handlers +Middleware Handlers se sitúan entre una solicitud HTTP y un router. En esencia, ellos no son diferentes de cualquier otro Handler en Martini. Usted puede añadir un handler de middleware para la pila de la siguiente forma: +~~~ go +m.Use(func() { + // Hacer algo con middleware +}) +~~~ + +Puede tener el control total sobre la pila de middleware con la función `Handlers`. Esto reemplazará a cualquier handler que se ha establecido previamente: +~~~ go +m.Handlers( + Middleware1, + Middleware2, + Middleware3, +) +~~~ + +Middleware Handlers trabaja realmente bien como logging, autorización, autenticación, sessión, gzipping, páginas de errores y una serie de otras operaciones que deben suceder antes de una solicitud http: +~~~ go +// Valida una llave de api +m.Use(func(res http.ResponseWriter, req *http.Request) { + if req.Header.Get("X-API-KEY") != "secret123" { + res.WriteHeader(http.StatusUnauthorized) + } +}) +~~~ + +### Next() +[Context.Next()](http://godoc.org/github.com/go-martini/martini#Context) es una función opcional que Middleware Handlers puede llamar para aguardar una ejecución de otros Handlers. Esto trabaja muy bien para calquier operación que debe suceder antes de una solicitud http: +~~~ go +// log antes y después de una solicitud +m.Use(func(c martini.Context, log *log.Logger){ + log.Println("antes de una solicitud") + + c.Next() + + log.Println("luego de una solicitud") +}) +~~~ + +## Martini Env + +Martini handlers hace uso de `martini.Env`, una variable global para proveer funcionalidad especial en ambientes de desarrollo y ambientes de producción. Es recomendado que una variable `MARTINI_ENV=production` sea definida cuando se despliegue en un ambiente de producción. + +## FAQ + +### ¿Dónde puedo encontrar una middleware X? + +Inicie su búsqueda en los proyectos [martini-contrib](https://github.com/martini-contrib). Si no esta allí, no dude en contactar a algún miembro del equipo martini-contrib para adicionar un nuevo repositorio para la organización. + +* [auth](https://github.com/martini-contrib/auth) - Handlers para autenticación. +* [binding](https://github.com/martini-contrib/binding) - Handler para mapeamiento/validación de un request en una estrutura. +* [gzip](https://github.com/martini-contrib/gzip) - Handler para agregar gzip comprimidos para requests +* [render](https://github.com/martini-contrib/render) - Handler que provee un servicio de fácil renderizado JSON y plantillas HTML. +* [acceptlang](https://github.com/martini-contrib/acceptlang) - Handler para analizar `Accept-Language` header HTTP. +* [sessions](https://github.com/martini-contrib/sessions) - Handler que provee un servicio de sesión. +* [strip](https://github.com/martini-contrib/strip) - URL Prefix stripping. +* [method](https://github.com/martini-contrib/method) - HTTP método de sobreescritura vía header o campos de formulario. +* [secure](https://github.com/martini-contrib/secure) - Implementa rápidamente items de seguridad. +* [encoder](https://github.com/martini-contrib/encoder) - Servicio de encoder para renderización de datos en varios formatos y negocios de contenidos. +* [cors](https://github.com/martini-contrib/cors) - Handler que habilita suporte a CORS. +* [oauth2](https://github.com/martini-contrib/oauth2) - Handler que provee sistema de login OAuth 2.0 para aplicaciones Martini. Google Sign-in, Facebook Connect y Github login son soportados. + +### ¿Cómo se integra con los servidores existentes? + +Una instancia de Martini implementa `http.Handler`, de modo que puede ser fácilmente utilizado para servir sub-rutas y directorios en servidores Go existentes. Por ejemplo, este es un aplicativo Martini trabajando para Google App Engine: + +~~~ go +package hello + +import ( + "net/http" + "github.com/go-martini/martini" +) + +func init() { + m := martini.Classic() + m.Get("/", func() string { + return "Hola Mundo!" + }) + http.Handle("/", m) +} +~~~ + +### ¿Cómo cambiar el puerto/host? + +La función `Run` de Martini observa las variables PORT e HOST para utilizarlas. Caso contrário, Martini asume por defecto localhost:3000. Para tener maayor flexibilidad sobre el puerto y host, use la función `martini.RunOnAddr`. + +~~~ go + m := martini.Classic() + // ... + log.Fatal(m.RunOnAddr(":8080")) +~~~ + +### ¿Servidor con autoreload? + +[gin](https://github.com/codegangsta/gin) y [fresh](https://github.com/pilu/fresh) son aplicaciones para autorecarga de Martini. + +## Contribuyendo +Martini se desea mantener pequeño y limpio. La mayoría de contribuciones deben realizarse en el repositorio [martini-contrib](https://github.com/martini-contrib). Si desea hacer una contribución al core de Martini es libre de realizar un Pull Request. + +## Sobre + +Inspirado por [express](https://github.com/visionmedia/express) y [sinatra](https://github.com/sinatra/sinatra) + +Martini está diseñoado obsesivamente por nada menos que [Code Gangsta](http://codegangsta.io/) diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_fr_FR.md b/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_fr_FR.md new file mode 100644 index 0000000..8381bf2 --- /dev/null +++ b/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_fr_FR.md @@ -0,0 +1,344 @@ +# Martini [![wercker status](https://app.wercker.com/status/9b7dbc6e2654b604cd694d191c3d5487/s/master "wercker status")](https://app.wercker.com/project/bykey/9b7dbc6e2654b604cd694d191c3d5487)[![GoDoc](https://godoc.org/github.com/go-martini/martini?status.png)](http://godoc.org/github.com/go-martini/martini) + +Martini est une puissante bibliothèque pour développer rapidement des applications et services web en Golang. + + +## Pour commencer + +Après avoir installé Go et configuré le chemin d'accès pour [GOPATH](http://golang.org/doc/code.html#GOPATH), créez votre premier fichier '.go'. Nous l'appellerons 'server.go'. + +~~~ go +package main + +import "github.com/go-martini/martini" + +func main() { + m := martini.Classic() + m.Get("/", func() string { + return "Hello world!" + }) + m.Run() +} +~~~ + +Installez ensuite le paquet Martini (**go 1.1** ou supérieur est requis) : + +~~~ +go get github.com/go-martini/martini +~~~ + +La commande suivante vous permettra de lancer votre serveur : +~~~ +go run server.go +~~~ + +Vous avez à présent un serveur web Martini à l'écoute sur l'adresse et le port suivants : `localhost:3000`. + +## Besoin d'aide +- Souscrivez à la [Liste d'emails](https://groups.google.com/forum/#!forum/martini-go) +- Regardez les vidéos [Demo en vidéo](http://martini.codegangsta.io/#demo) +- Posez vos questions sur StackOverflow.com en utilisant le tag [martini](http://stackoverflow.com/questions/tagged/martini) +- La documentation GoDoc [documentation](http://godoc.org/github.com/go-martini/martini) + + +## Caractéristiques +* Simple d'utilisation +* Design non-intrusif +* Compatible avec les autres paquets Golang +* Gestionnaire d'URL et routeur disponibles +* Modulable, permettant l'ajout et le retrait de fonctionnalités +* Un grand nombre de handlers/middlewares disponibles +* Prêt pour une utilisation immédiate +* **Entièrement compatible avec l'interface [http.HandlerFunc](http://godoc.org/net/http#HandlerFunc).** + +## Plus de Middleware +Pour plus de middlewares et de fonctionnalités, consultez le dépôt [martini-contrib](https://github.com/martini-contrib). + +## Table des matières +* [Classic Martini](#classic-martini) + * [Handlers](#handlers) + * [Routage](#routing) + * [Services](#services) + * [Serveur de fichiers statiques](#serving-static-files) +* [Middleware Handlers](#middleware-handlers) + * [Next()](#next) +* [Martini Env](#martini-env) +* [FAQ](#faq) + +## Classic Martini +Pour vous faire gagner un temps précieux, [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) est configuré avec des paramètres qui devraient couvrir les besoins de la plupart des applications web : + +~~~ go + m := martini.Classic() + // ... les middlewares and le routage sont insérés ici... + m.Run() +~~~ + +Voici quelques handlers/middlewares que [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) intègre par défault : + * Logging des requêtes/réponses - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger) + * Récupération sur erreur - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery) + * Serveur de fichiers statiques - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) + * Routage - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router) + +### Handlers +Les Handlers sont le coeur et l'âme de Martini. N'importe quelle fonction peut être utilisée comme un handler. +~~~ go +m.Get("/", func() { + println("hello world") +}) +~~~ + +#### Valeurs retournées +Si un handler retourne une valeur, Martini écrira le résultat dans l'instance [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) courante sous forme de ```string```: +~~~ go +m.Get("/", func() string { + return "hello world" // HTTP 200 : "hello world" +}) +~~~ +Vous pouvez aussi optionnellement renvoyer un code de statut HTTP : +~~~ go +m.Get("/", func() (int, string) { + return 418, "i'm a teapot" // HTTP 418 : "i'm a teapot" +}) +~~~ + +#### Injection de services +Les handlers sont appelés via réflexion. Martini utilise "l'injection par dépendance" pour résoudre les dépendances des handlers dans la liste d'arguments. **Cela permet à Martini d'être parfaitement compatible avec l'interface golang ```http.HandlerFunc```.** + +Si vous ajoutez un argument à votre Handler, Martini parcourera la liste des services et essayera de déterminer ses dépendances selon son type : +~~~ go +m.Get("/", func(res http.ResponseWriter, req *http.Request) { // res and req are injected by Martini + res.WriteHeader(200) // HTTP 200 +}) +~~~ +Les services suivants sont inclus avec [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic): + * [log.Logger](http://godoc.org/log#Logger) - Global logger for Martini. + * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - Contexte d'une requête HTTP. + * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string` contenant les paramètres retrouvés par correspondance des routes. + * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Service d'aide au routage. + * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - Interface d'écriture de réponses HTTP. + * [*http.Request](http://godoc.org/net/http/#Request) - Requête HTTP. + +### Routeur +Dans Martini, un chemin est une méthode HTTP liée à un modèle d'adresse URL. +Chaque chemin peut avoir un seul ou plusieurs méthodes *handler* : +~~~ go +m.Get("/", func() { + // show something +}) + +m.Patch("/", func() { + // update something +}) + +m.Post("/", func() { + // create something +}) + +m.Put("/", func() { + // replace something +}) + +m.Delete("/", func() { + // destroy something +}) + +m.Options("/", func() { + // http options +}) + +m.NotFound(func() { + // handle 404 +}) +~~~ +Les chemins seront traités dans l'ordre dans lequel ils auront été définis. Le *handler* du premier chemin trouvé qui correspondra à la requête sera invoqué. + + +Les chemins peuvent inclure des paramètres nommés, accessibles avec le service [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) : +~~~ go +m.Get("/hello/:name", func(params martini.Params) string { + return "Hello " + params["name"] +}) +~~~ + +Les chemins peuvent correspondre à des globs : +~~~ go +m.Get("/hello/**", func(params martini.Params) string { + return "Hello " + params["_1"] +}) +~~~ +Les expressions régulières peuvent aussi être utilisées : +~~~go +m.Get("/hello/(?P[a-zA-Z]+)", func(params martini.Params) string { + return fmt.Sprintf ("Hello %s", params["name"]) +}) +~~~ +Jetez un oeil à la documentation [Go documentation](http://golang.org/pkg/regexp/syntax/) pour plus d'informations sur la syntaxe des expressions régulières. + +Les handlers d'un chemins peuvent être superposés, ce qui s'avère particulièrement pratique pour des tâches comme la gestion de l'authentification et des autorisations : +~~~ go +m.Get("/secret", authorize, func() { + // this will execute as long as authorize doesn't write a response +}) +~~~ + +Un groupe de chemins peut aussi être ajouté en utilisant la méthode ```Group``` : +~~~ go +m.Group("/books", func(r martini.Router) { + r.Get("/:id", GetBooks) + r.Post("/new", NewBook) + r.Put("/update/:id", UpdateBook) + r.Delete("/delete/:id", DeleteBook) +}) +~~~ + +Comme vous pouvez passer des middlewares à un handler, vous pouvez également passer des middlewares à des groupes : +~~~ go +m.Group("/books", func(r martini.Router) { + r.Get("/:id", GetBooks) + r.Post("/new", NewBook) + r.Put("/update/:id", UpdateBook) + r.Delete("/delete/:id", DeleteBook) +}, MyMiddleware1, MyMiddleware2) +~~~ + +### Services +Les services sont des objets injectés dans la liste d'arguments d'un handler. Un service peut être défini pour une *requête*, ou de manière *globale*. + + +#### Global Mapping +Les instances Martini implémentent l'interace inject.Injector, ce qui facilite grandement le mapping de services : +~~~ go +db := &MyDatabase{} +m := martini.Classic() +m.Map(db) // the service will be available to all handlers as *MyDatabase +// ... +m.Run() +~~~ + +#### Requête-Level Mapping +Pour une déclaration au niveau d'une requête, il suffit d'utiliser un handler via [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) : +~~~ go +func MyCustomLoggerHandler(c martini.Context, req *http.Request) { + logger := &MyCustomLogger{req} + c.Map(logger) // mapped as *MyCustomLogger +} +~~~ + +#### Mapping de valeurs à des interfaces +L'un des aspects les plus intéressants des services réside dans le fait qu'ils peuvent être liés à des interfaces. Par exemple, pour surcharger [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) avec un objet qui l'enveloppe et étend ses fonctionnalités, vous pouvez utiliser le handler suivant : +~~~ go +func WrapResponseWriter(res http.ResponseWriter, c martini.Context) { + rw := NewSpecialResponseWriter(res) + c.MapTo(rw, (*http.ResponseWriter)(nil)) // override ResponseWriter with our wrapper ResponseWriter +} +~~~ + +### Serveur de fichiers statiques +Une instance [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) est déjà capable de servir les fichiers statiques qu'elle trouvera dans le dossier *public* à la racine de votre serveur. +Vous pouvez indiquer d'autres dossiers sources à l'aide du handler [martini.Static](http://godoc.org/github.com/go-martini/martini#Static). +~~~ go +m.Use(martini.Static("assets")) // serve from the "assets" directory as well +~~~ + +## Les middleware Handlers +Les *middleware handlers* sont placés entre la requête HTTP entrante et le routeur. Ils ne sont aucunement différents des autres handlers présents dans Martini. Vous pouvez ajouter un middleware handler comme ceci : +~~~ go +m.Use(func() { + // do some middleware stuff +}) +~~~ +Vous avez un contrôle total sur la structure middleware avec la fonction ```Handlers```. Son exécution écrasera tous les handlers configurés précédemment : +~~~ go +m.Handlers( + Middleware1, + Middleware2, + Middleware3, +) +~~~ +Middleware Handlers est très pratique pour automatiser des fonctions comme le logging, l'autorisation, l'authentification, sessions, gzipping, pages d'erreur, et toutes les opérations qui se font avant ou après chaque requête HTTP : +~~~ go +// validate an api key +m.Use(func(res http.ResponseWriter, req *http.Request) { + if req.Header.Get("X-API-KEY") != "secret123" { + res.WriteHeader(http.StatusUnauthorized) + } +}) +~~~ + +### Next() (Suivant) +[Context.Next()](http://godoc.org/github.com/go-martini/martini#Context) est une fonction optionnelle que les Middleware Handlers peuvent appeler pour patienter jusqu'à ce que tous les autres handlers aient été exécutés. Cela fonctionne très bien pour toutes opérations qui interviennent après une requête HTTP : +~~~ go +// log before and after a request +m.Use(func(c martini.Context, log *log.Logger){ + log.Println("avant la requête") + + c.Next() + + log.Println("après la requête") +}) +~~~ + +## Martini Env +Plusieurs Martini handlers utilisent 'martini.Env' comme variable globale pour fournir des fonctionnalités particulières qui diffèrent entre l'environnement de développement et l'environnement de production. Il est recommandé que la variable 'MARTINI_ENV=production' soit définie pour déployer un serveur Martini en environnement de production. + +## FAQ (Foire aux questions) + +### Où puis-je trouver des middleware ? +Commencer par regarder dans le [martini-contrib](https://github.com/martini-contrib) projet. S'il n'y est pas, n'hésitez pas à contacter un membre de l'équipe martini-contrib pour ajouter un nouveau dépôt à l'organisation. + +* [auth](https://github.com/martini-contrib/auth) - Handlers for authentication. +* [binding](https://github.com/martini-contrib/binding) - Handler for mapping/validating a raw request into a structure. +* [gzip](https://github.com/martini-contrib/gzip) - Handler for adding gzip compress to requests +* [render](https://github.com/martini-contrib/render) - Handler that provides a service for easily rendering JSON and HTML templates. +* [acceptlang](https://github.com/martini-contrib/acceptlang) - Handler for parsing the `Accept-Language` HTTP header. +* [sessions](https://github.com/martini-contrib/sessions) - Handler that provides a Session service. +* [strip](https://github.com/martini-contrib/strip) - URL Prefix stripping. +* [method](https://github.com/martini-contrib/method) - HTTP method overriding via Header or form fields. +* [secure](https://github.com/martini-contrib/secure) - Implements a few quick security wins. +* [encoder](https://github.com/martini-contrib/encoder) - Encoder service for rendering data in several formats and content negotiation. +* [cors](https://github.com/martini-contrib/cors) - Handler that enables CORS support. +* [oauth2](https://github.com/martini-contrib/oauth2) - Handler that provides OAuth 2.0 login for Martini apps. Google Sign-in, Facebook Connect and Github login is supported. +* [vauth](https://github.com/rafecolton/vauth) - Handlers for vender webhook authentication (currently GitHub and TravisCI) + +### Comment puis-je m'intègrer avec des serveurs existants ? +Une instance Martini implémente ```http.Handler```. Elle peut donc utilisée pour alimenter des sous-arbres sur des serveurs Go existants. Voici l'exemple d'une application Martini pour Google App Engine : + +~~~ go +package hello + +import ( + "net/http" + "github.com/go-martini/martini" +) + +func init() { + m := martini.Classic() + m.Get("/", func() string { + return "Hello world!" + }) + http.Handle("/", m) +} +~~~ + +### Comment changer le port/adresse ? + +La fonction ```Run``` de Martini utilise le port et l'adresse spécifiés dans les variables d'environnement. Si elles ne peuvent y être trouvées, Martini utilisera *localhost:3000* par default. +Pour avoir plus de flexibilité sur le port et l'adresse, utilisez la fonction `martini.RunOnAddr` à la place. + +~~~ go + m := martini.Classic() + // ... + log.Fatal(m.RunOnAddr(":8080")) +~~~ + +### Rechargement du code en direct ? + +[gin](https://github.com/codegangsta/gin) et [fresh](https://github.com/pilu/fresh) sont tous les capables de recharger le code des applications martini chaque fois qu'il est modifié. + +## Contribuer +Martini est destiné à rester restreint et épuré. Toutes les contributions doivent finir dans un dépot dans l'organisation [martini-contrib](https://github.com/martini-contrib). Si vous avez une contribution pour le noyau de Martini, n'hésitez pas à envoyer une Pull Request. + +## A propos de Martini + +Inspiré par [express](https://github.com/visionmedia/express) et [Sinatra](https://github.com/sinatra/sinatra), Martini est l'oeuvre de nul d'autre que [Code Gangsta](http://codegangsta.io/), votre serviteur. diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_ja_JP.md b/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_ja_JP.md new file mode 100644 index 0000000..e5fdd90 --- /dev/null +++ b/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_ja_JP.md @@ -0,0 +1,356 @@ +# Martini [![wercker status](https://app.wercker.com/status/9b7dbc6e2654b604cd694d191c3d5487/s/master "wercker status")](https://app.wercker.com/project/bykey/9b7dbc6e2654b604cd694d191c3d5487)[![GoDoc](https://godoc.org/github.com/go-martini/martini?status.png)](http://godoc.org/github.com/go-martini/martini) + +MartiniはGolangによる、モジュール形式のウェブアプリケーション/サービスを作成するパワフルなパッケージです。 + +## はじめに + +Goをインストールし、[GOPATH](http://golang.org/doc/code.html#GOPATH)を設定した後、Martiniを始める最初の`.go`ファイルを作りましょう。これを`server.go`とします。 + +~~~ go +package main + +import "github.com/go-martini/martini" + +func main() { + m := martini.Classic() + m.Get("/", func() string { + return "Hello world!" + }) + m.Run() +} +~~~ + +そのあとで、Martini パッケージをインストールします。(**go 1.1**か、それ以上のバーションが必要です。) + +~~~ +go get github.com/go-martini/martini +~~~ + +インストールが完了したら、サーバを起動しましょう。 +~~~ +go run server.go +~~~ + +そうすれば`localhost:3000`でMartiniのサーバが起動します。 + +## 分からないことがあったら? + +[メーリングリスト](https://groups.google.com/forum/#!forum/martini-go)に入る + +[デモビデオ](http://martini.codegangsta.io/#demo)をみる + +Stackoverflowで[martini tag](http://stackoverflow.com/questions/tagged/martini)を使い質問する + +GoDoc [documentation](http://godoc.org/github.com/go-martini/martini) + + +## 特徴 +* 非常にシンプルに使用できる +* 押し付けがましくないデザイン +* 他のGolangパッケージとの協調性 +* 素晴らしいパスマッチングとルーティング +* モジュラーデザイン - 機能性の付け外しが簡単 +* たくさんの良いハンドラ/ミドルウェア +* 優れた 'すぐに使える' 機能たち +* **[http.HandlerFunc](http://godoc.org/net/http#HandlerFunc)との完全な互換性** + +## もっとミドルウェアについて知るには? +さらに多くのミドルウェアとその機能について知りたいときは、[martini-contrib](https://github.com/martini-contrib) オーガナイゼーションにあるリポジトリを確認してください。 + +## 目次(Table of Contents) +* [Classic Martini](#classic-martini) + * [ハンドラ](#handlers) + * [ルーティング](#routing) + * [サービス](#services) + * [静的ファイル配信](#serving-static-files) +* [ミドルウェアハンドラ](#middleware-handlers) + * [Next()](#next) +* [Martini Env](#martini-env) +* [FAQ](#faq) + +## Classic Martini +立ち上げ、すぐ実行できるように、[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) はほとんどのウェブアプリケーションで機能する、標準的な機能を提供します。 +~~~ go + m := martini.Classic() + // ... middleware and routing goes here + m.Run() +~~~ + +下記が[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic)が自動的に読み込む機能の一覧です。 + * Request/Response Logging - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger) + * Panic Recovery - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery) + * Static File serving - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) + * Routing - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router) + +### ハンドラ +ハンドラはMartiniのコアであり、存在意義でもあります。ハンドラには基本的に、呼び出し可能な全ての関数が適応できます。 +~~~ go +m.Get("/", func() { + println("hello world") +}) +~~~ + +#### Return Values +もしハンドラが何かを返す場合、Martiniはその結果を現在の[http.ResponseWriter](http://godoc.org/net/http#ResponseWriter)にstringとして書き込みます。 +~~~ go +m.Get("/", func() string { + return "hello world" // HTTP 200 : "hello world" +}) +~~~ + +任意でステータスコードを返すこともできます。 +~~~ go +m.Get("/", func() (int, string) { + return 418, "i'm a teapot" // HTTP 418 : "i'm a teapot" +}) +~~~ + +#### Service Injection +ハンドラはリフレクションによって実行されます。Martiniはハンドラの引数内の依存関係を**依存性の注入(Dependency Injection)**を使って解決しています。**これによって、Martiniはgolangの`http.HandlerFunc`と完全な互換性を備えています。** + +ハンドラに引数を追加すると、Martiniは内部のサービスを検索し、依存性をtype assertionによって解決しようと試みます。 +~~~ go +m.Get("/", func(res http.ResponseWriter, req *http.Request) { // res and req are injected by Martini + res.WriteHeader(200) // HTTP 200 +}) +~~~ + +[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic)にはこれらのサービスが内包されています: + * [*log.Logger](http://godoc.org/log#Logger) - Martiniのためのグローバルなlogger. + * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http request context. + * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string`型の、ルートマッチングによって検出されたパラメータ + * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Route helper service. + * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http Response writer interface. + * [*http.Request](http://godoc.org/net/http/#Request) - http Request. + +### ルーティング +Martiniでは、ルーティングはHTTPメソッドとURL-matching patternによって対になっており、それぞれが一つ以上のハンドラメソッドを持つことができます。 +~~~ go +m.Get("/", func() { + // show something +}) + +m.Patch("/", func() { + // update something +}) + +m.Post("/", func() { + // create something +}) + +m.Put("/", func() { + // replace something +}) + +m.Delete("/", func() { + // destroy something +}) + +m.Options("/", func() { + // http options +}) + +m.NotFound(func() { + // handle 404 +}) +~~~ + +ルーティングはそれらの定義された順番に検索され、最初にマッチしたルーティングが呼ばれます。 + +名前付きパラメータを定義することもできます。これらのパラメータは[martini.Params](http://godoc.org/github.com/go-martini/martini#Params)サービスを通じてアクセスすることができます: +~~~ go +m.Get("/hello/:name", func(params martini.Params) string { + return "Hello " + params["name"] +}) +~~~ + +ワイルドカードを使用することができます: +~~~ go +m.Get("/hello/**", func(params martini.Params) string { + return "Hello " + params["_1"] +}) +~~~ + +正規表現も、このように使うことができます: +~~~go +m.Get("/hello/(?P[a-zA-Z]+)", func(params martini.Params) string { + return fmt.Sprintf ("Hello %s", params["name"]) +}) +~~~ + +もっと正規表現の構文をしりたい場合は、[Go documentation](http://golang.org/pkg/regexp/syntax/) を見てください。 + + +ハンドラは互いの上に積み重ねてることができます。これは、認証や承認処理の際に便利です: +~~~ go +m.Get("/secret", authorize, func() { + // this will execute as long as authorize doesn't write a response +}) +~~~ + +ルーティンググループも、Groupメソッドを使用することで追加できます。 +~~~ go +m.Group("/books", func(r martini.Router) { + r.Get("/:id", GetBooks) + r.Post("/new", NewBook) + r.Put("/update/:id", UpdateBook) + r.Delete("/delete/:id", DeleteBook) +}) +~~~ + +ハンドラにミドルウェアを渡せるのと同じように、グループにもミドルウェアを渡すことができます: +~~~ go +m.Group("/books", func(r martini.Router) { + r.Get("/:id", GetBooks) + r.Post("/new", NewBook) + r.Put("/update/:id", UpdateBook) + r.Delete("/delete/:id", DeleteBook) +}, MyMiddleware1, MyMiddleware2) +~~~ + +### サービス +サービスはハンドラの引数として注入されることで利用可能になるオブジェクトです。これらは*グローバル*、または*リクエスト*のレベルでマッピングすることができます。 + +#### Global Mapping +Martiniのインスタンスはinject.Injectorのインターフェースを実装しています。なので、サービスをマッピングすることは簡単です: +~~~ go +db := &MyDatabase{} +m := martini.Classic() +m.Map(db) // the service will be available to all handlers as *MyDatabase +// ... +m.Run() +~~~ + +#### Request-Level Mapping +リクエストレベルでのマッピングは[martini.Context](http://godoc.org/github.com/go-martini/martini#Context)を使い、ハンドラ内で行うことができます: +~~~ go +func MyCustomLoggerHandler(c martini.Context, req *http.Request) { + logger := &MyCustomLogger{req} + c.Map(logger) // mapped as *MyCustomLogger +} +~~~ + +#### Mapping values to Interfaces +サービスの最も強力なことの一つは、インターフェースにサービスをマッピングできる機能です。例えば、[http.ResponseWriter](http://godoc.org/net/http#ResponseWriter)を機能を追加して上書きしたい場合、このようにハンドラを書くことができます: +~~~ go +func WrapResponseWriter(res http.ResponseWriter, c martini.Context) { + rw := NewSpecialResponseWriter(res) + c.MapTo(rw, (*http.ResponseWriter)(nil)) // override ResponseWriter with our wrapper ResponseWriter +} +~~~ + +### 静的ファイル配信 + +[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) インスタンスは、自動的にルート直下の "public" ディレクトリ以下の静的ファイルを配信します。[martini.Static](http://godoc.org/github.com/go-martini/martini#Static)を追加することで、もっと多くのディレクトリを配信することもできます: +~~~ go +m.Use(martini.Static("assets")) // serve from the "assets" directory as well +~~~ + +## ミドルウェア ハンドラ +ミドルウェア ハンドラは次に来るhttpリクエストとルーターの間に位置します。本質的には、その他のハンドラとの違いはありません。ミドルウェア ハンドラの追加はこのように行います: +~~~ go +m.Use(func() { + // do some middleware stuff +}) +~~~ + +`Handlers`関数を使えば、ミドルウェアスタックを完全に制御できます。これは以前に設定されている全てのハンドラを置き換えます: + +~~~ go +m.Handlers( + Middleware1, + Middleware2, + Middleware3, +) +~~~ + +ミドルウェア ハンドラはロギング、認証、承認プロセス、セッション、gzipping、エラーページの表示、その他httpリクエストの前後で怒らなければならないような場合に素晴らしく効果を発揮します。 +~~~ go +// validate an api key +m.Use(func(res http.ResponseWriter, req *http.Request) { + if req.Header.Get("X-API-KEY") != "secret123" { + res.WriteHeader(http.StatusUnauthorized) + } +}) +~~~ + +### Next() + +[Context.Next()](http://godoc.org/github.com/go-martini/martini#Context) は他のハンドラが実行されたことを取得するために使用する機能です。これはhttpリクエストのあとに実行したい任意の関数があるときに素晴らしく機能します: +~~~ go +// log before and after a request +m.Use(func(c martini.Context, log *log.Logger){ + log.Println("before a request") + + c.Next() + + log.Println("after a request") +}) +~~~ + +## Martini Env + +いくつかのMartiniのハンドラはdevelopment環境とproduction環境で別々の動作を提供するために`martini.Env`グローバル変数を使用しています。Martiniサーバを本番環境にデプロイする際には、`MARTINI_ENV=production`環境変数をセットすることをおすすめします。 + +## FAQ + +### Middlewareを見つけるには? + +[martini-contrib](https://github.com/martini-contrib)プロジェクトをみることから始めてください。もし望みのものがなければ、新しいリポジトリをオーガナイゼーションに追加するために、martini-contribチームのメンバーにコンタクトを取ってみてください。 + +* [auth](https://github.com/martini-contrib/auth) - Handlers for authentication. +* [binding](https://github.com/martini-contrib/binding) - Handler for mapping/validating a raw request into a structure. +* [gzip](https://github.com/martini-contrib/gzip) - Handler for adding gzip compress to requests +* [render](https://github.com/martini-contrib/render) - Handler that provides a service for easily rendering JSON and HTML templates. +* [acceptlang](https://github.com/martini-contrib/acceptlang) - Handler for parsing the `Accept-Language` HTTP header. +* [sessions](https://github.com/martini-contrib/sessions) - Handler that provides a Session service. +* [strip](https://github.com/martini-contrib/strip) - URL Prefix stripping. +* [method](https://github.com/martini-contrib/method) - HTTP method overriding via Header or form fields. +* [secure](https://github.com/martini-contrib/secure) - Implements a few quick security wins. +* [encoder](https://github.com/martini-contrib/encoder) - Encoder service for rendering data in several formats and content negotiation. +* [cors](https://github.com/martini-contrib/cors) - Handler that enables CORS support. +* [oauth2](https://github.com/martini-contrib/oauth2) - Handler that provides OAuth 2.0 login for Martini apps. Google Sign-in, Facebook Connect and Github login is supported. + +### 既存のサーバに組み込むには? + +Martiniのインスタンスは`http.Handler`を実装しているので、既存のGoサーバ上でサブツリーを提供するのは簡単です。例えばこれは、Google App Engine上で動くMartiniアプリです: + +~~~ go +package hello + +import ( + "net/http" + "github.com/go-martini/martini" +) + +func init() { + m := martini.Classic() + m.Get("/", func() string { + return "Hello world!" + }) + http.Handle("/", m) +} +~~~ + +### どうやってポート/ホストをかえるの? + +Martiniの`Run`関数はPORTとHOSTという環境変数を探し、その値を使用します。見つからない場合はlocalhost:3000がデフォルトで使用されます。もっと柔軟性をもとめるなら、`martini.RunOnAddr`関数が役に立ちます: + +~~~ go + m := martini.Classic() + // ... + log.Fatal(m.RunOnAddr(":8080")) +~~~ + +### Live code reload? + +[gin](https://github.com/codegangsta/gin) と [fresh](https://github.com/pilu/fresh) 両方がMartiniアプリケーションを自動リロードできます。 + +## Contributing +Martini本体は小さく、クリーンであるべきであり、ほとんどのコントリビューションは[martini-contrib](https://github.com/martini-contrib) オーガナイゼーション内で完結すべきですが、もしMartiniのコアにコントリビュートすることがあるなら、自由に行ってください。 + +## About + +Inspired by [express](https://github.com/visionmedia/express) and [sinatra](https://github.com/sinatra/sinatra) + +Martini is obsessively designed by none other than the [Code Gangsta](http://codegangsta.io/) diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_ko_kr.md b/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_ko_kr.md new file mode 100644 index 0000000..8b5a1fa --- /dev/null +++ b/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_ko_kr.md @@ -0,0 +1,359 @@ +# Martini [![wercker status](https://app.wercker.com/status/9b7dbc6e2654b604cd694d191c3d5487/s/master "wercker status")](https://app.wercker.com/project/bykey/9b7dbc6e2654b604cd694d191c3d5487)[![GoDoc](https://godoc.org/github.com/go-martini/martini?status.png)](http://godoc.org/github.com/go-martini/martini) + +마티니(Martini)는 강력하고 손쉬운 웹애플리케이션 / 웹서비스개발을 위한 Golang 패키지입니다. + +## 시작하기 + +Go 인스톨 및 [GOPATH](http://golang.org/doc/code.html#GOPATH) 환경변수 설정 이후에, `.go` 파일 하나를 만들어 보죠..흠... 일단 `server.go`라고 부르겠습니다. +~~~go +package main + +import "github.com/go-martini/martini" + +func main() { + m := martini.Classic() + m.Get("/", func() string { + return "Hello, 세계!" + }) + m.Run() +} +~~~ + +마티니 패키지를 인스톨 합니다. (**go 1.1** 혹은 그 이상 버젼 필요): +~~~ +go get github.com/go-martini/martini +~~~ + +이제 서버를 돌려 봅시다: +~~~ +go run server.go +~~~ + +마티니 웹서버가 `localhost:3000`에서 돌아가고 있는 것을 확인하실 수 있을 겁니다. + +## 도움이 필요하다면? + +[메일링 리스트](https://groups.google.com/forum/#!forum/martini-go)에 가입해 주세요 + +[데모 비디오](http://martini.codegangsta.io/#demo)도 있어요. + +혹은 Stackoverflow에 [마티니 태크](http://stackoverflow.com/questions/tagged/martini)를 이용해서 물어봐 주세요 + +GoDoc [문서(documentation)](http://godoc.org/github.com/go-martini/martini) + +문제는 전부다 영어로 되어 있다는 건데요 -_-;;; +나는 한글 아니면 보기 싫다! 하는 분들은 아래 링크를 참조하세요 +- [golang-korea](https://code.google.com/p/golang-korea/) +- 혹은 ([RexK](http://github.com/RexK))의 이메일로 연락주세요. + +## 주요기능 +* 사용하기 엄청 쉽습니다. +* 비간섭(Non-intrusive) 디자인 +* 다른 Golang 패키지들과 잘 어울립니다. +* 끝내주는 경로 매칭과 라우팅. +* 모듈 형 디자인 - 기능추가 쉽고, 코드 꺼내오기도 쉬움. +* 쓸모있는 핸들러와 미들웨어가 많음. +* 훌률한 패키지화(out of the box) 기능들 +* **[http.HandlerFunc](http://godoc.org/net/http#HandlerFunc) 인터페이스와 호환율 100%** + +## 미들웨어(Middleware) +미들웨어들과 추가기능들은 [martini-contrib](https://github.com/martini-contrib)에서 확인해 주세요. + +## 목차 +* [Classic Martini](#classic-martini) + * [핸들러](#핸들러handlers) + * [라우팅](#라우팅routing) + * [서비스](#서비스services) + * [정적파일 서빙](#정적파일-서빙serving-static-files) +* [미들웨어 핸들러](#미들웨어-핸들러middleware-handlers) + * [Next()](#next) +* [Martini Env](#martini-env) +* [FAQ](#faq) + +## Classic Martini +마티니를 쉽고 빠르게 이용하시려면, [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic)를 이용해 보세요. 보통 웹애플리케이션에서 사용하는 설정들이 이미 포함되어 있습니다. +~~~ go + m := martini.Classic() + // ... 미들웨어와 라우팅 설정은 이곳에 오면 작성하면 됩니다. + m.Run() +~~~ + +아래는 [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic)의 자동으로 장착하는 기본 기능들입니다. + + * Request/Response 로그 기능 - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger) + * 패닉 리커버리 (Panic Recovery) - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery) + * 정적 파일 서빙 - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) + * 라우팅(Routing) - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router) + +### 핸들러(Handlers) + +핸들러(Handlers)는 마티니의 핵심입니다. 핸들러는 기본적으로 실행 가능한 모든형태의 함수들입니다. +~~~ go +m.Get("/", func() { + println("hello 세계") +}) +~~~ + +#### 반환 값 (Return Values) +핸들러가 반환을 하는 함수라면, 마티니는 반환 값을 [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter)에 스트링으로 입력 할 것입니다. +~~~ go +m.Get("/", func() string { + return "hello 세계" // HTTP 200 : "hello 세계" +}) +~~~ + +원하신다면, 선택적으로 상태코드도 함께 반화 할 수 있습니다. +~~~ go +m.Get("/", func() (int, string) { + return 418, "난 주전자야!" // HTTP 418 : "난 주전자야!" +}) +~~~ + +#### 서비스 주입(Service Injection) +핸들러들은 리플렉션을 통해 호출됩니다. 마티니는 *의존성 주입*을 이용해서 핸들러의 인수들을 주입합니다. **이것이 마티니를 `http.HandlerFunc` 인터페이스와 100% 호환할 수 있게 해줍니다.** + +핸들러의 인수를 입력했다면, 마티니가 서비스 목록들을 살펴본 후 타입확인(type assertion)을 통해 의존성을 해결을 시도 할 것입니다. +~~~ go +m.Get("/", func(res http.ResponseWriter, req *http.Request) { // res와 req는 마티니에 의해 주입되었다. + res.WriteHeader(200) // HTTP 200 +}) +~~~ + +아래 서비스들은 [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic):에 포함되어 있습니다. + * [*log.Logger](http://godoc.org/log#Logger) - 마티니의 글러벌(전역) 로그. + * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http 요청 컨텍스트. + * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - 루트 매칭으로 찾은 인자를 `map[string]string`으로 변형. + * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - 루트 도우미 서미스. + * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http Response writer 인터페이스. + * [*http.Request](http://godoc.org/net/http/#Request) - http 리퀘스트. + +### 라우팅(Routing) +마티니에서 루트는 HTTP 메소드와 URL매칭 패턴의 페어입니다. +각 루트는 하나 혹은 그 이상의 핸들러 메소드를 가질 수 있습니다. +~~~ go +m.Get("/", func() { + // 보여줘 봐 +}) + +m.Patch("/", func() { + // 업데이트 좀 해 +}) + +m.Post("/", func() { + // 만들어봐 +}) + +m.Put("/", func() { + // 교환해봐 +}) + +m.Delete("/", func() { + // 없애버려! +}) + +m.Options("/", func() { + // http 옵션 메소드 +}) + +m.NotFound(func() { + // 404 해결하기 +}) +~~~ + +루트들은 정의된 순서대로 매칭된다. 들어온 요그에 첫번째 매칭된 루트가 호출된다. + +루트 패턴은 [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) service로 액세스 가능한 인자들을 포함하기도 한다: +~~~ go +m.Get("/hello/:name", func(params martini.Params) string { + return "Hello " + params["name"] // :name을 Params인자에서 추출 +}) +~~~ + +루트는 별표식(\*)으로 매칭 될 수도 있습니다: +~~~ go +m.Get("/hello/**", func(params martini.Params) string { + return "Hello " + params["_1"] +}) +~~~ + +Regular expressions can be used as well: +정규식도 사용가능합니다: +~~~go +m.Get("/hello/(?P[a-zA-Z]+)", func(params martini.Params) string { + return fmt.Sprintf ("Hello %s", params["name"]) +}) +~~~ +정규식에 관하여 더 자세히 알고 싶다면 [Go documentation](http://golang.org/pkg/regexp/syntax/)을 참조해 주세요. + +루트 핸들러는 스택을 쌓아 올릴 수 있습니다. 특히 유저 인증작업이나, 허가작업에 유용히 쓰일 수 있죠. +~~~ go +m.Get("/secret", authorize, func() { + // 이 함수는 authorize 함수가 resopnse에 결과를 쓰지 않는이상 실행 될 거에요. +}) +~~~ + +루트그룹은 루트들을 한 곳에 모아 정리하는데 유용합니다. +~~~ go +m.Group("/books", func(r martini.Router) { + r.Get("/:id", GetBooks) + r.Post("/new", NewBook) + r.Put("/update/:id", UpdateBook) + r.Delete("/delete/:id", DeleteBook) +}) +~~~ + +핸들러에 미들웨어를 집어넣을 수 있었듯이, 그룹에도 미들웨어 집어넣는게 가능합니다. +~~~ go +m.Group("/books", func(r martini.Router) { + r.Get("/:id", GetBooks) + r.Post("/new", NewBook) + r.Put("/update/:id", UpdateBook) + r.Delete("/delete/:id", DeleteBook) +}, MyMiddleware1, MyMiddleware2) +~~~ + +### 서비스(Services) +서비스는 핸들러의 인수목록에 주입될수 있는 오브젝트들을 말합니다. 서비스는 *글로벌* 혹은 *리퀘스트* 레벨단위로 주입이 가능합니다. + +#### 글로벌 맵핑(Global Mapping) +마타니 인스턴스는 서비스 맵핑을 쉽게 하기 위해서 inject.Injector 인터페이스를 반형합니다: +~~~ go +db := &MyDatabase{} +m := martini.Classic() +m.Map(db) // 서비스가 모든 핸들러에서 *MyDatabase로서 사용될 수 있습니다. +// ... +m.Run() +~~~ + +#### 리퀘스트 레벨 맵핑(Request-Level Mapping) +리퀘스트 레벨 맵핑은 핸들러안에서 [martini.Context](http://godoc.org/github.com/go-martini/martini#Context)를 사용하면 됩니다: +~~~ go +func MyCustomLoggerHandler(c martini.Context, req *http.Request) { + logger := &MyCustomLogger{req} + c.Map(logger) // *MyCustomLogger로서 맵핑 됨 +} +~~~ + +#### 인터페이스로 값들 맵핑(Mapping values to Interfaces) +서비스의 강력한 기능중 하나는 서비스를 인터페이스로 맵핑이 가능하다는 것입니다. 예를들어, [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter)를 치환(override)해서 부가 기능들을 수행하게 하고 싶으시다면, 아래와 같은 핸들러를 작성 하시면 됩니다. + +~~~ go +func WrapResponseWriter(res http.ResponseWriter, c martini.Context) { + rw := NewSpecialResponseWriter(res) + c.MapTo(rw, (*http.ResponseWriter)(nil)) // ResponseWriter를 NewResponseWriter로 치환(override) +} +~~~ + +### 정적파일 서빙(Serving Static Files) +[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) 인스턴스는 "public" 폴더안에 있는 파일들은 정적파일로서 자동으로 서빙합니다. 더 많은 폴더들은 정적파일 폴더에 포함시키시려면 [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) 핸들러를 이용하시면 됩니다. + +~~~ go +m.Use(martini.Static("assets")) // "assets" 폴더에서도 정적파일 서빙. +~~~ + +## 미들웨어 핸들러(Middleware Handlers) +미들웨어 핸들러는 http request와 라우팅 사이에서 작동합니다. 미들웨어 핸들러는 근본적으로 다른 핸들러들과는 다릅니다. 사용방법은 아래와 같습니다: +~~~ go +m.Use(func() { + // 미들웨어 임무 수행! +}) +~~~ + +`Handlers`를 이용하여 미들웨어 스택들의 완전 컨트롤이 가능합니다. 다만, 이렇게 설정하시면 이전에 `Handlers`를 이용하여 설정한 핸들러들은 사라집니다: +~~~ go +m.Handlers( + Middleware1, + Middleware2, + Middleware3, +) +~~~ + +미들웨어 핸들러는 로깅(logging), 허가(authorization), 인가(authentication), 세션, 압축(gzipping), 에러 페이지 등 등, http request의 전후로 실행되어야 할 일들을 처리하기 아주 좋습니다: +~~~ go +// API 키 확인작업 +m.Use(func(res http.ResponseWriter, req *http.Request) { + if req.Header.Get("X-API-KEY") != "비밀암호!!!" { + res.WriteHeader(http.StatusUnauthorized) // HTTP 401 + } +}) +~~~ + +### Next() +[Context.Next()](http://godoc.org/github.com/go-martini/martini#Context)는 선택적 함수입니다. 이 함수는 http request가 다 작동 될때까지 기다립니다.따라서 http request 이후에 실행 되어야 할 업무들을 수행하기 좋은 함수입니다. +~~~ go +// log before and after a request +m.Use(func(c martini.Context, log *log.Logger){ + log.Println("request전입니다.") + + c.Next() + + log.Println("request후 입니다.") +}) +~~~ + +## Martini Env +마티니 핸들러들은 `martini.Env` 글로벌 변수를 사용하여 개발환경에서는 프로덕션 환경과는 다르게 작동하기도 합니다. 따라서, 프로덕션 서버로 마티니 서보를 배포하시게 된다면 꼭 환경변수 `MARTINI_ENV=production`를 세팅해주시기 바랍니다. + +## FAQ + +### 미들웨어들을 어디서 찾아야 하나요? + +깃헙에서 [martini-contrib](https://github.com/martini-contrib) 프로젝트들을 탖아보세요. 만약에 못 찾으시겠으면, martini-contrib 팀원들에게 연락해서 하나 만들어 달라고 해보세요. +* [auth](https: //github.com/martini-contrib/auth) - 인증작업을 도와주는 핸들러. +* [binding](https://github.com/martini-contrib/binding) - request를 맵핑하고 검사하는 핸들러. +* [gzip](https://github.com/martini-contrib/gzip) - gzip 핸들러. +* [render](https://github.com/martini-contrib/render) - HTML 템플레이트들과 JSON를 사용하기 편하게 해주는 핸들러. +* [acceptlang](https://github.com/martini-contrib/acceptlang) - `Accept-Language` HTTP 해더를 파싱할때 유용한 핸들러. +* [sessions](https://github.com/martini-contrib/sessions) - 세션 서비스를 제공하는 핸들러. +* [strip](https://github.com/martini-contrib/strip) - URL 프리틱스를 없애주는 핸들러. +* [method](https://github.com/martini-contrib/method) - 해더나 폼필드를 이용한 HTTP 메소드 치환. +* [secure](https://github.com/martini-contrib/secure) - 몇몇 보안설정을 위한 핸들러. +* [encoder](https://github.com/martini-contrib/encoder) - 데이터 렌더링과 컨텐트 타엽을위한 인코딩 서비스. +* [cors](https://github.com/martini-contrib/cors) - CORS 서포트를 위한 핸들러. +* [oauth2](https://github.com/martini-contrib/oauth2) - OAuth2.0 로그인 핸들러. 페이스북, 구글, 깃헙 지원. + +### 현재 작동중인 서버에 마티니를 적용하려면? + +마티니 인스턴스는 `http.Handler` 인터페이스를 차용합니다. 따라서 Go 서버 서브트리로 쉽게 사용될 수 있습니다. 아래 코드는 구글 앱 엔진에서 작동하는 마티니 앱입니다: + +~~~ go +package hello + +import ( + "net/http" + "github.com/go-martini/martini" +) + +func init() { + m := martini.Classic() + m.Get("/", func() string { + return "Hello 세계!" + }) + http.Handle("/", m) +} +~~~ + +### 포트와 호스트는 어떻게 바꾸나요? + +마티니의 `Run` 함수는 PORT와 HOST 환경변수를 이용하는데, 설정이 안되어 있다면 localhost:3000으로 설정 되어 집니다. +좀더 유연하게 설정을 하고 싶다면, `martini.RunOnAddr`를 활용해 주세요. + +~~~ go + m := martini.Classic() + // ... + log.Fatal(m.RunOnAddr(":8080")) +~~~ + +### 라이브 포드 리로드? + +[gin](https://github.com/codegangsta/gin) and [fresh](https://github.com/pilu/fresh) 마티니 앱의 라이브 리로드를 도와줍니다. + +## 공헌하기(Contributing) + +마티니는 간단하고 가벼운 패키지로 남을 것입니다. 따라서 보통 대부분의 공헌들은 [martini-contrib](https://github.com/martini-contrib) 그룹의 저장소로 가게 됩니다. 만약 마티니 코어에 기여하고 싶으시다면 주저없이 Pull Request를 해주세요. + +## About + +[express](https://github.com/visionmedia/express) 와 [sinatra](https://github.com/sinatra/sinatra)의 영향을 받았습니다. + +마티니는 [Code Gangsta](http://codegangsta.io/)가 디자인 했습니다. diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_pt_br.md b/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_pt_br.md new file mode 100644 index 0000000..2c0da51 --- /dev/null +++ b/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_pt_br.md @@ -0,0 +1,355 @@ +# Martini [![wercker status](https://app.wercker.com/status/9b7dbc6e2654b604cd694d191c3d5487/s/master "wercker status")](https://app.wercker.com/project/bykey/9b7dbc6e2654b604cd694d191c3d5487)[![GoDoc](https://godoc.org/github.com/go-martini/martini?status.png)](http://godoc.org/github.com/go-martini/martini) + +Martini é um poderoso pacote para escrever aplicações/serviços modulares em Golang.. + + +## Vamos começar + +Após a instalação do Go e de configurar o [GOPATH](http://golang.org/doc/code.html#GOPATH), crie seu primeiro arquivo `.go`. Vamos chamá-lo de `server.go`. + +~~~ go +package main + +import "github.com/go-martini/martini" + +func main() { + m := martini.Classic() + m.Get("/", func() string { + return "Hello world!" + }) + m.Run() +} +~~~ + +Então instale o pacote do Martini (É necessário **go 1.1** ou superior): +~~~ +go get github.com/go-martini/martini +~~~ + +Então rode o servidor: +~~~ +go run server.go +~~~ + +Agora você tem um webserver Martini rodando na porta `localhost:3000`. + +## Obtenha ajuda + +Assine a [Lista de email](https://groups.google.com/forum/#!forum/martini-go) + +Veja o [Vídeo demonstrativo](http://martini.codegangsta.io/#demo) + +Use a tag [martini](http://stackoverflow.com/questions/tagged/martini) para perguntas no Stackoverflow + + + +## Caracteríticas +* Extrema simplicidade de uso. +* Design não intrusivo. +* Boa integração com outros pacotes Golang. +* Router impressionante. +* Design modular - Fácil para adicionar e remover funcionalidades. +* Muito bom no uso handlers/middlewares. +* Grandes caracteríticas inovadoras. +* **Completa compatibilidade com a interface [http.HandlerFunc](http://godoc.org/net/http#HandlerFunc).** + +## Mais Middleware +Para mais middleware e funcionalidades, veja os repositórios em [martini-contrib](https://github.com/martini-contrib). + +## Tabela de Conteudos +* [Classic Martini](#classic-martini) + * [Handlers](#handlers) + * [Routing](#routing) + * [Services](#services) + * [Serving Static Files](#serving-static-files) +* [Middleware Handlers](#middleware-handlers) + * [Next()](#next) +* [Martini Env](#martini-env) +* [FAQ](#faq) + +## Classic Martini +Para iniciar rapidamente, [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) provê algumas ferramentas razoáveis para maioria das aplicações web: +~~~ go + m := martini.Classic() + // ... middleware e rota aqui + m.Run() +~~~ + +Algumas das funcionalidade que o [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) oferece automaticamente são: + * Request/Response Logging - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger) + * Panic Recovery - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery) + * Servidor de arquivos státicos - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) + * Rotas - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router) + +### Handlers +Handlers são o coração e a alma do Martini. Um handler é basicamente qualquer função que pode ser chamada: +~~~ go +m.Get("/", func() { + println("hello world") +}) +~~~ + +#### Retorno de Valores +Se um handler retornar alguma coisa, Martini irá escrever o valor retornado como uma string ao [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter): +~~~ go +m.Get("/", func() string { + return "hello world" // HTTP 200 : "hello world" +}) +~~~ + +Você também pode retornar o código de status: +~~~ go +m.Get("/", func() (int, string) { + return 418, "Eu sou um bule" // HTTP 418 : "Eu sou um bule" +}) +~~~ + +#### Injeção de Serviços +Handlers são chamados via reflexão. Martini utiliza *Injeção de Dependencia* para resolver as dependencias nas listas de argumentos dos Handlers . **Isso faz Martini ser completamente compatível com a interface `http.HandlerFunc` do golang.** + +Se você adicionar um argumento ao seu Handler, Martini ira procurar na sua lista de serviços e tentar resolver sua dependencia pelo seu tipo: +~~~ go +m.Get("/", func(res http.ResponseWriter, req *http.Request) { // res e req são injetados pelo Martini + res.WriteHeader(200) // HTTP 200 +}) +~~~ + +Os seguintes serviços são incluídos com [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic): + * [*log.Logger](http://godoc.org/log#Logger) - Log Global para Martini. + * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http request context. + * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string` de nomes dos parâmetros buscados pela rota. + * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Serviço de auxílio as rotas. + * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http Response escreve a interface. + * [*http.Request](http://godoc.org/net/http/#Request) - http Request. + +### Rotas +No Martini, uma rota é um método HTTP emparelhado com um padrão de URL de correspondência. +Cada rota pode ter um ou mais métodos handler: +~~~ go +m.Get("/", func() { + // mostra alguma coisa +}) + +m.Patch("/", func() { + // altera alguma coisa +}) + +m.Post("/", func() { + // cria alguma coisa +}) + +m.Put("/", func() { + // sobrescreve alguma coisa +}) + +m.Delete("/", func() { + // destrói alguma coisa +}) + +m.Options("/", func() { + // opções do HTTP +}) + +m.NotFound(func() { + // manipula 404 +}) +~~~ + +As rotas são combinadas na ordem em que são definidas. A primeira rota que corresponde a solicitação é chamada. + +O padrão de rotas pode incluir parâmetros que podem ser acessados via [martini.Params](http://godoc.org/github.com/go-martini/martini#Params): +~~~ go +m.Get("/hello/:name", func(params martini.Params) string { + return "Hello " + params["name"] +}) +~~~ + +As rotas podem ser combinados com expressões regulares e globs: +~~~ go +m.Get("/hello/**", func(params martini.Params) string { + return "Hello " + params["_1"] +}) +~~~ + +Expressões regulares podem ser bem usadas: +~~~go +m.Get("/hello/(?P[a-zA-Z]+)", func(params martini.Params) string { + return fmt.Sprintf ("Hello %s", params["name"]) +}) +~~~ +Dê uma olhada na [documentação](http://golang.org/pkg/regexp/syntax/) para mais informações sobre expressões regulares. + + +Handlers de rota podem ser empilhados em cima uns dos outros, o que é útil para coisas como autenticação e autorização: +~~~ go +m.Get("/secret", authorize, func() { + // Será executado quando authorize não escrever uma resposta +}) +~~~ + +Grupos de rota podem ser adicionados usando o método Group. +~~~ go +m.Group("/books", func(r martini.Router) { + r.Get("/:id", GetBooks) + r.Post("/new", NewBook) + r.Put("/update/:id", UpdateBook) + r.Delete("/delete/:id", DeleteBook) +}) +~~~ + +Assim como você pode passar middlewares para um manipulador você pode passar middlewares para grupos. +~~~ go +m.Group("/books", func(r martini.Router) { + r.Get("/:id", GetBooks) + r.Post("/new", NewBook) + r.Put("/update/:id", UpdateBook) + r.Delete("/delete/:id", DeleteBook) +}, MyMiddleware1, MyMiddleware2) +~~~ + +### Serviços +Serviços são objetos que estão disponíveis para ser injetado em uma lista de argumentos de Handler. Você pode mapear um serviço num nível *Global* ou *Request*. + +#### Mapeamento Global +Um exemplo onde o Martini implementa a interface inject.Injector, então o mapeamento de um serviço é fácil: +~~~ go +db := &MyDatabase{} +m := martini.Classic() +m.Map(db) // o serviço estará disponível para todos os handlers *MyDatabase. +// ... +m.Run() +~~~ + +#### Mapeamento por requisição +Mapeamento do nível de request pode ser feito via handler através [martini.Context](http://godoc.org/github.com/go-martini/martini#Context): +~~~ go +func MyCustomLoggerHandler(c martini.Context, req *http.Request) { + logger := &MyCustomLogger{req} + c.Map(logger) // mapeamento é *MyCustomLogger +} +~~~ + +#### Valores de Mapeamento para Interfaces +Uma das partes mais poderosas sobre os serviços é a capacidade para mapear um serviço de uma interface. Por exemplo, se você quiser substituir o [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) com um objeto que envolveu-o e realizou operações extras, você pode escrever o seguinte handler: +~~~ go +func WrapResponseWriter(res http.ResponseWriter, c martini.Context) { + rw := NewSpecialResponseWriter(res) + c.MapTo(rw, (*http.ResponseWriter)(nil)) // substituir ResponseWriter com nosso ResponseWriter invólucro +} +~~~ + +### Servindo Arquivos Estáticos +Uma instância de [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) serve automaticamente arquivos estáticos do diretório "public" na raiz do seu servidor. +Você pode servir de mais diretórios, adicionando mais [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) handlers. +~~~ go +m.Use(martini.Static("assets")) // servindo os arquivos do diretório "assets" +~~~ + +## Middleware Handlers +Middleware Handlers ficam entre a solicitação HTTP e o roteador. Em essência, eles não são diferentes de qualquer outro Handler no Martini. Você pode adicionar um handler de middleware para a pilha assim: +~~~ go +m.Use(func() { + // faz algo com middleware +}) +~~~ + +Você pode ter o controle total sobre a pilha de middleware com a função `Handlers`. Isso irá substituir quaisquer manipuladores que foram previamente definidos: +~~~ go +m.Handlers( + Middleware1, + Middleware2, + Middleware3, +) +~~~ + +Middleware Handlers trabalham muito bem com princípios com logging, autorização, autenticação, sessão, gzipping, páginas de erros e uma série de outras operações que devem acontecer antes ou depois de uma solicitação HTTP: +~~~ go +// Valida uma chave de API +m.Use(func(res http.ResponseWriter, req *http.Request) { + if req.Header.Get("X-API-KEY") != "secret123" { + res.WriteHeader(http.StatusUnauthorized) + } +}) +~~~ + +### Next() +[Context.Next()](http://godoc.org/github.com/go-martini/martini#Context) é uma função opcional que Middleware Handlers podem chamar para aguardar a execução de outros Handlers. Isso funciona muito bem para operações que devem acontecer após uma requisição: +~~~ go +// log antes e depois do request +m.Use(func(c martini.Context, log *log.Logger){ + log.Println("antes do request") + + c.Next() + + log.Println("depois do request") +}) +~~~ + +## Martini Env + +Martini handlers fazem uso do `martini.Env`, uma variável global para fornecer funcionalidade especial para ambientes de desenvolvimento e ambientes de produção. É recomendado que a variável `MARTINI_ENV=production` seja definida quando a implementação estiver em um ambiente de produção. + +## FAQ + +### Onde posso encontrar o middleware X? + +Inicie sua busca nos projetos [martini-contrib](https://github.com/martini-contrib). Se ele não estiver lá não hesite em contactar um membro da equipe martini-contrib sobre como adicionar um novo repo para a organização. + +* [auth](https://github.com/martini-contrib/auth) - Handlers para autenticação. +* [binding](https://github.com/martini-contrib/binding) - Handler para mapeamento/validação de um request a estrutura. +* [gzip](https://github.com/martini-contrib/gzip) - Handler para adicionar compreção gzip para o requests +* [render](https://github.com/martini-contrib/render) - Handler que providencia uma rederização simples para JSON e templates HTML. +* [acceptlang](https://github.com/martini-contrib/acceptlang) - Handler para parsing do `Accept-Language` no header HTTP. +* [sessions](https://github.com/martini-contrib/sessions) - Handler que prove o serviço de sessão. +* [strip](https://github.com/martini-contrib/strip) - URL Prefix stripping. +* [method](https://github.com/martini-contrib/method) - HTTP método de substituição via cabeçalho ou campos do formulário. +* [secure](https://github.com/martini-contrib/secure) - Implementa rapidamente itens de segurança. +* [encoder](https://github.com/martini-contrib/encoder) - Serviço Encoder para renderização de dados em vários formatos e negociação de conteúdo. +* [cors](https://github.com/martini-contrib/cors) - Handler que habilita suporte a CORS. +* [oauth2](https://github.com/martini-contrib/oauth2) - Handler que prove sistema de login OAuth 2.0 para aplicações Martini. Google Sign-in, Facebook Connect e Github login são suportados. + +### Como faço para integrar com os servidores existentes? + +Uma instância do Martini implementa `http.Handler`, de modo que pode ser facilmente utilizado para servir sub-rotas e diretórios +em servidores Go existentes. Por exemplo, este é um aplicativo Martini trabalhando para Google App Engine: + +~~~ go +package hello + +import ( + "net/http" + "github.com/go-martini/martini" +) + +func init() { + m := martini.Classic() + m.Get("/", func() string { + return "Hello world!" + }) + http.Handle("/", m) +} +~~~ + +### Como faço para alterar a porta/host? + +A função `Run` do Martini olha para as variáveis PORT e HOST para utilizá-las. Caso contrário o Martini assume como padrão localhost:3000. +Para ter mais flexibilidade sobre a porta e host use a função `martini.RunOnAddr`. + +~~~ go + m := martini.Classic() + // ... + log.Fatal(m.RunOnAddr(":8080")) +~~~ + +### Servidor com autoreload? + +[gin](https://github.com/codegangsta/gin) e [fresh](https://github.com/pilu/fresh) são aplicativos para autoreload do Martini. + +## Contribuindo +Martini é feito para ser mantido pequeno e limpo. A maioria das contribuições devem ser feitas no repositório [martini-contrib](https://github.com/martini-contrib). Se quiser contribuir com o core do Martini fique livre para fazer um Pull Request. + +## Sobre + +Inspirado por [express](https://github.com/visionmedia/express) e [sinatra](https://github.com/sinatra/sinatra) + +Martini is obsessively designed by none other than the [Code Gangsta](http://codegangsta.io/) diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_ru_RU.md b/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_ru_RU.md new file mode 100644 index 0000000..2cf00ea --- /dev/null +++ b/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_ru_RU.md @@ -0,0 +1,354 @@ +# Martini [![wercker status](https://app.wercker.com/status/9b7dbc6e2654b604cd694d191c3d5487/s/master "wercker status")](https://app.wercker.com/project/bykey/9b7dbc6e2654b604cd694d191c3d5487)[![GoDoc](https://godoc.org/github.com/go-martini/martini?status.png)](http://godoc.org/github.com/go-martini/martini) + +Martini - мощный пакет для быстрой разработки веб приложений и сервисов на Golang. + +## Начало работы + +После установки Golang и настройки вашего [GOPATH](http://golang.org/doc/code.html#GOPATH), создайте ваш первый `.go` файл. Назовем его `server.go`. + +~~~ go +package main + +import "github.com/go-martini/martini" + +func main() { + m := martini.Classic() + m.Get("/", func() string { + return "Hello world!" + }) + m.Run() +} +~~~ + +Потом установите пакет Martini (требуется **go 1.1** или выше): +~~~ +go get github.com/go-martini/martini +~~~ + +Потом запустите ваш сервер: +~~~ +go run server.go +~~~ + +И вы получите запущенный Martini сервер на `localhost:3000`. + +## Помощь + +Присоединяйтесь к [рассылке](https://groups.google.com/forum/#!forum/martini-go) + +Смотрите [демо видео](http://martini.codegangsta.io/#demo) + +Задавайте вопросы на Stackoverflow используя [тэг martini](http://stackoverflow.com/questions/tagged/martini) + +GoDoc [документация](http://godoc.org/github.com/go-martini/martini) + + +## Возможности +* Очень прост в использовании. +* Ненавязчивый дизайн. +* Хорошо сочетается с другими пакетами. +* Потрясающий роутинг и маршрутизация. +* Модульный дизайн - легко добавлять и исключать функциональность. +* Большое количество хороших обработчиков/middlewares, готовых к использованию. +* Отличный набор 'из коробки'. +* **Полностью совместим с интерфейсом [http.HandlerFunc](http://godoc.org/net/http#HandlerFunc).** + +## Больше Middleware +Смотрите репозитории организации [martini-contrib](https://github.com/martini-contrib), для большей информации о функциональности и middleware. + +## Содержание +* [Classic Martini](#classic-martini) + * [Обработчики](#%D0%9E%D0%B1%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D1%87%D0%B8%D0%BA%D0%B8) + * [Роутинг](#%D0%A0%D0%BE%D1%83%D1%82%D0%B8%D0%BD%D0%B3) + * [Сервисы](#%D0%A1%D0%B5%D1%80%D0%B2%D0%B8%D1%81%D1%8B) + * [Отдача статических файлов](#%D0%9E%D1%82%D0%B4%D0%B0%D1%87%D0%B0-%D1%81%D1%82%D0%B0%D1%82%D0%B8%D1%87%D0%B5%D1%81%D0%BA%D0%B8%D1%85-%D1%84%D0%B0%D0%B9%D0%BB%D0%BE%D0%B2) +* [Middleware обработчики](#middleware-%D0%9E%D0%B1%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D1%87%D0%B8%D0%BA%D0%B8) + * [Next()](#next) +* [Окружение](#%D0%9E%D0%BA%D1%80%D1%83%D0%B6%D0%B5%D0%BD%D0%B8%D0%B5) +* [FAQ](#faq) + +## Classic Martini +Для быстрого старта [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) предлагает несколько предустановок, это используется для большинства веб приложений: +~~~ go + m := martini.Classic() + // ... middleware и роутинг здесь + m.Run() +~~~ + +Ниже представлена уже подключенная [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) функциональность: + + * Request/Response логгирование - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger) + * Panic Recovery - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery) + * Отдача статики - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) + * Роутинг - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router) + +### Обработчики +Обработчики - это сердце и душа Martini. Обработчик - любая функция, которая может быть вызвана: +~~~ go +m.Get("/", func() { + println("hello world") +}) +~~~ + +#### Возвращаемые значения +Если обработчик возвращает что либо, Martini запишет это как результат в текущий [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter), в виде строки: +~~~ go +m.Get("/", func() string { + return "hello world" // HTTP 200 : "hello world" +}) +~~~ + +Так же вы можете возвращать код статуса, опционально: +~~~ go +m.Get("/", func() (int, string) { + return 418, "i'm a teapot" // HTTP 418 : "i'm a teapot" +}) +~~~ + +#### Внедрение сервисов +Обработчики вызываются посредством рефлексии. Martini использует **Внедрение зависимости** для разрешения зависимостей в списке аргумента обработчика. **Это делает Martini полностью совместимым с интерфейсом `http.HandlerFunc`.** + +Если вы добавите аргументы в ваш обработчик, Martini будет пытаться найти этот список сервисов за счет проверки типов(type assertion): +~~~ go +m.Get("/", func(res http.ResponseWriter, req *http.Request) { // res и req будут внедрены Martini + res.WriteHeader(200) // HTTP 200 +}) +~~~ + +Следующие сервисы включены в [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic): + + * [*log.Logger](http://godoc.org/log#Logger) - Глобальный логгер для Martini. + * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http request контекст. + * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string` именованых аргументов из роутера. + * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Хэлпер роутеров. + * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http Response writer интерфейс. + * [*http.Request](http://godoc.org/net/http/#Request) - http Request. + +### Роутинг +В Martini, роут - это объединенные паттерн и HTTP метод. +Каждый роут может принимать один или несколько обработчиков: +~~~ go +m.Get("/", func() { + // показать что-то +}) + +m.Patch("/", func() { + // обновить что-то +}) + +m.Post("/", func() { + // создать что-то +}) + +m.Put("/", func() { + // изменить что-то +}) + +m.Delete("/", func() { + // удалить что-то +}) + +m.Options("/", func() { + // http опции +}) + +m.NotFound(func() { + // обработчик 404 +}) +~~~ + +Роуты могут сопоставляться с http запросами только в порядке объявления. Вызывается первый роут, который соответствует запросу. + +Паттерны роутов могут включать именованные параметры, доступные через [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) сервис: +~~~ go +m.Get("/hello/:name", func(params martini.Params) string { + return "Hello " + params["name"] +}) +~~~ + +Роуты можно объявлять как glob'ы: +~~~ go +m.Get("/hello/**", func(params martini.Params) string { + return "Hello " + params["_1"] +}) +~~~ + +Так же могут использоваться регулярные выражения: +~~~go +m.Get("/hello/(?P[a-zA-Z]+)", func(params martini.Params) string { + return fmt.Sprintf ("Hello %s", params["name"]) +}) +~~~ +Синтаксис регулярных выражений смотрите [Go documentation](http://golang.org/pkg/regexp/syntax/). + +Обработчики роутов так же могут быть выстроены в стек, друг перед другом. Это очень удобно для таких задач как авторизация и аутентификация: +~~~ go +m.Get("/secret", authorize, func() { + // будет вызываться, в случае если authorize ничего не записал в ответ +}) +~~~ + +Роуты так же могут быть объединены в группы, посредством метода Group: +~~~ go +m.Group("/books", func(r martini.Router) { + r.Get("/:id", GetBooks) + r.Post("/new", NewBook) + r.Put("/update/:id", UpdateBook) + r.Delete("/delete/:id", DeleteBook) +}) +~~~ + +Так же как вы можете добавить middleware для обычного обработчика, вы можете добавить middleware и для группы. +~~~ go +m.Group("/books", func(r martini.Router) { + r.Get("/:id", GetBooks) + r.Post("/new", NewBook) + r.Put("/update/:id", UpdateBook) + r.Delete("/delete/:id", DeleteBook) +}, MyMiddleware1, MyMiddleware2) +~~~ + +### Сервисы +Сервисы - это объекты, которые доступны для внедрения в аргументы обработчиков. Вы можете замапить сервисы на уровне всего приложения либо на уровне запроса. + +#### Глобальный маппинг +Экземпляр Martini реализует интерфейс inject.Injector, поэтому замаппить сервис легко: +~~~ go +db := &MyDatabase{} +m := martini.Classic() +m.Map(db) // сервис будет доступен для всех обработчиков как *MyDatabase +// ... +m.Run() +~~~ + +#### Маппинг уровня запроса +Маппинг на уровне запроса можно сделать при помощи [martini.Context](http://godoc.org/github.com/go-martini/martini#Context): +~~~ go +func MyCustomLoggerHandler(c martini.Context, req *http.Request) { + logger := &MyCustomLogger{req} + c.Map(logger) // как *MyCustomLogger +} +~~~ + +#### Маппинг на определенный интерфейс +Одна из мощных частей, того что касается сервисов - маппинг сервиса на определенный интерфейс. Например, если вы хотите переопределить [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) объектом, который оборачивает и добавляет новые операции, вы можете написать следующее: +~~~ go +func WrapResponseWriter(res http.ResponseWriter, c martini.Context) { + rw := NewSpecialResponseWriter(res) + c.MapTo(rw, (*http.ResponseWriter)(nil)) // переопределить ResponseWriter нашей оберткой +} +~~~ + +### Отдача статических файлов +Экземпляр [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) автоматически отдает статические файлы из директории "public" в корне, рядом с вашим файлом `server.go`. +Вы можете добавить еще директорий, добавляя [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) обработчики. +~~~ go +m.Use(martini.Static("assets")) // отдача файлов из "assets" директории +~~~ + +## Middleware Обработчики +Middleware обработчики находятся между входящим http запросом и роутом. По сути, они ничем не отличаются от любого другого обработчика Martini. Вы можете добавить middleware обработчик в стек следующим образом: +~~~ go +m.Use(func() { + // делать какую то middleware работу +}) +~~~ + +Для полного контроля над стеком middleware существует метод `Handlers`. В этом примере будут заменены все обработчики, которые были до этого: +~~~ go +m.Handlers( + Middleware1, + Middleware2, + Middleware3, +) +~~~ + +Middleware обработчики очень хорошо работают для таких вещей как логгирование, авторизация, аутентификация, сессии, сжатие, страницы ошибок и любые другие операции, которые должны быть выполнены до или после http запроса: +~~~ go +// валидация api ключа +m.Use(func(res http.ResponseWriter, req *http.Request) { + if req.Header.Get("X-API-KEY") != "secret123" { + res.WriteHeader(http.StatusUnauthorized) + } +}) +~~~ + +### Next() +[Context.Next()](http://godoc.org/github.com/go-martini/martini#Context) опциональная функция, которая может быть вызвана в Middleware обработчике, для выхода из контекста, и возврата в него, после вызова всего стека обработчиков. Это можно использовать для операций, которые должны быть выполнены после http запроса: +~~~ go +// логгирование до и после http запроса +m.Use(func(c martini.Context, log *log.Logger){ + log.Println("до запроса") + + c.Next() + + log.Println("после запроса") +}) +~~~ + +## Окружение +Некоторые Martini обработчики используют глобальную переменную `martini.Env` для того, чтоб предоставить специальную функциональность для девелопмент и продакшн окружения. Рекомендуется устанавливать `MARTINI_ENV=production`, когда вы деплоите приложение на продакшн. + +## FAQ + +### Где найти готовые middleware? + +Начните поиск с [martini-contrib](https://github.com/martini-contrib) проектов. Если нет ничего подходящего, без колебаний пишите члену команды martini-contrib о добавлении нового репозитория в организацию. + +* [auth](https://github.com/martini-contrib/auth) - Обработчики для аутентификации. +* [binding](https://github.com/martini-contrib/binding) - Обработчик для маппинга/валидации сырого запроса в определенную структуру(struct). +* [gzip](https://github.com/martini-contrib/gzip) - Обработчик, добавляющий gzip сжатие для запросов. +* [render](https://github.com/martini-contrib/render) - Обработчик, которые предоставляет сервис для легкого рендеринга JSON и HTML шаблонов. +* [acceptlang](https://github.com/martini-contrib/acceptlang) - Обработчик для парсинга `Accept-Language` HTTP заголовка. +* [sessions](https://github.com/martini-contrib/sessions) - Сервис сессий. +* [strip](https://github.com/martini-contrib/strip) - Удаление префиксов из URL. +* [method](https://github.com/martini-contrib/method) - Подмена HTTP метода через заголовок. +* [secure](https://github.com/martini-contrib/secure) - Набор для безопасности. +* [encoder](https://github.com/martini-contrib/encoder) - Сервис для представления данных в нескольких форматах и взаимодействия с контентом. +* [cors](https://github.com/martini-contrib/cors) - Поддержка CORS. +* [oauth2](https://github.com/martini-contrib/oauth2) - Обработчик, предоставляющий OAuth 2.0 логин для Martini приложений. Вход через Google, Facebook и через Github поддерживаются. + +### Как интегрироваться с существуюшими серверами? + +Экземпляр Martini реализует интерфейс `http.Handler`, потому - это очень просто использовать вместе с существующим Go проектом. Например, это работает для платформы Google App Engine: +~~~ go +package hello + +import ( + "net/http" + "github.com/go-martini/martini" +) + +func init() { + m := martini.Classic() + m.Get("/", func() string { + return "Hello world!" + }) + http.Handle("/", m) +} +~~~ + +### Как изменить порт и/или хост? +Функция `Run` смотрит переменные окружиения PORT и HOST, и использует их. +В противном случае Martini по умолчанию будет использовать `localhost:3000`. +Для большей гибкости используйте вместо этого функцию `martini.RunOnAddr`. + +~~~ go + m := martini.Classic() + // ... + log.Fatal(m.RunOnAddr(":8080")) +~~~ + +### Живая перезагрузка кода? + +[gin](https://github.com/codegangsta/gin) и [fresh](https://github.com/pilu/fresh) могут работать вместе с Martini. + +## Вклад в обшее дело + +Подразумевается что Martini чистый и маленький. Большинство улучшений должны быть в организации [martini-contrib](https://github.com/martini-contrib). Но если вы хотите улучшить ядро Martini, отправляйте пулл реквесты. + +## О проекте + +Вдохновлен [express](https://github.com/visionmedia/express) и [sinatra](https://github.com/sinatra/sinatra) + +Martini создан [Code Gangsta](http://codegangsta.io/) diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_tr_TR.md b/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_tr_TR.md new file mode 100644 index 0000000..9221b34 --- /dev/null +++ b/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_tr_TR.md @@ -0,0 +1,387 @@ +# Martini [![wercker status](https://app.wercker.com/status/9b7dbc6e2654b604cd694d191c3d5487/s/master "wercker status")](https://app.wercker.com/project/bykey/9b7dbc6e2654b604cd694d191c3d5487)[![GoDoc](https://godoc.org/github.com/go-martini/martini?status.png)](http://godoc.org/github.com/go-martini/martini) + +Martini Go dilinde hızlı ve modüler web uygulamaları ve servisleri için güçlü bir pakettir. + + +## Başlangıç + +Go kurulumu ve [GOPATH](http://golang.org/doc/code.html#GOPATH) ayarını yaptıktan sonra, ilk `.go` uzantılı dosyamızı oluşturuyoruz. Bu oluşturduğumuz dosyayı `server.go` olarak adlandıracağız. + +~~~ go +package main + +import "github.com/go-martini/martini" + +func main() { + m := martini.Classic() + m.Get("/", func() string { + return "Hello world!" + }) + m.Run() +} +~~~ + +Martini paketini kurduktan sonra (**go 1.1** ve daha üst go sürümü gerekmektedir.): + +~~~ +go get github.com/go-martini/martini +~~~ + +Daha sonra server'ımızı çalıştırıyoruz: + +~~~ +go run server.go +~~~ + +Şimdi elimizde çalışan bir adet Martini webserver `localhost:3000` adresinde bulunmaktadır. + + +## Yardım Almak İçin + +[Mail Listesi](https://groups.google.com/forum/#!forum/martini-go) + +[Örnek Video](http://martini.codegangsta.io/#demo) + +Stackoverflow üzerinde [martini etiketine](http://stackoverflow.com/questions/tagged/martini) sahip sorular + +[GO Diline ait Dökümantasyonlar](http://godoc.org/github.com/go-martini/martini) + + +## Özellikler +* Oldukça basit bir kullanıma sahip. +* Kısıtlama yok. +* Golang paketleri ile rahat bir şekilde kullanılıyor. +* Müthiş bir şekilde path eşleştirme ve yönlendirme. +* Modüler dizayn - Kolay eklenen fonksiyonellik. +* handlers/middlewares kullanımı çok iyi. +* Büyük 'kutu dışarı' özellik seti. +* **[http.HandlerFunc](http://godoc.org/net/http#HandlerFunc) arayüzü ile tam uyumludur.** +* Varsayılan belgelendirme işlemleri (örnek olarak, AngularJS uygulamalarının HTML5 modunda servis edilmesi). + +## Daha Fazla Middleware(Ara Katman) + +Daha fazla ara katman ve fonksiyonellik için, şu repoları inceleyin [martini-contrib](https://github.com/martini-contrib). + +## Tablo İçerikleri +* [Classic Martini](#classic-martini) + * [İşleyiciler / Handlers](#handlers) + * [Yönlendirmeler / Routing](#routing) + * [Servisler](#services) + * [Statik Dosyaların Sunumu](#serving-static-files) +* [Katman İşleyiciler / Middleware Handlers](#middleware-handlers) + * [Next()](#next) +* [Martini Env](#martini-env) +* [FAQ](#faq) + +## Classic Martini +[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) hızlıca projeyi çalıştırır ve çoğu web uygulaması için iyi çalışan bazı makul varsayılanlar sağlar: + +~~~ go + m := martini.Classic() + // ... middleware and routing goes here + m.Run() +~~~ + +[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) aşağıdaki bazı fonsiyonelleri otomatik olarak çeker: + + * İstek/Yanıt Kayıtları (Request/Response Logging) - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger) + * Hataların Düzeltilmesi (Panic Recovery) - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery) + * Statik Dosyaların Sunumu (Static File serving) - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) + * Yönlendirmeler (Routing) - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router) + +### İşleyiciler (Handlers) +İşleyiciler Martini'nin ruhu ve kalbidir. Bir işleyici temel olarak her türlü fonksiyonu çağırabilir: + +~~~ go +m.Get("/", func() { + println("hello world") +}) +~~~ + +#### Geriye Dönen Değerler + +Eğer bir işleyici geriye bir şey dönderiyorsa, Martini string olarak sonucu [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) ile yazacaktır: + +~~~ go +m.Get("/", func() string { + return "hello world" // HTTP 200 : "hello world" +}) +~~~ + +Ayrıca isteğe bağlı bir durum kodu dönderebilir: +~~~ go +m.Get("/", func() (int, string) { + return 418, "i'm a teapot" // HTTP 418 : "i'm a teapot" +}) +~~~ + +#### Service Injection +İşlemciler yansıma yoluyla çağrılır. Martini *Dependency Injection* kullanarak arguman listesindeki bağımlıkları giderir.**Bu sayede Martini go programlama dilinin `http.HandlerFunc` arayüzü ile tamamen uyumlu hale getirilir.** + +Eğer işleyiciye bir arguman eklersek, Martini "type assertion" ile servis listesinde arayacak ve bağımlılıkları çözmek için girişimde bulunacaktır: + +~~~ go +m.Get("/", func(res http.ResponseWriter, req *http.Request) { // res and req are injected by Martini + res.WriteHeader(200) // HTTP 200 +}) +~~~ + +Aşağıdaki servislerin içerikleri + +[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic): + * [*log.Logger](http://godoc.org/log#Logger) - Martini için Global loglayıcı. + * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http request içereği. + * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string` ile yol eşleme tarafından params olarak isimlendirilen yapılar bulundu. + * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Yönledirilme için yardımcı olan yapıdır. + * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http yanıtlarını yazacak olan yapıdır. + * [*http.Request](http://godoc.org/net/http/#Request) - http Request(http isteği yapar). + +### Yönlendirme - Routing +Martini'de bir yol HTTP metodu URL-matching pattern'i ile eşleştirilir. +Her bir yol bir veya daha fazla işleyici metod alabilir: +~~~ go +m.Get("/", func() { + // show something +}) + +m.Patch("/", func() { + // update something +}) + +m.Post("/", func() { + // create something +}) + +m.Put("/", func() { + // replace something +}) + +m.Delete("/", func() { + // destroy something +}) + +m.Options("/", func() { + // http options +}) + +m.NotFound(func() { + // handle 404 +}) +~~~ + +Yollar sırayla tanımlandıkları şekilde eşleştirilir.Request ile eşleşen ilk rota çağrılır. + +Yol patternleri [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) servisi tarafından adlandırılan parametreleri içerebilir: +~~~ go +m.Get("/hello/:name", func(params martini.Params) string { + return "Hello " + params["name"] +}) +~~~ + +Yollar globaller ile eşleşebilir: +~~~ go +m.Get("/hello/**", func(params martini.Params) string { + return "Hello " + params["_1"] +}) +~~~ + +Düzenli ifadeler kullanılabilir: +~~~go +m.Get("/hello/(?P[a-zA-Z]+)", func(params martini.Params) string { + return fmt.Sprintf ("Hello %s", params["name"]) +}) +~~~ +Düzenli ifadeler hakkında daha fazla bilgiyi [Go dökümanlarından](http://golang.org/pkg/regexp/syntax/) elde edebilirsiniz. + +Yol işleyicileri birbirlerinin üstüne istiflenebilir. Bu durum doğrulama ve yetkilendirme(authentication and authorization) işlemleri için iyi bir yöntemdir: +~~~ go +m.Get("/secret", authorize, func() { + // this will execute as long as authorize doesn't write a response +}) +~~~ + +Yol grupları Grup metodlar kullanılarak eklenebilir. +~~~ go +m.Group("/books", func(r martini.Router) { + r.Get("/:id", GetBooks) + r.Post("/new", NewBook) + r.Put("/update/:id", UpdateBook) + r.Delete("/delete/:id", DeleteBook) +}) +~~~ + +Tıpkı ara katmanların işleyiciler için bazı ara katman işlemlerini atlayabileceği gibi gruplar içinde atlayabilir. +~~~ go +m.Group("/books", func(r martini.Router) { + r.Get("/:id", GetBooks) + r.Post("/new", NewBook) + r.Put("/update/:id", UpdateBook) + r.Delete("/delete/:id", DeleteBook) +}, MyMiddleware1, MyMiddleware2) +~~~ + +### Servisler + +Servisler işleyicilerin arguman listesine enjekte edilecek kullanılabilir nesnelerdir. İstenildiği taktirde bir servis *Global* ve *Request* seviyesinde eşlenebilir. + +#### Global Eşleme - Global Mapping + +Bir martini örneği(instance) projeye enjekte edilir. +A Martini instance implements the inject.Enjekte arayüzü, çok kolay bir şekilde servis eşlemesi yapar: +~~~ go +db := &MyDatabase{} +m := martini.Classic() +m.Map(db) // the service will be available to all handlers as *MyDatabase +// ... +m.Run() +~~~ + +#### Request-Level Mapping +Request düzeyinde eşleme yapmak üzere işleyici [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) ile oluşturulabilir: +~~~ go +func MyCustomLoggerHandler(c martini.Context, req *http.Request) { + logger := &MyCustomLogger{req} + c.Map(logger) // mapped as *MyCustomLogger +} +~~~ + +#### Arayüz Eşleme Değerleri +Servisler hakkındaki en güçlü şeylerden birisi bir arabirim ile bir servis eşleşmektedir. Örneğin, istenirse [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter) yapısı paketlenmiş ve ekstra işlemleri gerçekleştirilen bir nesne ile override edilebilir. Şu işleyici yazılabilir: + +~~~ go +func WrapResponseWriter(res http.ResponseWriter, c martini.Context) { + rw := NewSpecialResponseWriter(res) + c.MapTo(rw, (*http.ResponseWriter)(nil)) // override ResponseWriter with our wrapper ResponseWriter +} +~~~ + +### Statik Dosyaların Sunumu + +[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) örneği otomatik olarak statik dosyaları serverda root içinde yer alan "public" dizininden servis edilir. + +Eğer istenirse daha fazla [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) işleyicisi eklenerek daha fazla dizin servis edilebilir. +~~~ go +m.Use(martini.Static("assets")) // serve from the "assets" directory as well +~~~ + +#### Standart Dökümanların Sunulması - Serving a Default Document + +Eğer istenilen URL bulunamaz ise özel bir URL dönderilebilir. Ayrıca bir dışlama(exclusion) ön eki ile bazı URL'ler göz ardı edilir. Bu durum statik dosyaların ve ilave işleyiciler için kullanışlıdır(Örneğin, REST API). Bunu yaparken, bu işlem ile NotFound zincirinin bir parçası olan statik işleyiciyi tanımlamak kolaydır. + +Herhangi bir URL isteği bir local dosya ile eşleşmediği ve `/api/v` ile başlamadığı zaman aşağıdaki örnek `/index.html` dosyasını sonuç olarak geriye döndürecektir. +~~~ go +static := martini.Static("assets", martini.StaticOptions{Fallback: "/index.html", Exclude: "/api/v"}) +m.NotFound(static, http.NotFound) +~~~ + +## Ara Katman İşleyicileri +Ara katmana ait işleyiciler http isteği ve yönlendirici arasında bulunmaktadır. Özünde onlar diğer Martini işleyicilerinden farklı değildirler. İstenildiği taktirde bir yığına ara katman işleyicisi şu şekilde eklenebilir: +~~~ go +m.Use(func() { + // do some middleware stuff +}) +~~~ + +`Handlers` fonksiyonu ile ara katman yığını üzerinde tüm kontrole sahip olunabilir. Bu daha önceden ayarlanmış herhangi bir işleyicinin yerini alacaktır: +~~~ go +m.Handlers( + Middleware1, + Middleware2, + Middleware3, +) +~~~ + +Orta katman işleyicileri loglama, giriş , yetkilendirme , sessionlar, sıkıştırma(gzipping) , hata sayfaları ve HTTP isteklerinden önce ve sonra herhangi bir olay sonucu oluşan durumlar için gerçekten iyi bir yapıya sahiptir: + +~~~ go +// validate an api key +m.Use(func(res http.ResponseWriter, req *http.Request) { + if req.Header.Get("X-API-KEY") != "secret123" { + res.WriteHeader(http.StatusUnauthorized) + } +}) +~~~ + +### Next() +[Context.Next()](http://godoc.org/github.com/go-martini/martini#Context) orta katman işleyicilerinin diğer işleyiciler yok edilmeden çağrılmasını sağlayan opsiyonel bir fonksiyondur.Bu iş http işlemlerinden sonra gerçekleşecek işlemler için gerçekten iyidir: +~~~ go +// log before and after a request +m.Use(func(c martini.Context, log *log.Logger){ + log.Println("before a request") + + c.Next() + + log.Println("after a request") +}) +~~~ + +## Martini Env + +Bazı Martini işleyicileri `martini.Env` yapısının özel fonksiyonlarını kullanmak için geliştirici ortamları, üretici ortamları vs. kullanır.Bu üretim ortamına Martini sunucu kurulurken `MARTINI_ENV=production` şeklinde ortam değişkeninin ayarlanması gerekir. + +## FAQ + +### Ara Katmanda X'i Nerede Bulurum? + +[martini-contrib](https://github.com/martini-contrib) projelerine bakarak başlayın. Eğer aradığınız şey orada mevcut değil ise yeni bir repo eklemek için martini-contrib takım üyeleri ile iletişime geçin. + +* [auth](https://github.com/martini-contrib/auth) - Kimlik doğrulama için işleyiciler. +* [binding](https://github.com/martini-contrib/binding) - Mapping/Validating yapısı içinde ham request'i doğrulamak için kullanılan işleyici(handler) +* [gzip](https://github.com/martini-contrib/gzip) - İstekleri gzip sıkışıtırıp eklemek için kullanılan işleyici +* [render](https://github.com/martini-contrib/render) - Kolay bir şekilde JSON ve HTML şablonları oluşturmak için kullanılan işleyici. +* [acceptlang](https://github.com/martini-contrib/acceptlang) - `Kabul edilen dile` göre HTTP başlığını oluşturmak için kullanılan işleyici. +* [sessions](https://github.com/martini-contrib/sessions) - Oturum hizmeti vermek için kullanılır. +* [strip](https://github.com/martini-contrib/strip) - İşleyicilere gitmeden önce URL'ye ait ön şeriti değiştirme işlemini yapar. +* [method](https://github.com/martini-contrib/method) - Formlar ve başlık için http metodunu override eder. +* [secure](https://github.com/martini-contrib/secure) - Birkaç hızlı güvenlik uygulaması ile kazanımda bulundurur. +* [encoder](https://github.com/martini-contrib/encoder) - Encoder servis veri işlemleri için çeşitli format ve içerik sağlar. +* [cors](https://github.com/martini-contrib/cors) - İşleyicilerin CORS desteği bulunur. +* [oauth2](https://github.com/martini-contrib/oauth2) - İşleyiciler OAuth 2.0 için Martini uygulamalarına giriş sağlar. Google , Facebook ve Github için desteği mevcuttur. +* [vauth](https://github.com/rafecolton/vauth) - Webhook için giriş izni sağlar. (şimdilik sadece GitHub ve TravisCI ile) + +### Mevcut Sunucular ile Nasıl Entegre Edilir? + +Bir martini örneği `http.Handler`'ı projeye dahil eder, bu sayde kolay bir şekilde mevcut olan Go sunucularında bulunan alt ağaçlarda kullanabilir. Örnek olarak, bu olay Google App Engine için hazırlanmış Martini uygulamalarında kullanılmaktadır: + +~~~ go +package hello + +import ( + "net/http" + "github.com/go-martini/martini" +) + +func init() { + m := martini.Classic() + m.Get("/", func() string { + return "Hello world!" + }) + http.Handle("/", m) +} +~~~ + +### port/hostu nasıl değiştiririm? + +Martini'ye ait `Run` fonksiyounu PORT ve HOST'a ait ortam değişkenlerini arar ve bunları kullanır. Aksi taktirde standart olarak localhost:3000 adresini port ve host olarak kullanacaktır. + +Port ve host için daha fazla esneklik isteniyorsa `martini.RunOnAddr` fonksiyonunu kullanın. + +~~~ go + m := martini.Classic() + // ... + log.Fatal(m.RunOnAddr(":8080")) +~~~ + +### Anlık Kod Yüklemesi? + +[gin](https://github.com/codegangsta/gin) ve [fresh](https://github.com/pilu/fresh) anlık kod yüklemeleri yapan martini uygulamalarıdır. + +## Katkıda Bulunmak +Martini'nin temiz ve düzenli olaması gerekiyordu. +Martini is meant to be kept tiny and clean. Tüm kullanıcılar katkı yapmak için [martini-contrib](https://github.com/martini-contrib) organizasyonunda yer alan repoları bitirmelidirler. Eğer martini core için katkıda bulunacaksanız fork işlemini yaparak başlayabilirsiniz. + +## Hakkında + +[express](https://github.com/visionmedia/express) ve [sinatra](https://github.com/sinatra/sinatra) projelerinden esinlenmiştir. + +Martini [Code Gangsta](http://codegangsta.io/) tarafından tasarlanılmıştır. diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_zh_cn.md b/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_zh_cn.md new file mode 100644 index 0000000..3fa2c1b --- /dev/null +++ b/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_zh_cn.md @@ -0,0 +1,315 @@ +# Martini [![wercker status](https://app.wercker.com/status/174bef7e3c999e103cacfe2770102266 "wercker status")](https://app.wercker.com/project/bykey/174bef7e3c999e103cacfe2770102266) [![GoDoc](https://godoc.org/github.com/go-martini/martini?status.png)](http://godoc.org/github.com/go-martini/martini) + +Martini是一个强大为了编写模块化Web应用而生的GO语言框架. + +## 第一个应用 + +在你安装了GO语言和设置了你的[GOPATH](http://golang.org/doc/code.html#GOPATH)之后, 创建你的自己的`.go`文件, 这里我们假设它的名字叫做 `server.go`. + +~~~ go +package main + +import "github.com/go-martini/martini" + +func main() { + m := martini.Classic() + m.Get("/", func() string { + return "Hello world!" + }) + m.Run() +} +~~~ + +然后安装Martini的包. (注意Martini需要Go语言1.1或者以上的版本支持): +~~~ +go get github.com/go-martini/martini +~~~ + +最后运行你的服务: +~~~ +go run server.go +~~~ + +这时你将会有一个Martini的服务监听了, 地址是: `localhost:3000`. + +## 获得帮助 + +请加入: [邮件列表](https://groups.google.com/forum/#!forum/martini-go) + +或者可以查看在线演示地址: [演示视频](http://martini.codegangsta.io/#demo) + +## 功能列表 +* 使用极其简单. +* 无侵入式的设计. +* 很好的与其他的Go语言包协同使用. +* 超赞的路径匹配和路由. +* 模块化的设计 - 容易插入功能件,也容易将其拔出来. +* 已有很多的中间件可以直接使用. +* 框架内已拥有很好的开箱即用的功能支持. +* **完全兼容[http.HandlerFunc](http://godoc.org/net/http#HandlerFunc)接口.** + +## 更多中间件 +更多的中间件和功能组件, 请查看代码仓库: [martini-contrib](https://github.com/martini-contrib). + +## 目录 +* [核心 Martini](#classic-martini) + * [处理器](#handlers) + * [路由](#routing) + * [服务](#services) + * [服务静态文件](#serving-static-files) +* [中间件处理器](#middleware-handlers) + * [Next()](#next) +* [常见问答](#faq) + +## 核心 Martini +为了更快速的启用Martini, [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) 提供了一些默认的方便Web开发的工具: +~~~ go + m := martini.Classic() + // ... middleware and routing goes here + m.Run() +~~~ + +下面是Martini核心已经包含的功能 [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic): + * Request/Response Logging (请求/响应日志) - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger) + * Panic Recovery (容错) - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery) + * Static File serving (静态文件服务) - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) + * Routing (路由) - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router) + +### 处理器 +处理器是Martini的灵魂和核心所在. 一个处理器基本上可以是任何的函数: +~~~ go +m.Get("/", func() { + println("hello world") +}) +~~~ + +#### 返回值 +当一个处理器返回结果的时候, Martini将会把返回值作为字符串写入到当前的[http.ResponseWriter](http://godoc.org/net/http#ResponseWriter)里面: +~~~ go +m.Get("/", func() string { + return "hello world" // HTTP 200 : "hello world" +}) +~~~ + +另外你也可以选择性的返回多一个状态码: +~~~ go +m.Get("/", func() (int, string) { + return 418, "i'm a teapot" // HTTP 418 : "i'm a teapot" +}) +~~~ + +#### 服务的注入 +处理器是通过反射来调用的. Martini 通过*Dependency Injection* *(依赖注入)* 来为处理器注入参数列表. **这样使得Martini与Go语言的`http.HandlerFunc`接口完全兼容.** + +如果你加入一个参数到你的处理器, Martini将会搜索它参数列表中的服务,并且通过类型判断来解决依赖关系: +~~~ go +m.Get("/", func(res http.ResponseWriter, req *http.Request) { // res 和 req 是通过Martini注入的 + res.WriteHeader(200) // HTTP 200 +}) +~~~ + +下面的这些服务已经被包含在核心Martini中: [martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic): + * [*log.Logger](http://godoc.org/log#Logger) - Martini的全局日志. + * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http request context (请求上下文). + * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string` of named params found by route matching. (名字和参数键值对的参数列表) + * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Route helper service. (路由协助处理) + * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http Response writer interface. (响应结果的流接口) + * [*http.Request](http://godoc.org/net/http/#Request) - http Request. (http请求) + +### 路由 +在Martini中, 路由是一个HTTP方法配对一个URL匹配模型. 每一个路由可以对应一个或多个处理器方法: +~~~ go +m.Get("/", func() { + // 显示 +}) + +m.Patch("/", func() { + // 更新 +}) + +m.Post("/", func() { + // 创建 +}) + +m.Put("/", func() { + // 替换 +}) + +m.Delete("/", func() { + // 删除 +}) + +m.Options("/", func() { + // http 选项 +}) + +m.NotFound(func() { + // 处理 404 +}) +~~~ + +路由匹配的顺序是按照他们被定义的顺序执行的. 最先被定义的路由将会首先被用户请求匹配并调用. + +路由模型可能包含参数列表, 可以通过[martini.Params](http://godoc.org/github.com/go-martini/martini#Params)服务来获取: +~~~ go +m.Get("/hello/:name", func(params martini.Params) string { + return "Hello " + params["name"] +}) +~~~ + +路由匹配可以通过正则表达式或者glob的形式: +~~~ go +m.Get("/hello/**", func(params martini.Params) string { + return "Hello " + params["_1"] +}) +~~~ + +路由处理器可以被相互叠加使用, 例如很有用的地方可以是在验证和授权的时候: +~~~ go +m.Get("/secret", authorize, func() { + // 该方法将会在authorize方法没有输出结果的时候执行. +}) +~~~ + +### 服务 +服务即是被注入到处理器中的参数. 你可以映射一个服务到 *全局* 或者 *请求* 的级别. + + +#### 全局映射 +如果一个Martini实现了inject.Injector的接口, 那么映射成为一个服务就非常简单: +~~~ go +db := &MyDatabase{} +m := martini.Classic() +m.Map(db) // *MyDatabase 这个服务将可以在所有的处理器中被使用到. +// ... +m.Run() +~~~ + +#### 请求级别的映射 +映射在请求级别的服务可以用[martini.Context](http://godoc.org/github.com/go-martini/martini#Context)来完成: +~~~ go +func MyCustomLoggerHandler(c martini.Context, req *http.Request) { + logger := &MyCustomLogger{req} + c.Map(logger) // 映射成为了 *MyCustomLogger +} +~~~ + +#### 映射值到接口 +关于服务最强悍的地方之一就是它能够映射服务到接口. 例如说, 假设你想要覆盖[http.ResponseWriter](http://godoc.org/net/http#ResponseWriter)成为一个对象, 那么你可以封装它并包含你自己的额外操作, 你可以如下这样来编写你的处理器: +~~~ go +func WrapResponseWriter(res http.ResponseWriter, c martini.Context) { + rw := NewSpecialResponseWriter(res) + c.MapTo(rw, (*http.ResponseWriter)(nil)) // 覆盖 ResponseWriter 成为我们封装过的 ResponseWriter +} +~~~ + +### 服务静态文件 +[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) 默认会服务位于你服务器环境根目录下的"public"文件夹. +你可以通过加入[martini.Static](http://godoc.org/github.com/go-martini/martini#Static)的处理器来加入更多的静态文件服务的文件夹. +~~~ go +m.Use(martini.Static("assets")) // 也会服务静态文件于"assets"的文件夹 +~~~ + +## 中间件处理器 +中间件处理器是工作于请求和路由之间的. 本质上来说和Martini其他的处理器没有分别. 你可以像如下这样添加一个中间件处理器到它的堆中: +~~~ go +m.Use(func() { + // 做一些中间件该做的事情 +}) +~~~ + +你可以通过`Handlers`函数对中间件堆有完全的控制. 它将会替换掉之前的任何设置过的处理器: +~~~ go +m.Handlers( + Middleware1, + Middleware2, + Middleware3, +) +~~~ + +中间件处理器可以非常好处理一些功能,像logging(日志), authorization(授权), authentication(认证), sessions(会话), error pages(错误页面), 以及任何其他的操作需要在http请求发生之前或者之后的: + +~~~ go +// 验证api密匙 +m.Use(func(res http.ResponseWriter, req *http.Request) { + if req.Header.Get("X-API-KEY") != "secret123" { + res.WriteHeader(http.StatusUnauthorized) + } +}) +~~~ + +### Next() +[Context.Next()](http://godoc.org/github.com/go-martini/martini#Context)是一个可选的函数用于中间件处理器暂时放弃执行直到其他的处理器都执行完毕. 这样就可以很好的处理在http请求完成后需要做的操作. +~~~ go +// log 记录请求完成前后 (*译者注: 很巧妙,掌声鼓励.) +m.Use(func(c martini.Context, log *log.Logger){ + log.Println("before a request") + + c.Next() + + log.Println("after a request") +}) +~~~ + +## 常见问答 + +### 我在哪里可以找到中间件资源? + +可以查看 [martini-contrib](https://github.com/martini-contrib) 项目. 如果看了觉得没有什么好货色, 可以联系martini-contrib的团队成员为你创建一个新的代码资源库. + +* [auth](https://github.com/martini-contrib/auth) - 认证处理器。 +* [binding](https://github.com/martini-contrib/binding) - 映射/验证raw请求到结构体(structure)里的处理器。 +* [gzip](https://github.com/martini-contrib/gzip) - 通过giz方式压缩请求信息的处理器。 +* [render](https://github.com/martini-contrib/render) - 渲染JSON和HTML模板的处理器。 +* [acceptlang](https://github.com/martini-contrib/acceptlang) - 解析`Accept-Language` HTTP报头的处理器。 +* [sessions](https://github.com/martini-contrib/sessions) - 提供`Session`服务支持的处理器。 +* [strip](https://github.com/martini-contrib/strip) - 用于过滤指定的URL前缀。 +* [method](https://github.com/martini-contrib/method) - 通过请求头或表单域覆盖HTTP方法。 +* [secure](https://github.com/martini-contrib/secure) - 提供一些安全方面的速效方案。 +* [encoder](https://github.com/martini-contrib/encoder) - 提供用于多种格式的数据渲染或内容协商的编码服务。 +* [cors](https://github.com/martini-contrib/cors) - 提供支持 CORS 的处理器。 +* [oauth2](https://github.com/martini-contrib/oauth2) - 基于 OAuth 2.0 的应用登录处理器。支持谷歌、Facebook和Github的登录。 +* [vauth](https://github.com/rafecolton/vauth) - 负责webhook认证的处理器(目前支持GitHub和TravisCI)。 + + +### 我如何整合到我现有的服务器中? + +由于Martini实现了 `http.Handler`, 所以它可以很简单的应用到现有Go服务器的子集中. 例如说这是一段在Google App Engine中的示例: + +~~~ go +package hello + +import ( + "net/http" + "github.com/go-martini/martini" +) + +func init() { + m := martini.Classic() + m.Get("/", func() string { + return "Hello world!" + }) + http.Handle("/", m) +} +~~~ + +### 我如何修改port/host? + +Martini的`Run`函数会检查PORT和HOST的环境变量并使用它们. 否则Martini将会默认使用localhost:3000 +如果想要自定义PORT和HOST, 使用`martini.RunOnAddr`函数来代替. + +~~~ go + m := martini.Classic() + // ... + m.RunOnAddr(":8080") +~~~ + +## 贡献 +Martini项目想要保持简单且干净的代码. 大部分的代码应该贡献到[martini-contrib](https://github.com/martini-contrib)组织中作为一个项目. 如果你想要贡献Martini的核心代码也可以发起一个Pull Request. + +## 关于 + +灵感来自于 [express](https://github.com/visionmedia/express) 和 [sinatra](https://github.com/sinatra/sinatra) + +Martini作者 [Code Gangsta](http://codegangsta.io/) +译者: [Leon](http://github.com/leonli) diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_zh_tw.md b/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_zh_tw.md new file mode 100644 index 0000000..8d19dbe --- /dev/null +++ b/Godeps/_workspace/src/github.com/go-martini/martini/translations/README_zh_tw.md @@ -0,0 +1,381 @@ +# Martini [![wercker status](https://app.wercker.com/status/9b7dbc6e2654b604cd694d191c3d5487/s/master "wercker status")](https://app.wercker.com/project/bykey/9b7dbc6e2654b604cd694d191c3d5487)[![GoDoc](https://godoc.org/github.com/go-martini/martini?status.png)](http://godoc.org/github.com/go-martini/martini) + +Martini 是一個使用 Go 語言來快速開發模組化 Web 應用程式或服務的強大套件 + +## 開始 + +在您安裝Go語言以及設定好 +[GOPATH](http://golang.org/doc/code.html#GOPATH)環境變數後, +開始寫您第一支`.go`檔, 我們將稱它為`server.go` + +~~~ go +package main + +import "github.com/go-martini/martini" + +func main() { + m := martini.Classic() + m.Get("/", func() string { + return "Hello 世界!" + }) + m.Run() +} +~~~ + +然後安裝Martini套件 (**go 1.1**以上的版本是必要的) +~~~ +go get github.com/go-martini/martini +~~~ + +然後利用以下指令執行你的程式: +~~~ +go run server.go +~~~ + +此時, 您將會看到一個 Martini Web 伺服器在`localhost:3000`上執行 + +## 尋求幫助 + +可以加入 [Mailing list](https://groups.google.com/forum/#!forum/martini-go) + +觀看 [Demo Video](http://martini.codegangsta.io/#demo) + +## 功能 + +* 超容易使用 +* 非侵入式設計 +* 很容易跟其他Go套件同時使用 +* 很棒的路徑matching和routing方式 +* 模組化設計 - 容易增加或移除功能 +* 有很多handlers或middlewares可以直接使用 +* 已經提供很多內建功能 +* **跟[http.HandlerFunc](http://godoc.org/net/http#HandlerFunc) 介面**完全相容 +* 預設document服務 (例如, 提供AngularJS在HTML5模式的服務) + +## 其他Middleware +尋找更多的middleware或功能, 請到 [martini-contrib](https://github.com/martini-contrib)程式集搜尋 + +## 目錄 +* [Classic Martini](#classic-martini) +* [Handlers](#handlers) +* [Routing](#routing) +* [Services (服務)](#services) +* [Serving Static Files (伺服靜態檔案)](#serving-static-files) +* [Middleware Handlers](#middleware-handlers) +* [Next()](#next) +* [Martini Env](#martini-env) +* [FAQ (常見問題與答案)](#faq) + +## Classic Martini + +[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) +提供大部份web應用程式所需要的基本預設功能: + +~~~ go + m := martini.Classic() + // ... middleware 或 routing 寫在這裡 + m.Run() +~~~ +[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) + 會自動提供以下功能 +* Request/Response Logging - [martini.Logger](http://godoc.org/github.com/go-martini/martini#Logger) +* Panic Recovery - [martini.Recovery](http://godoc.org/github.com/go-martini/martini#Recovery) +* Static File serving - [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) +* Routing - [martini.Router](http://godoc.org/github.com/go-martini/martini#Router) + + +### Handlers +Handlers 是 Martini 的核心, 每個 handler 就是一個基本的呼叫函式, 例如: +~~~ go +m.Get("/", func() { + println("hello 世界") +}) +~~~ + +#### 回傳值 +如果一個 handler 有回傳值, Martini就會用字串的方式將結果寫回現在的 +[http.ResponseWriter](http://godoc.org/net/http#ResponseWriter), 例如: +~~~ go +m.Get("/", func() string { + return "hello 世界" // HTTP 200 : "hello 世界" +}) +~~~ + +你也可以選擇回傳狀態碼, 例如: +~~~ go +m.Get("/", func() (int, string) { + return 418, "我是一個茶壺" // HTTP 418 : "我是一個茶壺" +}) +~~~ + +#### 注入服務 (Service Injection) +Handlers 是透過 reflection 方式被喚起, Martini 使用 *Dependency Injection* 的方法 +載入 Handler 變數所需要的相關物件 **這也是 Martini 跟 Go 語言`http.HandlerFunc`介面 +完全相容的原因** + +如果你在 Handler 裡加入一個變數, Martini 會嘗試著從它的服務清單裡透過 type assertion +方式將相關物件載入 +~~~ go +m.Get("/", func(res http.ResponseWriter, req *http.Request) { // res 和 req 是由 Martini 注入 + res.WriteHeader(200) // HTTP 200 +}) +~~~ + +[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) 包含以下物件: + * [*log.Logger](http://godoc.org/log#Logger) - Martini 的全區域 Logger. + * [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) - http request 內文. + * [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) - `map[string]string` of named params found by route matching. + * [martini.Routes](http://godoc.org/github.com/go-martini/martini#Routes) - Route helper 服務. + * [http.ResponseWriter](http://godoc.org/net/http/#ResponseWriter) - http 回應 writer 介面. + * [*http.Request](http://godoc.org/net/http/#Request) - http 請求. + +### Routing +在 Martini 裡, 一個 route 就是一個 HTTP 方法與其 URL 的比對模式. +每個 route 可以有ㄧ或多個 handler 方法: +~~~ go +m.Get("/", func() { + // 顯示(值) +}) + +m.Patch("/", func() { + // 更新 +}) + +m.Post("/", func() { + // 產生 +}) + +m.Put("/", func() { + // 取代 +}) + +m.Delete("/", func() { + // 刪除 +}) + +m.Options("/", func() { + // http 選項 +}) + +m.NotFound(func() { + // handle 404 +}) +~~~ + +Routes 依照它們被定義時的順序做比對. 第一個跟請求 (request) 相同的 route 就被執行. + +Route 比對模式可以包含變數部分, 可以透過 [martini.Params](http://godoc.org/github.com/go-martini/martini#Params) 物件來取值: +~~~ go +m.Get("/hello/:name", func(params martini.Params) string { + return "Hello " + params["name"] +}) +~~~ + +Routes 也可以用 "**" 來配對, 例如: +~~~ go +m.Get("/hello/**", func(params martini.Params) string { + return "Hello " + params["_1"] +}) +~~~ + +也可以用正規表示法 (regular expressions) 來做比對, 例如: +~~~go +m.Get("/hello/(?P[a-zA-Z]+)", func(params martini.Params) string { + return fmt.Sprintf ("Hello %s", params["name"]) +}) +~~~ +更多有關正規表示法文法的資訊, 請參考 [Go 文件](http://golang.org/pkg/regexp/syntax/). + +Route handlers 也可以相互堆疊, 尤其是認證與授權相當好用: +~~~ go +m.Get("/secret", authorize, func() { + // 這裏開始處理授權問題, 而非寫出回應 +}) +~~~ + +也可以用 Group 方法, 將 route 編成一組. +~~~ go +m.Group("/books", func(r martini.Router) { + r.Get("/:id", GetBooks) + r.Post("/new", NewBook) + r.Put("/update/:id", UpdateBook) + r.Delete("/delete/:id", DeleteBook) +}) +~~~ + +跟對 handler 增加 middleware 方法一樣, 你也可以為一組 routes 增加 middleware. +~~~ go +m.Group("/books", func(r martini.Router) { + r.Get("/:id", GetBooks) + r.Post("/new", NewBook) + r.Put("/update/:id", UpdateBook) + r.Delete("/delete/:id", DeleteBook) +}, MyMiddleware1, MyMiddleware2) +~~~ + +### Services +服務是一些物件可以被注入 Handler 變數裡的東西, 可以分對應到 *Global* 或 *Request* 兩種等級. + +#### Global Mapping (全域級對應) +一個 Martini 實體 (instance) 實現了 inject.Injector 介面, 所以非常容易對應到所需要的服務, 例如: +~~~ go +db := &MyDatabase{} +m := martini.Classic() +m.Map(db) // 所以 *MyDatabase 就可以被所有的 handlers 使用 +// ... +m.Run() +~~~ + +#### Request-Level Mapping (請求級對應) +如果只在一個 handler 裡定義, 透由 [martini.Context](http://godoc.org/github.com/go-martini/martini#Context) 獲得一個請求 (request) 級的對應: +~~~ go +func MyCustomLoggerHandler(c martini.Context, req *http.Request) { + logger := &MyCustomLogger{req} + c.Map(logger) // 對應到 *MyCustomLogger +} +~~~ + +#### 透由介面對應 +有關服務, 最強的部分是它還能對應到一個介面 (interface), 例如, +如果你想要包裹並增加一個變數而改寫 (override) 原有的 [http.ResponseWriter](http://godoc.org/net/http#ResponseWriter), 你的 handler 可以寫成: +~~~ go +func WrapResponseWriter(res http.ResponseWriter, c martini.Context) { + rw := NewSpecialResponseWriter(res) + c.MapTo(rw, (*http.ResponseWriter)(nil)) // 我們包裹的 ResponseWriter 蓋掉原始的 ResponseWrite +} +~~~ + +### Serving Static Files +一個[martini.Classic()](http://godoc.org/github.com/go-martini/martini#Classic) 實體會將伺服器根目錄下 public 子目錄裡的檔案自動當成靜態檔案處理. 你也可以手動用 [martini.Static](http://godoc.org/github.com/go-martini/martini#Static) 增加其他目錄, 例如. +~~~ go +m.Use(martini.Static("assets")) // "assets" 子目錄裡, 也視為靜態檔案 +~~~ + +#### Serving a Default Document +當某些 URL 找不到時, 你也可以指定本地檔案的 URL 來顯示. +你也可以用開頭除外 (exclusion prefix) 的方式, 來忽略某些 URLs, +它尤其在某些伺服器同時伺服靜態檔案, 而且還有額外 handlers 處理 (例如 REST API) 時, 特別好用. +比如說, 在比對找不到之後, 想要用靜態檔來處理特別好用. + +以下範例, 就是在 URL 開頭不是`/api/v`而且也不是本地檔案的情況下, 顯示`/index.html`檔: +~~~ go +static := martini.Static("assets", martini.StaticOptions{Fallback: "/index.html", Exclude: "/api/v"}) +m.NotFound(static, http.NotFound) +~~~ + +## Middleware Handlers +Middleware Handlers 位於進來的 http 請求與 router 之間, 在 Martini 裡, 本質上它跟其他 + Handler 沒有什麼不同, 例如, 你可加入一個 middleware 方法如下 +~~~ go +m.Use(func() { + // 做 middleware 的事 +}) +~~~ + +你也可以用`Handlers`完全控制 middelware 層, 把先前設定的 handlers 都替換掉, 例如: +~~~ go +m.Handlers( + Middleware1, + Middleware2, + Middleware3, +) +~~~ + +Middleware Handlers 成被拿來處理 http 請求之前和之後的事, 尤其是用來紀錄logs, 授權, 認證, +sessions, 壓縮 (gzipping), 顯示錯誤頁面等等, 都非常好用, 例如: +~~~ go +// validate an api key +m.Use(func(res http.ResponseWriter, req *http.Request) { + if req.Header.Get("X-API-KEY") != "secret123" { + res.WriteHeader(http.StatusUnauthorized) + } +}) +~~~ + +### Next() +[Context.Next()](http://godoc.org/github.com/go-martini/martini#Context) 是 Middleware Handlers 可以呼叫的選項功能, 用來等到其他 handlers 處理完再開始執行. +它常常被用來處理那些必須在 http 請求之後才能發生的事件, 例如: +~~~ go +// 在請求前後加 logs +m.Use(func(c martini.Context, log *log.Logger){ + log.Println("before a request") + + c.Next() + + log.Println("after a request") +}) +~~~ + +## Martini Env + +有些 Martini handlers 使用 `martini.Env` 全區域變數, 來當成開發環境或是上架 (production) +環境的設定判斷. 建議用 `MARTINI_ENV=production` 環境變數來設定 Martini 伺服器是上架與否. + +## FAQ + +### 我去哪可以找到 middleware X? + +可以從 [martini-contrib](https://github.com/martini-contrib) 裡的專案找起. +如果那裡沒有, 請與 martini-contrib 團隊聯絡, 將它加入. + +* [auth](https://github.com/martini-contrib/auth) - 處理認證的 Handler. +* [binding](https://github.com/martini-contrib/binding) - +處理一個單純的請求對應到一個結構體與確認內容正確與否的 Handler. +* [gzip](https://github.com/martini-contrib/gzip) - 對請求加 gzip 壓縮的 Handler. +* [render](https://github.com/martini-contrib/render) - 提供簡單處理 JSON 和 +HTML 樣板成形 (rendering) 的 Handler. +* [acceptlang](https://github.com/martini-contrib/acceptlang) - 解析 `Accept-Language` HTTP 檔頭的 Handler. +* [sessions](https://github.com/martini-contrib/sessions) - 提供 Session 服務的 Handler. +* [strip](https://github.com/martini-contrib/strip) - URL 字頭處理 (Prefix stripping). +* [method](https://github.com/martini-contrib/method) - 透過 Header 或表格 (form) 欄位蓋過 HTTP 方法 (method). +* [secure](https://github.com/martini-contrib/secure) - 提供一些簡單的安全機制. +* [encoder](https://github.com/martini-contrib/encoder) - 轉換資料格式之 Encoder 服務. +* [cors](https://github.com/martini-contrib/cors) - 啟動支援 CORS 之 Handler. +* [oauth2](https://github.com/martini-contrib/oauth2) - 讓 Martini 應用程式能提供 OAuth 2.0 登入的 Handler. 其中支援 Google 登錄, Facebook Connect 與 Github 的登入等. +* [vauth](https://github.com/rafecolton/vauth) - 處理 vender webhook 認證的 Handler (目前支援 GitHub 以及 TravisCI) + +### 我如何整合到現有的伺服器? + +Martini 實作 `http.Handler`,所以可以非常容易整合到現有的 Go 伺服器裡. +以下寫法, 是一個能在 Google App Engine 上運行的 Martini 應用程式: + +~~~ go +package hello + +import ( + "net/http" + "github.com/go-martini/martini" +) + +func init() { + m := martini.Classic() + m.Get("/", func() string { + return "Hello world!" + }) + http.Handle("/", m) +} +~~~ + +### 我要如何改變 port/host? + +Martini 的 `Run` 功能會看 PORT 及 HOST 當時的環境變數, 否則 Martini 會用 localhost:3000 +當預設值. 讓 port 及 host 更有彈性, 可以用 `martini.RunOnAddr` 取代. + +~~~ go + m := martini.Classic() + // ... + log.Fatal(m.RunOnAddr(":8080")) +~~~ + +### 可以線上更新 (live reload) 嗎? + +[gin](https://github.com/codegangsta/gin) 和 [fresh](https://github.com/pilu/fresh) 可以幫 Martini 程式做到線上更新. + +## 貢獻 +Martini 盡量保持小而美的精神, 大多數的程式貢獻者可以在 [martini-contrib](https://github.com/martini-contrib) 組織提供代碼. 如果你想要對 Martini 核心提出貢獻, 請丟出 Pull Request. + +## 關於 + +靈感來自與 [express](https://github.com/visionmedia/express) 以及 [sinatra](https://github.com/sinatra/sinatra) + +Martini 由 [Code Gangsta](http://codegangsta.io/) 公司設計出品 (著魔地) diff --git a/Godeps/_workspace/src/github.com/go-martini/martini/wercker.yml b/Godeps/_workspace/src/github.com/go-martini/martini/wercker.yml new file mode 100644 index 0000000..f8bf918 --- /dev/null +++ b/Godeps/_workspace/src/github.com/go-martini/martini/wercker.yml @@ -0,0 +1 @@ +box: wercker/golang@1.1.1 \ No newline at end of file diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/.travis.yml b/Godeps/_workspace/src/github.com/zenazn/goji/.travis.yml deleted file mode 100644 index 8d7d11f..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ -language: go -go: - - 1.2 - - 1.3 - - tip -install: - - go list -f '{{range .Imports}}{{.}} {{end}}' ./... | xargs go get -v - - go list -f '{{range .TestImports}}{{.}} {{end}}' ./... | xargs go get -v - - go get code.google.com/p/go.tools/cmd/cover - - go build -v ./... -script: - - go test -v -cover ./... diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/README.md b/Godeps/_workspace/src/github.com/zenazn/goji/README.md deleted file mode 100644 index 7fbc620..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/README.md +++ /dev/null @@ -1,156 +0,0 @@ -Goji [![GoDoc](https://godoc.org/github.com/zenazn/goji?status.png)](https://godoc.org/github.com/zenazn/goji) [![Build Status](https://travis-ci.org/zenazn/goji.svg)](https://travis-ci.org/zenazn/goji) -==== - -Goji is a minimalistic web framework that values composability and simplicity. - -Example -------- - -```go -package main - -import ( - "fmt" - "net/http" - - "github.com/zenazn/goji" - "github.com/zenazn/goji/web" -) - -func hello(c web.C, w http.ResponseWriter, r *http.Request) { - fmt.Fprintf(w, "Hello, %s!", c.URLParams["name"]) -} - -func main() { - goji.Get("/hello/:name", hello) - goji.Serve() -} -``` - -Goji also includes a [sample application][sample] in the `example` folder which -was artificially constructed to show off all of Goji's features. Check it out! - -[sample]: https://github.com/zenazn/goji/tree/master/example - - -Features --------- - -* Compatible with `net/http` -* URL patterns (both Sinatra style `/foo/:bar` patterns and regular expressions, - as well as [custom patterns][pattern]) -* Reconfigurable middleware stack -* Context/environment object threaded through middleware and handlers -* Automatic support for [Einhorn][einhorn], systemd, and [more][bind] -* [Graceful shutdown][graceful], and zero-downtime graceful reload when combined - with Einhorn. -* Ruby on Rails / jQuery style [parameter parsing][param] -* High in antioxidants - -[einhorn]: https://github.com/stripe/einhorn -[bind]: http://godoc.org/github.com/zenazn/goji/bind -[graceful]: http://godoc.org/github.com/zenazn/goji/graceful -[param]: http://godoc.org/github.com/zenazn/goji/param -[pattern]: https://godoc.org/github.com/zenazn/goji/web#Pattern - - -Is it any good? ---------------- - -Maybe! - -There are [plenty][revel] of [other][gorilla] [good][pat] [Go][martini] -[web][gocraft] [frameworks][tiger] out there. Goji is by no means especially -novel, nor is it uniquely good. The primary difference between Goji and other -frameworks—and the primary reason I think Goji is any good—is its philosophy: - -Goji first of all attempts to be simple. It is of the Sinatra and Flask school -of web framework design, and not the Rails/Django one. If you want me to tell -you what directory you should put your models in, or if you want built-in flash -sessions, you won't have a good time with Goji. - -Secondly, Goji attempts to be composable. It is fully composable with net/http, -and can be used as a `http.Handler`, or can serve arbitrary `http.Handler`s. At -least a few HTTP frameworks share this property, and is not particularly novel. -The more interesting property in my mind is that Goji is fully composable with -itself: it defines an interface (`web.Handler`) which is both fully compatible -with `http.Handler` and allows Goji to perform a "protocol upgrade" of sorts -when it detects that it is talking to itself (or another `web.Handler` -compatible component). `web.Handler` is at the core of Goji's interfaces and is -what allows it to share request contexts across unrelated objects. - -Third, Goji is not magic. One of my favorite existing frameworks is -[Martini][martini], but I rejected it in favor of building Goji because I -thought it was too magical. Goji's web package does not use reflection at all, -which is not in itself a sign of API quality, but to me at least seems to -suggest it. - -Finally, Goji gives you enough rope to hang yourself with. One of my other -favorite libraries, [pat][pat], implements Sinatra-like routing in a -particularly elegant way, but because of its reliance on net/http's interfaces, -doesn't allow programmers to thread their own state through the request handling -process. Implementing arbitrary context objects was one of the primary -motivations behind abandoning pat to write Goji. - -[revel]: http://revel.github.io/ -[gorilla]: http://www.gorillatoolkit.org/ -[pat]: https://github.com/bmizerany/pat -[martini]: http://martini.codegangsta.io/ -[gocraft]: https://github.com/gocraft/web -[tiger]: https://github.com/rcrowley/go-tigertonic - - -Is it fast? ------------ - -[Yeah][bench1], [it is][bench2]. Goji is among the fastest HTTP routers out -there, and is very gentle on the garbage collector. - -But that's sort of missing the point. Almost all Go routers are fast enough for -almost all purposes. In my opinion, what matters more is how simple and flexible -the routing semantics are. - -Goji provides results indistinguishable from naively trying routes one after -another. This means that a route added before another route will be attempted -before that route as well. This is perhaps the most simple and most intuitive -interface a router can provide, and makes routes very easy to understand and -debug. - -Goji's router is also very flexible: in addition to the standard Sinatra-style -patterns and regular expression patterns, you can define [custom -patterns][pattern] to perform whatever custom matching logic you desire. Custom -patterns of course are fully compatible with the routing semantics above. - -It's easy (and quite a bit of fun!) to get carried away by microbenchmarks, but -at the end of the day you're not going to miss those extra hundred nanoseconds -on a request. What matters is that you aren't compromising on the API for a -handful of CPU cycles. - -[bench1]: https://gist.github.com/zenazn/c5c8528efe1a00634096 -[bench2]: https://github.com/julienschmidt/go-http-routing-benchmark - - -Third-Party Libraries ---------------------- - -Goji is already compatible with a great many third-party libraries that are -themselves compatible with `net/http`, however some library authors have gone -out of their way to include Goji compatibility specifically, perhaps by -integrating more tightly with Goji's `web.C` or by providing a custom pattern -type. An informal list of such libraries is maintained [on the wiki][third]; -feel free to add to it as you see fit. - -[third]: https://github.com/zenazn/goji/wiki/Third-Party-Libraries - - -Contributing ------------- - -Please do! I love pull requests, and I love pull requests that include tests -even more. Goji's core packages have pretty good code coverage (yay code -coverage gamification!), and if you have the time to write tests I'd like to -keep it that way. - -In addition to contributing code, I'd love to know what you think about Goji. -Please open an issue or send me an email with your thoughts; it'd mean a lot to -me. diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/bind/bind.go b/Godeps/_workspace/src/github.com/zenazn/goji/bind/bind.go deleted file mode 100644 index 9228f5a..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/bind/bind.go +++ /dev/null @@ -1,133 +0,0 @@ -/* -Package bind provides a convenient way to bind to sockets. It exposes a flag in -the default flag set named "bind" which provides syntax to bind TCP and UNIX -sockets. It also supports binding to arbitrary file descriptors passed by a -parent (for instance, systemd), and for binding to Einhorn sockets (including -Einhorn ACK support). - -If the value passed to bind contains a colon, as in ":8000" or "127.0.0.1:9001", -it will be treated as a TCP address. If it begins with a "/" or a ".", it will -be treated as a path to a UNIX socket. If it begins with the string "fd@", as in -"fd@3", it will be treated as a file descriptor (useful for use with systemd, -for instance). If it begins with the string "einhorn@", as in "einhorn@0", the -corresponding einhorn socket will be used. - -If an option is not explicitly passed, the implementation will automatically -select between using "einhorn@0", "fd@3", and ":8000", depending on whether -Einhorn or systemd (or neither) is detected. - -This package is a teensy bit magical, and goes out of its way to Do The Right -Thing in many situations, including in both development and production. If -you're looking for something less magical, you'd probably be better off just -calling net.Listen() the old-fashioned way. -*/ -package bind - -import ( - "flag" - "fmt" - "log" - "net" - "os" - "strconv" - "strings" - "sync" -) - -var bind string - -func init() { - einhornInit() - systemdInit() -} - -// WithFlag adds a standard flag to the global flag instance that allows -// configuration of the default socket. Users who call Default() must call this -// function before flags are parsed, for example in an init() block. -// -// When selecting the default bind string, this function will examine its -// environment for hints about what port to bind to, selecting the GOJI_BIND -// environment variable, Einhorn, systemd, the PORT environment variable, and -// the port 8000, in order. In most cases, this means that the default behavior -// of the default socket will be reasonable for use in your circumstance. -func WithFlag() { - defaultBind := ":8000" - if bind := os.Getenv("GOJI_BIND"); bind != "" { - defaultBind = bind - } else if usingEinhorn() { - defaultBind = "einhorn@0" - } else if usingSystemd() { - defaultBind = "fd@3" - } else if port := os.Getenv("PORT"); port != "" { - defaultBind = ":" + port - } - flag.StringVar(&bind, "bind", defaultBind, - `Address to bind on. If this value has a colon, as in ":8000" or - "127.0.0.1:9001", it will be treated as a TCP address. If it - begins with a "/" or a ".", it will be treated as a path to a - UNIX socket. If it begins with the string "fd@", as in "fd@3", - it will be treated as a file descriptor (useful for use with - systemd, for instance). If it begins with the string "einhorn@", - as in "einhorn@0", the corresponding einhorn socket will be - used. If an option is not explicitly passed, the implementation - will automatically select among "einhorn@0" (Einhorn), "fd@3" - (systemd), and ":8000" (fallback) based on its environment.`) -} - -func listenTo(bind string) (net.Listener, error) { - if strings.Contains(bind, ":") { - return net.Listen("tcp", bind) - } else if strings.HasPrefix(bind, ".") || strings.HasPrefix(bind, "/") { - return net.Listen("unix", bind) - } else if strings.HasPrefix(bind, "fd@") { - fd, err := strconv.Atoi(bind[3:]) - if err != nil { - return nil, fmt.Errorf("error while parsing fd %v: %v", - bind, err) - } - f := os.NewFile(uintptr(fd), bind) - defer f.Close() - return net.FileListener(f) - } else if strings.HasPrefix(bind, "einhorn@") { - fd, err := strconv.Atoi(bind[8:]) - if err != nil { - return nil, fmt.Errorf( - "error while parsing einhorn %v: %v", bind, err) - } - return einhornBind(fd) - } - - return nil, fmt.Errorf("error while parsing bind arg %v", bind) -} - -// Socket parses and binds to the specified address. If Socket encounters an -// error while parsing or binding to the given socket it will exit by calling -// log.Fatal. -func Socket(bind string) net.Listener { - l, err := listenTo(bind) - if err != nil { - log.Fatal(err) - } - return l -} - -// Default parses and binds to the default socket as given to us by the flag -// module. If there was an error parsing or binding to that socket, Default will -// exit by calling `log.Fatal`. -func Default() net.Listener { - return Socket(bind) -} - -// I'm not sure why you'd ever want to call Ready() more than once, but we may -// as well be safe against it... -var ready sync.Once - -// Ready notifies the environment (for now, just Einhorn) that the process is -// ready to receive traffic. Should be called at the last possible moment to -// maximize the chances that a faulty process exits before signaling that it's -// ready. -func Ready() { - ready.Do(func() { - einhornAck() - }) -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/bind/einhorn.go b/Godeps/_workspace/src/github.com/zenazn/goji/bind/einhorn.go deleted file mode 100644 index e695c0e..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/bind/einhorn.go +++ /dev/null @@ -1,91 +0,0 @@ -// +build !windows - -package bind - -import ( - "fmt" - "log" - "net" - "os" - "strconv" - "syscall" -) - -const tooBigErr = "bind: einhorn@%d not found (einhorn only passed %d fds)" -const bindErr = "bind: could not bind einhorn@%d: not running under einhorn" -const einhornErr = "bind: einhorn environment initialization error" -const ackErr = "bind: error ACKing to einhorn: %v" - -var einhornNumFds int - -func envInt(val string) (int, error) { - return strconv.Atoi(os.Getenv(val)) -} - -// Unfortunately this can't be a normal init function, because their execution -// order is undefined, and we need to run before the init() in bind.go. -func einhornInit() { - mpid, err := envInt("EINHORN_MASTER_PID") - if err != nil || mpid != os.Getppid() { - return - } - - einhornNumFds, err = envInt("EINHORN_FD_COUNT") - if err != nil { - einhornNumFds = 0 - return - } - - // Prevent einhorn's fds from leaking to our children - for i := 0; i < einhornNumFds; i++ { - syscall.CloseOnExec(einhornFdMap(i)) - } -} - -func usingEinhorn() bool { - return einhornNumFds > 0 -} - -func einhornFdMap(n int) int { - name := fmt.Sprintf("EINHORN_FD_%d", n) - fno, err := envInt(name) - if err != nil { - log.Fatal(einhornErr) - } - return fno -} - -func einhornBind(n int) (net.Listener, error) { - if !usingEinhorn() { - return nil, fmt.Errorf(bindErr, n) - } - if n >= einhornNumFds || n < 0 { - return nil, fmt.Errorf(tooBigErr, n, einhornNumFds) - } - - fno := einhornFdMap(n) - f := os.NewFile(uintptr(fno), fmt.Sprintf("einhorn@%d", n)) - defer f.Close() - return net.FileListener(f) -} - -// Fun story: this is actually YAML, not JSON. -const ackMsg = `{"command": "worker:ack", "pid": %d}` + "\n" - -func einhornAck() { - if !usingEinhorn() { - return - } - log.Print("bind: ACKing to einhorn") - - ctl, err := net.Dial("unix", os.Getenv("EINHORN_SOCK_PATH")) - if err != nil { - log.Fatalf(ackErr, err) - } - defer ctl.Close() - - _, err = fmt.Fprintf(ctl, ackMsg, os.Getpid()) - if err != nil { - log.Fatalf(ackErr, err) - } -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/bind/einhorn_windows.go b/Godeps/_workspace/src/github.com/zenazn/goji/bind/einhorn_windows.go deleted file mode 100644 index 093707f..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/bind/einhorn_windows.go +++ /dev/null @@ -1,12 +0,0 @@ -// +build windows - -package bind - -import ( - "net" -) - -func einhornInit() {} -func einhornAck() {} -func einhornBind(fd int) (net.Listener, error) { return nil, nil } -func usingEinhorn() bool { return false } diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/bind/systemd.go b/Godeps/_workspace/src/github.com/zenazn/goji/bind/systemd.go deleted file mode 100644 index e7cd8e4..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/bind/systemd.go +++ /dev/null @@ -1,36 +0,0 @@ -// +build !windows - -package bind - -import ( - "os" - "syscall" -) - -const systemdMinFd = 3 - -var systemdNumFds int - -// Unfortunately this can't be a normal init function, because their execution -// order is undefined, and we need to run before the init() in bind.go. -func systemdInit() { - pid, err := envInt("LISTEN_PID") - if err != nil || pid != os.Getpid() { - return - } - - systemdNumFds, err = envInt("LISTEN_FDS") - if err != nil { - systemdNumFds = 0 - return - } - - // Prevent fds from leaking to our children - for i := 0; i < systemdNumFds; i++ { - syscall.CloseOnExec(systemdMinFd + i) - } -} - -func usingSystemd() bool { - return systemdNumFds > 0 -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/bind/systemd_windows.go b/Godeps/_workspace/src/github.com/zenazn/goji/bind/systemd_windows.go deleted file mode 100644 index 4ad4d20..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/bind/systemd_windows.go +++ /dev/null @@ -1,6 +0,0 @@ -// +build windows - -package bind - -func systemdInit() {} -func usingSystemd() bool { return false } diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/default.go b/Godeps/_workspace/src/github.com/zenazn/goji/default.go deleted file mode 100644 index 9e5d536..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/default.go +++ /dev/null @@ -1,102 +0,0 @@ -package goji - -import ( - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/zenazn/goji/web" - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware" -) - -var DefaultMux *web.Mux - -func // The default web.Mux. -init() { - DefaultMux = web.New() - - DefaultMux.Use(middleware.RequestID) - DefaultMux.Use(middleware.Logger) - DefaultMux.Use(middleware.Recoverer) - DefaultMux.Use(middleware.AutomaticOptions) -} - -// Use appends the given middleware to the default Mux's middleware stack. See -// the documentation for web.Mux.Use for more information. -func Use(middleware interface{}) { - DefaultMux.Use(middleware) -} - -// Insert the given middleware into the default Mux's middleware stack. See the -// documentation for web.Mux.Insert for more information. -func Insert(middleware, before interface{}) error { - return DefaultMux.Insert(middleware, before) -} - -// Abandon removes the given middleware from the default Mux's middleware stack. -// See the documentation for web.Mux.Abandon for more information. -func Abandon(middleware interface{}) error { - return DefaultMux.Abandon(middleware) -} - -// Handle adds a route to the default Mux. See the documentation for web.Mux for -// more information about what types this function accepts. -func Handle(pattern interface{}, handler interface{}) { - DefaultMux.Handle(pattern, handler) -} - -// Connect adds a CONNECT route to the default Mux. See the documentation for -// web.Mux for more information about what types this function accepts. -func Connect(pattern interface{}, handler interface{}) { - DefaultMux.Connect(pattern, handler) -} - -// Delete adds a DELETE route to the default Mux. See the documentation for -// web.Mux for more information about what types this function accepts. -func Delete(pattern interface{}, handler interface{}) { - DefaultMux.Delete(pattern, handler) -} - -// Get adds a GET route to the default Mux. See the documentation for web.Mux for -// more information about what types this function accepts. -func Get(pattern interface{}, handler interface{}) { - DefaultMux.Get(pattern, handler) -} - -// Head adds a HEAD route to the default Mux. See the documentation for web.Mux -// for more information about what types this function accepts. -func Head(pattern interface{}, handler interface{}) { - DefaultMux.Head(pattern, handler) -} - -// Options adds a OPTIONS route to the default Mux. See the documentation for -// web.Mux for more information about what types this function accepts. -func Options(pattern interface{}, handler interface{}) { - DefaultMux.Options(pattern, handler) -} - -// Patch adds a PATCH route to the default Mux. See the documentation for web.Mux -// for more information about what types this function accepts. -func Patch(pattern interface{}, handler interface{}) { - DefaultMux.Patch(pattern, handler) -} - -// Post adds a POST route to the default Mux. See the documentation for web.Mux -// for more information about what types this function accepts. -func Post(pattern interface{}, handler interface{}) { - DefaultMux.Post(pattern, handler) -} - -// Put adds a PUT route to the default Mux. See the documentation for web.Mux for -// more information about what types this function accepts. -func Put(pattern interface{}, handler interface{}) { - DefaultMux.Put(pattern, handler) -} - -// Trace adds a TRACE route to the default Mux. See the documentation for -// web.Mux for more information about what types this function accepts. -func Trace(pattern interface{}, handler interface{}) { - DefaultMux.Trace(pattern, handler) -} - -// NotFound sets the NotFound handler for the default Mux. See the documentation -// for web.Mux.NotFound for more information. -func NotFound(handler interface{}) { - DefaultMux.NotFound(handler) -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/example/.gitignore b/Godeps/_workspace/src/github.com/zenazn/goji/example/.gitignore deleted file mode 100644 index 33a9488..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/example/.gitignore +++ /dev/null @@ -1 +0,0 @@ -example diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/example/README.md b/Godeps/_workspace/src/github.com/zenazn/goji/example/README.md deleted file mode 100644 index acb84d6..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/example/README.md +++ /dev/null @@ -1,10 +0,0 @@ -Gritter -======= - -Gritter is an example application built using Goji, where people who have -nothing better to do can post short 140-character "greets." - -A good place to start is with `main.go`, which contains a well-commented -walthrough of Goji's features. Gritter uses a couple custom middlewares, which -have been arbitrarily placed in `middleware.go`. Finally some uninteresting -"database models" live in `models.go`. diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/example/main.go b/Godeps/_workspace/src/github.com/zenazn/goji/example/main.go deleted file mode 100644 index 44dbe0d..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/example/main.go +++ /dev/null @@ -1,152 +0,0 @@ -// Command example is a sample application built with Goji. Its goal is to give -// you a taste for what Goji looks like in the real world by artificially using -// all of its features. -// -// In particular, this is a complete working site for gritter.com, a site where -// users can post 140-character "greets". Any resemblance to real websites, -// alive or dead, is purely coincidental. -package main - -import ( - "fmt" - "io" - "net/http" - "regexp" - "strconv" - - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/zenazn/goji" - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/zenazn/goji/param" - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/zenazn/goji/web" -) - -// Note: the code below cuts a lot of corners to make the example app simple. - -func main() { - // Add routes to the global handler - goji.Get("/", Root) - // Fully backwards compatible with net/http's Handlers - goji.Get("/greets", http.RedirectHandler("/", 301)) - // Use your favorite HTTP verbs - goji.Post("/greets", NewGreet) - // Use Sinatra-style patterns in your URLs - goji.Get("/users/:name", GetUser) - // Goji also supports regular expressions with named capture groups. - goji.Get(regexp.MustCompile(`^/greets/(?P\d+)$`), GetGreet) - - // Middleware can be used to inject behavior into your app. The - // middleware for this application are defined in middleware.go, but you - // can put them wherever you like. - goji.Use(PlainText) - - // If the last character of a pattern is an asterisk, the path is - // treated as a prefix, and can be used to implement sub-routes. - // Sub-routes can be used to set custom middleware on sub-applications. - // Goji's interfaces are completely composable. - admin := web.New() - goji.Handle("/admin/*", admin) - admin.Use(SuperSecure) - - // Goji's routing, like Sinatra's, is exact: no effort is made to - // normalize trailing slashes. - goji.Get("/admin", http.RedirectHandler("/admin/", 301)) - - // Set up admin routes. Note that sub-routes do *not* mutate the path in - // any way, so we need to supply full ("/admin/" prefixed) paths. - admin.Get("/admin/", AdminRoot) - admin.Get("/admin/finances", AdminFinances) - - // Use a custom 404 handler - goji.NotFound(NotFound) - - // Call Serve() at the bottom of your main() function, and it'll take - // care of everything else for you, including binding to a socket (with - // automatic support for systemd and Einhorn) and supporting graceful - // shutdown on SIGINT. Serve() is appropriate for both development and - // production. - goji.Serve() -} - -// Root route (GET "/"). Print a list of greets. -func Root(w http.ResponseWriter, r *http.Request) { - // In the real world you'd probably use a template or something. - io.WriteString(w, "Gritter\n======\n\n") - for i := len(Greets) - 1; i >= 0; i-- { - Greets[i].Write(w) - } -} - -// NewGreet creates a new greet (POST "/greets"). Creates a greet and redirects -// you to the created greet. -// -// To post a new greet, try this at a shell: -// $ now=$(date +'%Y-%m-%mT%H:%M:%SZ') -// $ curl -i -d "user=carl&message=Hello+World&time=$now" localhost:8000/greets -func NewGreet(w http.ResponseWriter, r *http.Request) { - var greet Greet - - // Parse the POST body into the Greet struct. The format is the same as - // is emitted by (e.g.) jQuery.param. - r.ParseForm() - err := param.Parse(r.Form, &greet) - - if err != nil || len(greet.Message) > 140 { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - - // We make no effort to prevent races against other insertions. - Greets = append(Greets, greet) - url := fmt.Sprintf("/greets/%d", len(Greets)-1) - http.Redirect(w, r, url, http.StatusCreated) -} - -// GetUser finds a given user and her greets (GET "/user/:name") -func GetUser(c web.C, w http.ResponseWriter, r *http.Request) { - io.WriteString(w, "Gritter\n======\n\n") - handle := c.URLParams["name"] - user, ok := Users[handle] - if !ok { - http.Error(w, http.StatusText(404), 404) - return - } - - user.Write(w, handle) - - io.WriteString(w, "\nGreets:\n") - for i := len(Greets) - 1; i >= 0; i-- { - if Greets[i].User == handle { - Greets[i].Write(w) - } - } -} - -// GetGreet finds a particular greet by ID (GET "/greet/\d+"). Does no bounds -// checking, so will probably panic. -func GetGreet(c web.C, w http.ResponseWriter, r *http.Request) { - id, err := strconv.Atoi(c.URLParams["id"]) - if err != nil { - http.Error(w, http.StatusText(404), 404) - return - } - // This will panic if id is too big. Try it out! - greet := Greets[id] - - io.WriteString(w, "Gritter\n======\n\n") - greet.Write(w) -} - -// AdminRoot is root (GET "/admin/root"). Much secret. Very administrate. Wow. -func AdminRoot(w http.ResponseWriter, r *http.Request) { - io.WriteString(w, "Gritter\n======\n\nSuper secret admin page!\n") -} - -// AdminFinances would answer the question 'How are we doing?' -// (GET "/admin/finances") -func AdminFinances(w http.ResponseWriter, r *http.Request) { - io.WriteString(w, "Gritter\n======\n\nWe're broke! :(\n") -} - -// NotFound is a 404 handler. -func NotFound(w http.ResponseWriter, r *http.Request) { - http.Error(w, "Umm... have you tried turning it off and on again?", 404) -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/example/middleware.go b/Godeps/_workspace/src/github.com/zenazn/goji/example/middleware.go deleted file mode 100644 index 6d10a44..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/example/middleware.go +++ /dev/null @@ -1,47 +0,0 @@ -package main - -import ( - "encoding/base64" - "net/http" - "strings" - - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/zenazn/goji/web" -) - -// PlainText sets the content-type of responses to text/plain. -func PlainText(h http.Handler) http.Handler { - fn := func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "text/plain") - h.ServeHTTP(w, r) - } - return http.HandlerFunc(fn) -} - -// Nobody will ever guess this! -const Password = "admin:admin" - -// SuperSecure is HTTP Basic Auth middleware for super-secret admin page. Shhhh! -func SuperSecure(c *web.C, h http.Handler) http.Handler { - fn := func(w http.ResponseWriter, r *http.Request) { - auth := r.Header.Get("Authorization") - if !strings.HasPrefix(auth, "Basic ") { - pleaseAuth(w) - return - } - - password, err := base64.StdEncoding.DecodeString(auth[6:]) - if err != nil || string(password) != Password { - pleaseAuth(w) - return - } - - h.ServeHTTP(w, r) - } - return http.HandlerFunc(fn) -} - -func pleaseAuth(w http.ResponseWriter) { - w.Header().Set("WWW-Authenticate", `Basic realm="Gritter"`) - w.WriteHeader(http.StatusUnauthorized) - w.Write([]byte("Go away!\n")) -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/example/models.go b/Godeps/_workspace/src/github.com/zenazn/goji/example/models.go deleted file mode 100644 index 4c34c08..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/example/models.go +++ /dev/null @@ -1,49 +0,0 @@ -package main - -import ( - "fmt" - "io" - "time" -) - -// A Greet is a 140-character micro-blogpost that has no resemblance whatsoever -// to the noise a bird makes. -type Greet struct { - User string `param:"user"` - Message string `param:"message"` - Time time.Time `param:"time"` -} - -// Store all our greets in a big list in memory, because, let's be honest, who's -// actually going to use a service that only allows you to post 140-character -// messages? -var Greets = []Greet{ - {"carl", "Welcome to Gritter!", time.Now()}, - {"alice", "Wanna know a secret?", time.Now()}, - {"bob", "Okay!", time.Now()}, - {"eve", "I'm listening...", time.Now()}, -} - -// Write out a representation of the greet -func (g Greet) Write(w io.Writer) { - fmt.Fprintf(w, "%s\n@%s at %s\n---\n", g.Message, g.User, - g.Time.Format(time.UnixDate)) -} - -// A User is a person. It may even be someone you know. Or a rabbit. Hard to say -// from here. -type User struct { - Name, Bio string -} - -// All the users we know about! There aren't very many... -var Users = map[string]User{ - "alice": {"Alice in Wonderland", "Eating mushrooms"}, - "bob": {"Bob the Builder", "Making children dumber"}, - "carl": {"Carl Jackson", "Duct tape aficionado"}, -} - -// Write out the user -func (u User) Write(w io.Writer, handle string) { - fmt.Fprintf(w, "%s (@%s)\n%s\n", u.Name, handle, u.Bio) -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/goji.go b/Godeps/_workspace/src/github.com/zenazn/goji/goji.go deleted file mode 100644 index fcdcf9a..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/goji.go +++ /dev/null @@ -1,77 +0,0 @@ -/* -Package goji provides an out-of-box web server with reasonable defaults. - -Example: - package main - - import ( - "fmt" - "net/http" - - "github.com/zenazn/goji" - "github.com/zenazn/goji/web" - ) - - func hello(c web.C, w http.ResponseWriter, r *http.Request) { - fmt.Fprintf(w, "Hello, %s!", c.URLParams["name"]) - } - - func main() { - goji.Get("/hello/:name", hello) - goji.Serve() - } - -This package exists purely as a convenience to programmers who want to get -started as quickly as possible. It draws almost all of its code from goji's -subpackages, the most interesting of which is goji/web, and where most of the -documentation for the web framework lives. - -A side effect of this package's ease-of-use is the fact that it is opinionated. -If you don't like (or have outgrown) its opinions, it should be straightforward -to use the APIs of goji's subpackages to reimplement things to your liking. Both -methods of using this library are equally well supported. - -Goji requires Go 1.2 or newer. -*/ -package goji - -import ( - "flag" - "log" - "net/http" - - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/zenazn/goji/bind" - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/zenazn/goji/graceful" -) - -func init() { - bind.WithFlag() - if fl := log.Flags(); fl&log.Ltime != 0 { - log.SetFlags(fl | log.Lmicroseconds) - } -} - -// Serve starts Goji using reasonable defaults. -func Serve() { - if !flag.Parsed() { - flag.Parse() - } - - // Install our handler at the root of the standard net/http default mux. - // This allows packages like expvar to continue working as expected. - http.Handle("/", DefaultMux) - - listener := bind.Default() - log.Println("Starting Goji on", listener.Addr()) - - graceful.HandleSignals() - bind.Ready() - - err := graceful.Serve(listener, http.DefaultServeMux) - - if err != nil { - log.Fatal(err) - } - - graceful.Wait() -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/graceful/conn_test.go b/Godeps/_workspace/src/github.com/zenazn/goji/graceful/conn_test.go deleted file mode 100644 index d86f12e..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/graceful/conn_test.go +++ /dev/null @@ -1,63 +0,0 @@ -package graceful - -import ( - "net" - "time" -) - -// Stub out a net.Conn. This is going to be painful. - -type fakeAddr struct{} - -func (f fakeAddr) Network() string { - return "fake" -} -func (f fakeAddr) String() string { - return "fake" -} - -type fakeConn struct { - onRead, onWrite, onClose, onLocalAddr, onRemoteAddr func() - onSetDeadline, onSetReadDeadline, onSetWriteDeadline func() -} - -// Here's my number, so... -func callMeMaybe(f func()) { - // I apologize for nothing. - if f != nil { - f() - } -} - -func (f fakeConn) Read(b []byte) (int, error) { - callMeMaybe(f.onRead) - return len(b), nil -} -func (f fakeConn) Write(b []byte) (int, error) { - callMeMaybe(f.onWrite) - return len(b), nil -} -func (f fakeConn) Close() error { - callMeMaybe(f.onClose) - return nil -} -func (f fakeConn) LocalAddr() net.Addr { - callMeMaybe(f.onLocalAddr) - return fakeAddr{} -} -func (f fakeConn) RemoteAddr() net.Addr { - callMeMaybe(f.onRemoteAddr) - return fakeAddr{} -} -func (f fakeConn) SetDeadline(t time.Time) error { - callMeMaybe(f.onSetDeadline) - return nil -} -func (f fakeConn) SetReadDeadline(t time.Time) error { - callMeMaybe(f.onSetReadDeadline) - return nil -} -func (f fakeConn) SetWriteDeadline(t time.Time) error { - callMeMaybe(f.onSetWriteDeadline) - return nil -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/graceful/einhorn.go b/Godeps/_workspace/src/github.com/zenazn/goji/graceful/einhorn.go deleted file mode 100644 index 082d1c4..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/graceful/einhorn.go +++ /dev/null @@ -1,21 +0,0 @@ -// +build !windows - -package graceful - -import ( - "os" - "strconv" - "syscall" -) - -func init() { - // This is a little unfortunate: goji/bind already knows whether we're - // running under einhorn, but we don't want to introduce a dependency - // between the two packages. Since the check is short enough, inlining - // it here seems "fine." - mpid, err := strconv.Atoi(os.Getenv("EINHORN_MASTER_PID")) - if err != nil || mpid != os.Getppid() { - return - } - stdSignals = append(stdSignals, syscall.SIGUSR2) -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/graceful/graceful.go b/Godeps/_workspace/src/github.com/zenazn/goji/graceful/graceful.go deleted file mode 100644 index 13537e7..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/graceful/graceful.go +++ /dev/null @@ -1,133 +0,0 @@ -/* -Package graceful implements graceful shutdown for HTTP servers by closing idle -connections after receiving a signal. By default, this package listens for -interrupts (i.e., SIGINT), but when it detects that it is running under Einhorn -it will additionally listen for SIGUSR2 as well, giving your application -automatic support for graceful upgrades. - -It's worth mentioning explicitly that this package is a hack to shim graceful -shutdown behavior into the net/http package provided in Go 1.2. It was written -by carefully reading the sequence of function calls net/http happened to use as -of this writing and finding enough surface area with which to add appropriate -behavior. There's a very good chance that this package will cease to work in -future versions of Go, but with any luck the standard library will add support -of its own by then (https://code.google.com/p/go/issues/detail?id=4674). - -If you're interested in figuring out how this package works, we suggest you read -the documentation for WrapConn() and net.go. -*/ -package graceful - -import ( - "crypto/tls" - "net" - "net/http" - "time" -) - -/* -You might notice that these methods look awfully similar to the methods of the -same name from the go standard library--that's because they were stolen from -there! If go were more like, say, Ruby, it'd actually be possible to shim just -the Serve() method, since we can do everything we want from there. However, it's -not possible to get the other methods which call Serve() (ListenAndServe(), say) -to call your shimmed copy--they always call the original. - -Since I couldn't come up with a better idea, I just copy-and-pasted both -ListenAndServe and ListenAndServeTLS here more-or-less verbatim. "Oh well!" -*/ - -// Type Server is exactly the same as an http.Server, but provides more graceful -// implementations of its methods. -type Server http.Server - -func (srv *Server) Serve(l net.Listener) (err error) { - go func() { - <-kill - l.Close() - }() - l = WrapListener(l) - - // Spawn a shadow http.Server to do the actual servering. We do this - // because we need to sketch on some of the parameters you passed in, - // and it's nice to keep our sketching to ourselves. - shadow := *(*http.Server)(srv) - - if shadow.ReadTimeout == 0 { - shadow.ReadTimeout = forever - } - shadow.Handler = Middleware(shadow.Handler) - - err = shadow.Serve(l) - - // We expect an error when we close the listener, so we indiscriminately - // swallow Serve errors when we're in a shutdown state. - select { - case <-kill: - return nil - default: - return err - } -} - -// About 200 years, also known as "forever" -const forever time.Duration = 200 * 365 * 24 * time.Hour - -func (srv *Server) ListenAndServe() error { - addr := srv.Addr - if addr == "" { - addr = ":http" - } - l, e := net.Listen("tcp", addr) - if e != nil { - return e - } - return srv.Serve(l) -} - -func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error { - addr := srv.Addr - if addr == "" { - addr = ":https" - } - config := &tls.Config{} - if srv.TLSConfig != nil { - *config = *srv.TLSConfig - } - if config.NextProtos == nil { - config.NextProtos = []string{"http/1.1"} - } - - var err error - config.Certificates = make([]tls.Certificate, 1) - config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile) - if err != nil { - return err - } - - conn, err := net.Listen("tcp", addr) - if err != nil { - return err - } - - tlsListener := tls.NewListener(conn, config) - return srv.Serve(tlsListener) -} - -// ListenAndServe behaves exactly like the net/http function of the same name. -func ListenAndServe(addr string, handler http.Handler) error { - server := &Server{Addr: addr, Handler: handler} - return server.ListenAndServe() -} - -// ListenAndServeTLS behaves exactly like the net/http function of the same name. -func ListenAndServeTLS(addr, certfile, keyfile string, handler http.Handler) error { - server := &Server{Addr: addr, Handler: handler} - return server.ListenAndServeTLS(certfile, keyfile) -} - -// Serve behaves exactly like the net/http function of the same name. -func Serve(l net.Listener, handler http.Handler) error { - server := &Server{Handler: handler} - return server.Serve(l) -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/graceful/middleware.go b/Godeps/_workspace/src/github.com/zenazn/goji/graceful/middleware.go deleted file mode 100644 index 3e17620..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/graceful/middleware.go +++ /dev/null @@ -1,121 +0,0 @@ -package graceful - -import ( - "bufio" - "io" - "net" - "net/http" -) - -/* -Middleware adds graceful shutdown capabilities to the given handler. When a -graceful shutdown is in progress, this middleware intercepts responses to add a -"Connection: close" header to politely inform the client that we are about to go -away. - -This package creates a shim http.ResponseWriter that it passes to subsequent -handlers. Unfortunately, there's a great many optional interfaces that this -http.ResponseWriter might implement (e.g., http.CloseNotifier, http.Flusher, and -http.Hijacker), and in order to perfectly proxy all of these options we'd be -left with some kind of awful powerset of ResponseWriters, and that's not even -counting all the other custom interfaces you might be expecting. Instead of -doing that, we have implemented two kinds of proxies: one that contains no -additional methods (i.e., exactly corresponding to the http.ResponseWriter -interface), and one that supports all three of http.CloseNotifier, http.Flusher, -and http.Hijacker. If you find that this is not enough, the original -http.ResponseWriter can be retrieved by calling Unwrap() on the proxy object. - -This middleware is automatically applied to every http.Handler passed to this -package, and most users will not need to call this function directly. It is -exported primarily for documentation purposes and in the off chance that someone -really wants more control over their http.Server than we currently provide. -*/ -func Middleware(h http.Handler) http.Handler { - if h == nil { - return nil - } - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - _, cn := w.(http.CloseNotifier) - _, fl := w.(http.Flusher) - _, hj := w.(http.Hijacker) - _, rf := w.(io.ReaderFrom) - - bw := basicWriter{ResponseWriter: w} - - if cn && fl && hj && rf { - h.ServeHTTP(&fancyWriter{bw}, r) - } else { - h.ServeHTTP(&bw, r) - } - if !bw.headerWritten { - bw.maybeClose() - } - }) -} - -type basicWriter struct { - http.ResponseWriter - headerWritten bool -} - -func (b *basicWriter) maybeClose() { - b.headerWritten = true - select { - case <-kill: - b.ResponseWriter.Header().Set("Connection", "close") - default: - } -} - -func (b *basicWriter) WriteHeader(code int) { - b.maybeClose() - b.ResponseWriter.WriteHeader(code) -} - -func (b *basicWriter) Write(buf []byte) (int, error) { - if !b.headerWritten { - b.maybeClose() - } - return b.ResponseWriter.Write(buf) -} - -func (b *basicWriter) Unwrap() http.ResponseWriter { - return b.ResponseWriter -} - -// Optimize for the common case of a ResponseWriter that supports all three of -// CloseNotifier, Flusher, and Hijacker. -type fancyWriter struct { - basicWriter -} - -func (f *fancyWriter) CloseNotify() <-chan bool { - cn := f.basicWriter.ResponseWriter.(http.CloseNotifier) - return cn.CloseNotify() -} -func (f *fancyWriter) Flush() { - fl := f.basicWriter.ResponseWriter.(http.Flusher) - fl.Flush() -} -func (f *fancyWriter) Hijack() (c net.Conn, b *bufio.ReadWriter, e error) { - hj := f.basicWriter.ResponseWriter.(http.Hijacker) - c, b, e = hj.Hijack() - - if conn, ok := c.(hijackConn); ok { - c = conn.hijack() - } - - return -} -func (f *fancyWriter) ReadFrom(r io.Reader) (int64, error) { - rf := f.basicWriter.ResponseWriter.(io.ReaderFrom) - if !f.basicWriter.headerWritten { - f.basicWriter.maybeClose() - } - return rf.ReadFrom(r) -} - -var _ http.CloseNotifier = &fancyWriter{} -var _ http.Flusher = &fancyWriter{} -var _ http.Hijacker = &fancyWriter{} -var _ io.ReaderFrom = &fancyWriter{} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/graceful/middleware_test.go b/Godeps/_workspace/src/github.com/zenazn/goji/graceful/middleware_test.go deleted file mode 100644 index ecec606..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/graceful/middleware_test.go +++ /dev/null @@ -1,68 +0,0 @@ -package graceful - -import ( - "net/http" - "testing" -) - -type fakeWriter http.Header - -func (f fakeWriter) Header() http.Header { - return http.Header(f) -} -func (f fakeWriter) Write(buf []byte) (int, error) { - return len(buf), nil -} -func (f fakeWriter) WriteHeader(status int) {} - -func testClose(t *testing.T, h http.Handler, expectClose bool) { - m := Middleware(h) - r, _ := http.NewRequest("GET", "/", nil) - w := make(fakeWriter) - m.ServeHTTP(w, r) - - c, ok := w["Connection"] - if expectClose { - if !ok || len(c) != 1 || c[0] != "close" { - t.Fatal("Expected 'Connection: close'") - } - } else { - if ok { - t.Fatal("Did not expect Connection header") - } - } -} - -func TestNormal(t *testing.T) { - kill = make(chan struct{}) - h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte{}) - }) - testClose(t, h, false) -} - -func TestClose(t *testing.T) { - kill = make(chan struct{}) - h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - close(kill) - }) - testClose(t, h, true) -} - -func TestCloseWriteHeader(t *testing.T) { - kill = make(chan struct{}) - h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - close(kill) - w.WriteHeader(200) - }) - testClose(t, h, true) -} - -func TestCloseWrite(t *testing.T) { - kill = make(chan struct{}) - h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - close(kill) - w.Write([]byte{}) - }) - testClose(t, h, true) -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/graceful/net.go b/Godeps/_workspace/src/github.com/zenazn/goji/graceful/net.go deleted file mode 100644 index 5573796..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/graceful/net.go +++ /dev/null @@ -1,198 +0,0 @@ -package graceful - -import ( - "io" - "net" - "sync" - "time" -) - -type listener struct { - net.Listener -} - -type gracefulConn interface { - gracefulShutdown() -} - -// WrapListener wraps an arbitrary net.Listener for use with graceful shutdowns. -// All net.Conn's Accept()ed by this listener will be auto-wrapped as if -// WrapConn() were called on them. -func WrapListener(l net.Listener) net.Listener { - return listener{l} -} - -func (l listener) Accept() (net.Conn, error) { - conn, err := l.Listener.Accept() - if err != nil { - return nil, err - } - - return WrapConn(conn), nil -} - -/* -WrapConn wraps an arbitrary connection for use with graceful shutdowns. The -graceful shutdown process will ensure that this connection is closed before -terminating the process. - -In order to use this function, you must call SetReadDeadline() before the call -to Read() you might make to read a new request off the wire. The connection is -eligible for abrupt closing at any point between when the call to -SetReadDeadline() returns and when the call to Read returns with new data. It -does not matter what deadline is given to SetReadDeadline()--the default HTTP -server provided by this package sets a deadline far into the future when a -deadline is not provided, for instance. - -Unfortunately, this means that it's difficult to use SetReadDeadline() in a -great many perfectly reasonable circumstances, such as to extend a deadline -after more data has been read, without the connection being eligible for -"graceful" termination at an undesirable time. Since this package was written -explicitly to target net/http, which does not as of this writing do any of this, -fixing the semantics here does not seem especially urgent. - -As an optimization for net/http over TCP, if the input connection supports the -ReadFrom() function, the returned connection will as well. This allows the net -package to use sendfile(2) on certain platforms in certain circumstances. -*/ -func WrapConn(c net.Conn) net.Conn { - wg.Add(1) - - nc := conn{ - Conn: c, - closing: make(chan struct{}), - } - - if _, ok := c.(io.ReaderFrom); ok { - c = &sendfile{nc} - } else { - c = &nc - } - - go c.(gracefulConn).gracefulShutdown() - - return c -} - -type connstate int - -/* -State diagram. (Waiting) is the starting state. - -(Waiting) -----Read()-----> Working ---+ - | ^ / | ^ Read() - | \ / | +----+ - kill SetReadDeadline() kill - | | +-----+ - V V V Read() - Dead <-SetReadDeadline()-- Dying ----+ - ^ - | - +--Close()--- [from any state] - -*/ - -const ( - // Waiting for more data, and eligible for killing - csWaiting connstate = iota - // In the middle of a connection - csWorking - // Kill has been requested, but waiting on request to finish up - csDying - // Connection is gone forever. Also used when a connection gets hijacked - csDead -) - -type conn struct { - net.Conn - m sync.Mutex - state connstate - closing chan struct{} -} -type sendfile struct{ conn } - -func (c *conn) gracefulShutdown() { - select { - case <-kill: - case <-c.closing: - return - } - c.m.Lock() - defer c.m.Unlock() - - switch c.state { - case csWaiting: - c.unlockedClose(true) - case csWorking: - c.state = csDying - } -} - -func (c *conn) unlockedClose(closeConn bool) { - if closeConn { - c.Conn.Close() - } - close(c.closing) - wg.Done() - c.state = csDead -} - -// We do some hijinks to support hijacking. The semantics here is that any -// connection that gets hijacked is dead to us: we return the raw net.Conn and -// stop tracking the connection entirely. -type hijackConn interface { - hijack() net.Conn -} - -func (c *conn) hijack() net.Conn { - c.m.Lock() - defer c.m.Unlock() - if c.state != csDead { - close(c.closing) - wg.Done() - c.state = csDead - } - return c.Conn -} - -func (c *conn) Read(b []byte) (n int, err error) { - defer func() { - c.m.Lock() - defer c.m.Unlock() - - if c.state == csWaiting { - c.state = csWorking - } - }() - - return c.Conn.Read(b) -} -func (c *conn) Close() error { - defer func() { - c.m.Lock() - defer c.m.Unlock() - - if c.state != csDead { - c.unlockedClose(false) - } - }() - return c.Conn.Close() -} -func (c *conn) SetReadDeadline(t time.Time) error { - defer func() { - c.m.Lock() - defer c.m.Unlock() - switch c.state { - case csDying: - c.unlockedClose(false) - case csWorking: - c.state = csWaiting - } - }() - return c.Conn.SetReadDeadline(t) -} - -func (s *sendfile) ReadFrom(r io.Reader) (int64, error) { - // conn.Conn.KHAAAAAAAANNNNNN - return s.conn.Conn.(io.ReaderFrom).ReadFrom(r) -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/graceful/net_test.go b/Godeps/_workspace/src/github.com/zenazn/goji/graceful/net_test.go deleted file mode 100644 index d6e7208..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/graceful/net_test.go +++ /dev/null @@ -1,198 +0,0 @@ -package graceful - -import ( - "io" - "net" - "strings" - "testing" - "time" -) - -var b = make([]byte, 0) - -func connify(c net.Conn) *conn { - switch c.(type) { - case (*conn): - return c.(*conn) - case (*sendfile): - return &c.(*sendfile).conn - default: - panic("IDK") - } -} - -func assertState(t *testing.T, n net.Conn, st connstate) { - c := connify(n) - c.m.Lock() - defer c.m.Unlock() - if c.state != st { - t.Fatalf("conn was %v, but expected %v", c.state, st) - } -} - -// Not super happy about making the tests dependent on the passing of time, but -// I'm not really sure what else to do. - -func expectCall(t *testing.T, ch <-chan struct{}, name string) { - select { - case <-ch: - case <-time.After(5 * time.Millisecond): - t.Fatalf("Expected call to %s", name) - } -} - -func TestCounting(t *testing.T) { - kill = make(chan struct{}) - c := WrapConn(fakeConn{}) - ch := make(chan struct{}) - - go func() { - wg.Wait() - ch <- struct{}{} - }() - - select { - case <-ch: - t.Fatal("Expected connection to keep us from quitting") - case <-time.After(5 * time.Millisecond): - } - - c.Close() - expectCall(t, ch, "wg.Wait()") -} - -func TestStateTransitions1(t *testing.T) { - kill = make(chan struct{}) - ch := make(chan struct{}) - - onclose := make(chan struct{}) - read := make(chan struct{}) - deadline := make(chan struct{}) - c := WrapConn(fakeConn{ - onClose: func() { - onclose <- struct{}{} - }, - onRead: func() { - read <- struct{}{} - }, - onSetReadDeadline: func() { - deadline <- struct{}{} - }, - }) - - go func() { - wg.Wait() - ch <- struct{}{} - }() - - assertState(t, c, csWaiting) - - // Waiting + Read() = Working - go c.Read(b) - expectCall(t, read, "c.Read()") - assertState(t, c, csWorking) - - // Working + SetReadDeadline() = Waiting - go c.SetReadDeadline(time.Now()) - expectCall(t, deadline, "c.SetReadDeadline()") - assertState(t, c, csWaiting) - - // Waiting + kill = Dead - close(kill) - expectCall(t, onclose, "c.Close()") - assertState(t, c, csDead) - - expectCall(t, ch, "wg.Wait()") -} - -func TestStateTransitions2(t *testing.T) { - kill = make(chan struct{}) - ch := make(chan struct{}) - onclose := make(chan struct{}) - read := make(chan struct{}) - deadline := make(chan struct{}) - c := WrapConn(fakeConn{ - onClose: func() { - onclose <- struct{}{} - }, - onRead: func() { - read <- struct{}{} - }, - onSetReadDeadline: func() { - deadline <- struct{}{} - }, - }) - - go func() { - wg.Wait() - ch <- struct{}{} - }() - - assertState(t, c, csWaiting) - - // Waiting + Read() = Working - go c.Read(b) - expectCall(t, read, "c.Read()") - assertState(t, c, csWorking) - - // Working + Read() = Working - go c.Read(b) - expectCall(t, read, "c.Read()") - assertState(t, c, csWorking) - - // Working + kill = Dying - close(kill) - time.Sleep(5 * time.Millisecond) - assertState(t, c, csDying) - - // Dying + Read() = Dying - go c.Read(b) - expectCall(t, read, "c.Read()") - assertState(t, c, csDying) - - // Dying + SetReadDeadline() = Dead - go c.SetReadDeadline(time.Now()) - expectCall(t, deadline, "c.SetReadDeadline()") - assertState(t, c, csDead) - - expectCall(t, ch, "wg.Wait()") -} - -func TestHijack(t *testing.T) { - kill = make(chan struct{}) - fake := fakeConn{} - c := WrapConn(fake) - ch := make(chan struct{}) - - go func() { - wg.Wait() - ch <- struct{}{} - }() - - cc := connify(c) - if _, ok := cc.hijack().(fakeConn); !ok { - t.Error("Expected original connection back out") - } - assertState(t, c, csDead) - expectCall(t, ch, "wg.Wait()") -} - -type fakeSendfile struct { - fakeConn -} - -func (f fakeSendfile) ReadFrom(r io.Reader) (int64, error) { - return 0, nil -} - -func TestReadFrom(t *testing.T) { - kill = make(chan struct{}) - c := WrapConn(fakeSendfile{}) - r := strings.NewReader("Hello world") - - if rf, ok := c.(io.ReaderFrom); ok { - rf.ReadFrom(r) - } else { - t.Fatal("Expected a ReaderFrom in return") - } -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/graceful/signal.go b/Godeps/_workspace/src/github.com/zenazn/goji/graceful/signal.go deleted file mode 100644 index 5c2ab15..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/graceful/signal.go +++ /dev/null @@ -1,118 +0,0 @@ -package graceful - -import ( - "log" - "os" - "os/signal" - "sync" -) - -// This is the channel that the connections select on. When it is closed, the -// connections should gracefully exit. -var kill = make(chan struct{}) - -// This is the channel that the Wait() function selects on. It should only be -// closed once all the posthooks have been called. -var wait = make(chan struct{}) - -// This is the WaitGroup that indicates when all the connections have gracefully -// shut down. -var wg sync.WaitGroup - -// This lock protects the list of pre- and post- hooks below. -var hookLock sync.Mutex -var prehooks = make([]func(), 0) -var posthooks = make([]func(), 0) - -var stdSignals = []os.Signal{os.Interrupt} -var sigchan = make(chan os.Signal, 1) - -func init() { - go waitForSignal() -} - -// HandleSignals installs signal handlers for a set of standard signals. By -// default, this set only includes keyboard interrupts, however when the package -// detects that it is running under Einhorn, a SIGUSR2 handler is installed as -// well. -func HandleSignals() { - AddSignal(stdSignals...) -} - -// AddSignal adds the given signal to the set of signals that trigger a graceful -// shutdown. -func AddSignal(sig ...os.Signal) { - signal.Notify(sigchan, sig...) -} - -// ResetSignals resets the list of signals that trigger a graceful shutdown. -func ResetSignals() { - signal.Stop(sigchan) -} - -type userShutdown struct{} - -func (u userShutdown) String() string { - return "application initiated shutdown" -} -func (u userShutdown) Signal() {} - -// Shutdown manually triggers a shutdown from your application. Like Wait(), -// blocks until all connections have gracefully shut down. -func Shutdown() { - sigchan <- userShutdown{} - <-wait -} - -// PreHook registers a function to be called before any of this package's normal -// shutdown actions. All listeners will be called in the order they were added, -// from a single goroutine. -func PreHook(f func()) { - hookLock.Lock() - defer hookLock.Unlock() - - prehooks = append(prehooks, f) -} - -// PostHook registers a function to be called after all of this package's normal -// shutdown actions. All listeners will be called in the order they were added, -// from a single goroutine, and are guaranteed to be called after all listening -// connections have been closed, but before Wait() returns. -// -// If you've Hijack()ed any connections that must be gracefully shut down in -// some other way (since this library disowns all hijacked connections), it's -// reasonable to use a PostHook() to signal and wait for them. -func PostHook(f func()) { - hookLock.Lock() - defer hookLock.Unlock() - - posthooks = append(posthooks, f) -} - -func waitForSignal() { - sig := <-sigchan - log.Printf("Received %v, gracefully shutting down!", sig) - - hookLock.Lock() - defer hookLock.Unlock() - - for _, f := range prehooks { - f() - } - - close(kill) - wg.Wait() - - for _, f := range posthooks { - f() - } - - close(wait) -} - -// Wait for all connections to gracefully shut down. This is commonly called at -// the bottom of the main() function to prevent the program from exiting -// prematurely. -func Wait() { - <-wait -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/param/crazy_test.go b/Godeps/_workspace/src/github.com/zenazn/goji/param/crazy_test.go deleted file mode 100644 index 46538cd..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/param/crazy_test.go +++ /dev/null @@ -1,56 +0,0 @@ -package param - -import ( - "net/url" - "testing" -) - -type Crazy struct { - A *Crazy - B *Crazy - Value int - Slice []int - Map map[string]Crazy -} - -func TestCrazy(t *testing.T) { - t.Parallel() - - c := Crazy{} - err := Parse(url.Values{ - "A[B][B][A][Value]": {"1"}, - "B[A][A][Slice][]": {"3", "1", "4"}, - "B[Map][hello][A][Value]": {"8"}, - "A[Value]": {"2"}, - "A[Slice][]": {"9", "1", "1"}, - "Value": {"42"}, - }, &c) - if err != nil { - t.Error("Error parsing craziness: ", err) - } - - // Exhaustively checking everything here is going to be a huge pain, so - // let's just hope for the best, pretend NPEs don't exist, and hope that - // this test covers enough stuff that it's actually useful. - assertEqual(t, "c.A.B.B.A.Value", 1, c.A.B.B.A.Value) - assertEqual(t, "c.A.Value", 2, c.A.Value) - assertEqual(t, "c.Value", 42, c.Value) - assertEqual(t, `c.B.Map["hello"].A.Value`, 8, c.B.Map["hello"].A.Value) - - assertEqual(t, "c.A.B.B.B", (*Crazy)(nil), c.A.B.B.B) - assertEqual(t, "c.A.B.A", (*Crazy)(nil), c.A.B.A) - assertEqual(t, "c.A.A", (*Crazy)(nil), c.A.A) - - if c.Slice != nil || c.Map != nil { - t.Error("Map and Slice should not be set") - } - - sl := c.B.A.A.Slice - if len(sl) != 3 || sl[0] != 3 || sl[1] != 1 || sl[2] != 4 { - t.Error("Something is wrong with c.B.A.A.Slice") - } - sl = c.A.Slice - if len(sl) != 3 || sl[0] != 9 || sl[1] != 1 || sl[2] != 1 { - t.Error("Something is wrong with c.A.Slice") - } -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/param/error_helpers.go b/Godeps/_workspace/src/github.com/zenazn/goji/param/error_helpers.go deleted file mode 100644 index 9477d3a..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/param/error_helpers.go +++ /dev/null @@ -1,25 +0,0 @@ -package param - -import ( - "errors" - "fmt" - "log" -) - -// Testing log.Fatal in tests is... not a thing. Allow tests to stub it out. -var pebkacTesting bool - -const errPrefix = "param/parse: " -const yourFault = " This is a bug in your use of the param library." - -// Problem exists between keyboard and chair. This function is used in cases of -// programmer error, i.e. an inappropriate use of the param library, to -// immediately force the program to halt with a hopefully helpful error message. -func pebkac(format string, a ...interface{}) { - err := errors.New(errPrefix + fmt.Sprintf(format, a...) + yourFault) - if pebkacTesting { - panic(err) - } else { - log.Fatal(err) - } -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/param/errors.go b/Godeps/_workspace/src/github.com/zenazn/goji/param/errors.go deleted file mode 100644 index e6b9de6..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/param/errors.go +++ /dev/null @@ -1,112 +0,0 @@ -package param - -import ( - "fmt" - "reflect" -) - -// TypeError is an error type returned when param has difficulty deserializing a -// parameter value. -type TypeError struct { - // The key that was in error. - Key string - // The type that was expected. - Type reflect.Type - // The underlying error produced as part of the deserialization process, - // if one exists. - Err error -} - -func (t TypeError) Error() string { - return fmt.Sprintf("param: error parsing key %q as %v: %v", t.Key, t.Type, - t.Err) -} - -// SingletonError is an error type returned when a parameter is passed multiple -// times when only a single value is expected. For example, for a struct with -// integer field "foo", "foo=1&foo=2" will return a SingletonError with key -// "foo". -type SingletonError struct { - // The key that was in error. - Key string - // The type that was expected for that key. - Type reflect.Type - // The list of values that were provided for that key. - Values []string -} - -func (s SingletonError) Error() string { - return fmt.Sprintf("param: error parsing key %q: expected single "+ - "value but was given %d: %v", s.Key, len(s.Values), s.Values) -} - -// NestingError is an error type returned when a key is nested when the target -// type does not support nesting of the given type. For example, deserializing -// the parameter key "anint[foo]" into a struct that defines an integer param -// "anint" will produce a NestingError with key "anint" and nesting "[foo]". -type NestingError struct { - // The portion of the key that was correctly parsed into a value. - Key string - // The type of the key that was invalidly nested on. - Type reflect.Type - // The portion of the key that could not be parsed due to invalid - // nesting. - Nesting string -} - -func (n NestingError) Error() string { - return fmt.Sprintf("param: error parsing key %q: invalid nesting "+ - "%q on %s key %q", n.Key+n.Nesting, n.Nesting, n.Type, n.Key) -} - -// SyntaxErrorSubtype describes what sort of syntax error was encountered. -type SyntaxErrorSubtype int - -const ( - MissingOpeningBracket SyntaxErrorSubtype = iota + 1 - MissingClosingBracket -) - -// SyntaxError is an error type returned when a key is incorrectly formatted. -type SyntaxError struct { - // The key for which there was a syntax error. - Key string - // The subtype of the syntax error, which describes what sort of error - // was encountered. - Subtype SyntaxErrorSubtype - // The part of the key (generally the suffix) that was in error. - ErrorPart string -} - -func (s SyntaxError) Error() string { - prefix := fmt.Sprintf("param: syntax error while parsing key %q: ", - s.Key) - - switch s.Subtype { - case MissingOpeningBracket: - return prefix + fmt.Sprintf("expected opening bracket, got %q", - s.ErrorPart) - case MissingClosingBracket: - return prefix + fmt.Sprintf("expected closing bracket in %q", - s.ErrorPart) - default: - panic("switch is not exhaustive!") - } -} - -// KeyError is an error type returned when an unknown field is set on a struct. -type KeyError struct { - // The full key that was in error. - FullKey string - // The key of the struct that did not have the given field. - Key string - // The type of the struct that did not have the given field. - Type reflect.Type - // The name of the field which was not present. - Field string -} - -func (k KeyError) Error() string { - return fmt.Sprintf("param: error parsing key %q: unknown field %q on "+ - "struct %q of type %v", k.FullKey, k.Field, k.Key, k.Type) -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/param/param.go b/Godeps/_workspace/src/github.com/zenazn/goji/param/param.go deleted file mode 100644 index 685df90..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/param/param.go +++ /dev/null @@ -1,60 +0,0 @@ -/* -Package param deserializes parameter values into a given struct using magical -reflection ponies. Inspired by gorilla/schema, but uses Rails/jQuery style param -encoding instead of their weird dotted syntax. In particular, this package was -written with the intent of parsing the output of jQuery.param. - -This package uses struct tags to guess what names things ought to have. If a -struct value has a "param" tag defined, it will use that. If there is no "param" -tag defined, the name part of the "json" tag will be used. If that is not -defined, the name of the field itself will be used (no case transformation is -performed). - -If the name derived in this way is the string "-", param will refuse to set that -value. - -The parser is extremely strict, and will return an error if it has any -difficulty whatsoever in parsing any parameter, or if there is any kind of type -mismatch. -*/ -package param - -import ( - "net/url" - "reflect" - "strings" -) - -// Parse the given arguments into the the given pointer to a struct object. -func Parse(params url.Values, target interface{}) (err error) { - v := reflect.ValueOf(target) - - defer func() { - if r := recover(); r != nil { - var ok bool - err, ok = r.(error) - if !ok { - panic(err) - } - } - }() - - if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Struct { - pebkac("Target of param.Parse must be a pointer to a struct. "+ - "We instead were passed a %v", v.Type()) - } - - el := v.Elem() - t := el.Type() - cache := cacheStruct(t) - - for key, values := range params { - sk, keytail := key, "" - if i := strings.IndexRune(key, '['); i != -1 { - sk, keytail = sk[:i], sk[i:] - } - parseStructField(cache, key, sk, keytail, values, el) - } - - return nil -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/param/param_test.go b/Godeps/_workspace/src/github.com/zenazn/goji/param/param_test.go deleted file mode 100644 index 48f5e42..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/param/param_test.go +++ /dev/null @@ -1,505 +0,0 @@ -package param - -import ( - "net/url" - "reflect" - "strings" - "testing" - "time" -) - -type Everything struct { - Bool bool - Int int - Uint uint - Float float64 - Map map[string]int - Slice []int - String string - Struct Sub - Time time.Time - - PBool *bool - PInt *int - PUint *uint - PFloat *float64 - PMap *map[string]int - PSlice *[]int - PString *string - PStruct *Sub - PTime *time.Time - - PPInt **int - - ABool MyBool - AInt MyInt - AUint MyUint - AFloat MyFloat - AMap MyMap - APtr MyPtr - ASlice MySlice - AString MyString -} - -type Sub struct { - A int - B int -} - -type MyBool bool -type MyInt int -type MyUint uint -type MyFloat float64 -type MyMap map[MyString]MyInt -type MyPtr *MyInt -type MySlice []MyInt -type MyString string - -var boolAnswers = map[string]bool{ - "true": true, - "false": false, - "0": false, - "1": true, - "on": true, - "": false, -} - -var testTimeString = "1996-12-19T16:39:57-08:00" -var testTime time.Time - -func init() { - testTime, _ = time.Parse(time.RFC3339, testTimeString) -} - -func singletonErrors(t *testing.T, field, valid, invalid string) { - e := Everything{} - - err := Parse(url.Values{field: {invalid}}, &e) - if err == nil { - t.Errorf("Expected error parsing %q as %s", invalid, field) - } - - err = Parse(url.Values{field + "[]": {valid}}, &e) - if err == nil { - t.Errorf("Expected error parsing nested %s", field) - } - - err = Parse(url.Values{field + "[nested]": {valid}}, &e) - if err == nil { - t.Errorf("Expected error parsing nested %s", field) - } - - err = Parse(url.Values{field: {valid, valid}}, &e) - if err == nil { - t.Errorf("Expected error passing %s twice", field) - } -} - -func TestBool(t *testing.T) { - t.Parallel() - - for val, correct := range boolAnswers { - e := Everything{} - e.Bool = !correct - err := Parse(url.Values{"Bool": {val}}, &e) - if err != nil { - t.Error("Parse error on key: ", val) - } - assertEqual(t, "e.Bool", correct, e.Bool) - } -} - -func TestBoolTyped(t *testing.T) { - t.Parallel() - - e := Everything{} - err := Parse(url.Values{"ABool": {"true"}}, &e) - if err != nil { - t.Error("Parse error for typed bool") - } - assertEqual(t, "e.ABool", MyBool(true), e.ABool) -} - -func TestBoolErrors(t *testing.T) { - t.Parallel() - singletonErrors(t, "Bool", "true", "llama") -} - -var intAnswers = map[string]int{ - "0": 0, - "9001": 9001, - "-42": -42, -} - -func TestInt(t *testing.T) { - t.Parallel() - - for val, correct := range intAnswers { - e := Everything{} - e.Int = 1 - err := Parse(url.Values{"Int": {val}}, &e) - if err != nil { - t.Error("Parse error on key: ", val) - } - assertEqual(t, "e.Int", correct, e.Int) - } -} - -func TestIntTyped(t *testing.T) { - t.Parallel() - - e := Everything{} - err := Parse(url.Values{"AInt": {"1"}}, &e) - if err != nil { - t.Error("Parse error for typed int") - } - assertEqual(t, "e.AInt", MyInt(1), e.AInt) -} - -func TestIntErrors(t *testing.T) { - t.Parallel() - singletonErrors(t, "Int", "1", "llama") - - e := Everything{} - err := Parse(url.Values{"Int": {"4.2"}}, &e) - if err == nil { - t.Error("Expected error parsing float as int") - } -} - -var uintAnswers = map[string]uint{ - "0": 0, - "9001": 9001, -} - -func TestUint(t *testing.T) { - t.Parallel() - - for val, correct := range uintAnswers { - e := Everything{} - e.Uint = 1 - err := Parse(url.Values{"Uint": {val}}, &e) - if err != nil { - t.Error("Parse error on key: ", val) - } - assertEqual(t, "e.Uint", correct, e.Uint) - } -} - -func TestUintTyped(t *testing.T) { - t.Parallel() - - e := Everything{} - err := Parse(url.Values{"AUint": {"1"}}, &e) - if err != nil { - t.Error("Parse error for typed uint") - } - assertEqual(t, "e.AUint", MyUint(1), e.AUint) -} - -func TestUintErrors(t *testing.T) { - t.Parallel() - singletonErrors(t, "Uint", "1", "llama") - - e := Everything{} - err := Parse(url.Values{"Uint": {"4.2"}}, &e) - if err == nil { - t.Error("Expected error parsing float as uint") - } - - err = Parse(url.Values{"Uint": {"-42"}}, &e) - if err == nil { - t.Error("Expected error parsing negative number as uint") - } -} - -var floatAnswers = map[string]float64{ - "0": 0, - "9001": 9001, - "-42": -42, - "9001.0": 9001.0, - "4.2": 4.2, - "-9.000001": -9.000001, -} - -func TestFloat(t *testing.T) { - t.Parallel() - - for val, correct := range floatAnswers { - e := Everything{} - e.Float = 1 - err := Parse(url.Values{"Float": {val}}, &e) - if err != nil { - t.Error("Parse error on key: ", val) - } - assertEqual(t, "e.Float", correct, e.Float) - } -} - -func TestFloatTyped(t *testing.T) { - t.Parallel() - - e := Everything{} - err := Parse(url.Values{"AFloat": {"1.0"}}, &e) - if err != nil { - t.Error("Parse error for typed float") - } - assertEqual(t, "e.AFloat", MyFloat(1.0), e.AFloat) -} - -func TestFloatErrors(t *testing.T) { - t.Parallel() - singletonErrors(t, "Float", "1.0", "llama") -} - -func TestMap(t *testing.T) { - t.Parallel() - e := Everything{} - - err := Parse(url.Values{ - "Map[one]": {"1"}, - "Map[two]": {"2"}, - "Map[three]": {"3"}, - }, &e) - if err != nil { - t.Error("Parse error in map: ", err) - } - - for k, v := range map[string]int{"one": 1, "two": 2, "three": 3} { - if mv, ok := e.Map[k]; !ok { - t.Errorf("Key %q not in map", k) - } else { - assertEqual(t, "Map["+k+"]", v, mv) - } - } -} - -func TestMapTyped(t *testing.T) { - t.Parallel() - - e := Everything{} - err := Parse(url.Values{"AMap[one]": {"1"}}, &e) - if err != nil { - t.Error("Parse error for typed map") - } - assertEqual(t, "e.AMap[one]", MyInt(1), e.AMap[MyString("one")]) -} - -func TestMapErrors(t *testing.T) { - t.Parallel() - e := Everything{} - - err := Parse(url.Values{"Map[]": {"llama"}}, &e) - if err == nil { - t.Error("expected error parsing empty map key") - } - - err = Parse(url.Values{"Map": {"llama"}}, &e) - if err == nil { - t.Error("expected error parsing map without key") - } - - err = Parse(url.Values{"Map[": {"llama"}}, &e) - if err == nil { - t.Error("expected error parsing map with malformed key") - } -} - -func testPtr(t *testing.T, key, in string, out interface{}) { - e := Everything{} - - err := Parse(url.Values{key: {in}}, &e) - if err != nil { - t.Errorf("Parse error while parsing pointer e.%s: %v", key, err) - } - fieldKey := key - if i := strings.IndexRune(fieldKey, '['); i >= 0 { - fieldKey = fieldKey[:i] - } - v := reflect.ValueOf(e).FieldByName(fieldKey) - if v.IsNil() { - t.Errorf("Expected param to allocate pointer for e.%s", key) - } else { - assertEqual(t, "*e."+key, out, v.Elem().Interface()) - } -} - -func TestPtr(t *testing.T) { - t.Parallel() - testPtr(t, "PBool", "true", true) - testPtr(t, "PInt", "2", 2) - testPtr(t, "PUint", "2", uint(2)) - testPtr(t, "PFloat", "2.0", 2.0) - testPtr(t, "PMap[llama]", "4", map[string]int{"llama": 4}) - testPtr(t, "PSlice[]", "4", []int{4}) - testPtr(t, "PString", "llama", "llama") - testPtr(t, "PStruct[B]", "2", Sub{0, 2}) - testPtr(t, "PTime", testTimeString, testTime) - - foo := 2 - testPtr(t, "PPInt", "2", &foo) -} - -func TestPtrTyped(t *testing.T) { - t.Parallel() - - e := Everything{} - err := Parse(url.Values{"APtr": {"1"}}, &e) - if err != nil { - t.Error("Parse error for typed pointer") - } - assertEqual(t, "e.APtr", MyInt(1), *e.APtr) -} - -func TestSlice(t *testing.T) { - t.Parallel() - - e := Everything{} - err := Parse(url.Values{"Slice[]": {"3", "1", "4"}}, &e) - if err != nil { - t.Error("Parse error for slice") - } - if e.Slice == nil { - t.Fatal("Expected param to allocate a slice") - } - if len(e.Slice) != 3 { - t.Fatal("Expected a slice of length 3") - } - - assertEqual(t, "e.Slice[0]", 3, e.Slice[0]) - assertEqual(t, "e.Slice[1]", 1, e.Slice[1]) - assertEqual(t, "e.Slice[2]", 4, e.Slice[2]) -} - -func TestSliceTyped(t *testing.T) { - t.Parallel() - e := Everything{} - err := Parse(url.Values{"ASlice[]": {"3", "1", "4"}}, &e) - if err != nil { - t.Error("Parse error for typed slice") - } - if e.ASlice == nil { - t.Fatal("Expected param to allocate a slice") - } - if len(e.ASlice) != 3 { - t.Fatal("Expected a slice of length 3") - } - - assertEqual(t, "e.ASlice[0]", MyInt(3), e.ASlice[0]) - assertEqual(t, "e.ASlice[1]", MyInt(1), e.ASlice[1]) - assertEqual(t, "e.ASlice[2]", MyInt(4), e.ASlice[2]) -} - -func TestSliceErrors(t *testing.T) { - t.Parallel() - e := Everything{} - err := Parse(url.Values{"Slice": {"1"}}, &e) - if err == nil { - t.Error("expected error parsing slice without key") - } - - err = Parse(url.Values{"Slice[llama]": {"1"}}, &e) - if err == nil { - t.Error("expected error parsing slice with string key") - } - - err = Parse(url.Values{"Slice[": {"1"}}, &e) - if err == nil { - t.Error("expected error parsing malformed slice key") - } -} - -var stringAnswer = "This is the world's best string" - -func TestString(t *testing.T) { - t.Parallel() - e := Everything{} - - err := Parse(url.Values{"String": {stringAnswer}}, &e) - if err != nil { - t.Error("Parse error in string: ", err) - } - - assertEqual(t, "e.String", stringAnswer, e.String) -} - -func TestStringTyped(t *testing.T) { - t.Parallel() - - e := Everything{} - err := Parse(url.Values{"AString": {"llama"}}, &e) - if err != nil { - t.Error("Parse error for typed string") - } - assertEqual(t, "e.AString", MyString("llama"), e.AString) -} - -func TestStruct(t *testing.T) { - t.Parallel() - e := Everything{} - - err := Parse(url.Values{ - "Struct[A]": {"1"}, - }, &e) - if err != nil { - t.Error("Parse error in struct: ", err) - } - assertEqual(t, "e.Struct.A", 1, e.Struct.A) - assertEqual(t, "e.Struct.B", 0, e.Struct.B) - - err = Parse(url.Values{ - "Struct[A]": {"4"}, - "Struct[B]": {"2"}, - }, &e) - if err != nil { - t.Error("Parse error in struct: ", err) - } - assertEqual(t, "e.Struct.A", 4, e.Struct.A) - assertEqual(t, "e.Struct.B", 2, e.Struct.B) -} - -func TestStructErrors(t *testing.T) { - t.Parallel() - e := Everything{} - - err := Parse(url.Values{"Struct[]": {"llama"}}, &e) - if err == nil { - t.Error("expected error parsing empty struct key") - } - - err = Parse(url.Values{"Struct": {"llama"}}, &e) - if err == nil { - t.Error("expected error parsing struct without key") - } - - err = Parse(url.Values{"Struct[": {"llama"}}, &e) - if err == nil { - t.Error("expected error parsing malformed struct key") - } - - err = Parse(url.Values{"Struct[C]": {"llama"}}, &e) - if err == nil { - t.Error("expected error parsing unknown") - } -} - -func TestTextUnmarshaler(t *testing.T) { - t.Parallel() - e := Everything{} - - err := Parse(url.Values{"Time": {testTimeString}}, &e) - if err != nil { - t.Error("parse error for TextUnmarshaler (Time): ", err) - } - assertEqual(t, "e.Time", testTime, e.Time) -} - -func TestTextUnmarshalerError(t *testing.T) { - t.Parallel() - e := Everything{} - - err := Parse(url.Values{"Time": {"llama"}}, &e) - if err == nil { - t.Error("expected error parsing llama as time") - } -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/param/parse.go b/Godeps/_workspace/src/github.com/zenazn/goji/param/parse.go deleted file mode 100644 index b8c069d..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/param/parse.go +++ /dev/null @@ -1,249 +0,0 @@ -package param - -import ( - "encoding" - "fmt" - "reflect" - "strconv" - "strings" -) - -var textUnmarshalerType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem() - -// Generic parse dispatcher. This function's signature is the interface of all -// parse functions. `key` is the entire key that is currently being parsed, such -// as "foo[bar][]". `keytail` is the portion of the string that the current -// parser is responsible for, for instance "[bar][]". `values` is the list of -// values assigned to this key, and `target` is where the resulting typed value -// should be Set() to. -func parse(key, keytail string, values []string, target reflect.Value) { - t := target.Type() - if reflect.PtrTo(t).Implements(textUnmarshalerType) { - parseTextUnmarshaler(key, keytail, values, target) - return - } - - switch k := target.Kind(); k { - case reflect.Bool: - parseBool(key, keytail, values, target) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - parseInt(key, keytail, values, target) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - parseUint(key, keytail, values, target) - case reflect.Float32, reflect.Float64: - parseFloat(key, keytail, values, target) - case reflect.Map: - parseMap(key, keytail, values, target) - case reflect.Ptr: - parsePtr(key, keytail, values, target) - case reflect.Slice: - parseSlice(key, keytail, values, target) - case reflect.String: - parseString(key, keytail, values, target) - case reflect.Struct: - parseStruct(key, keytail, values, target) - - default: - pebkac("unsupported object of type %v and kind %v.", - target.Type(), k) - } -} - -// We pass down both the full key ("foo[bar][]") and the part the current layer -// is responsible for making sense of ("[bar][]"). This computes the other thing -// you probably want to know, which is the path you took to get here ("foo"). -func kpath(key, keytail string) string { - l, t := len(key), len(keytail) - return key[:l-t] -} - -// Helper for validating that a value has been passed exactly once, and that the -// user is not attempting to nest on the key. -func primitive(key, keytail string, tipe reflect.Type, values []string) { - if keytail != "" { - panic(NestingError{ - Key: kpath(key, keytail), - Type: tipe, - Nesting: keytail, - }) - } - if len(values) != 1 { - panic(SingletonError{ - Key: kpath(key, keytail), - Type: tipe, - Values: values, - }) - } -} - -func keyed(tipe reflect.Type, key, keytail string) (string, string) { - if keytail[0] != '[' { - panic(SyntaxError{ - Key: kpath(key, keytail), - Subtype: MissingOpeningBracket, - ErrorPart: keytail, - }) - } - - idx := strings.IndexRune(keytail, ']') - if idx == -1 { - panic(SyntaxError{ - Key: kpath(key, keytail), - Subtype: MissingClosingBracket, - ErrorPart: keytail[1:], - }) - } - - return keytail[1:idx], keytail[idx+1:] -} - -func parseTextUnmarshaler(key, keytail string, values []string, target reflect.Value) { - primitive(key, keytail, target.Type(), values) - - tu := target.Addr().Interface().(encoding.TextUnmarshaler) - err := tu.UnmarshalText([]byte(values[0])) - if err != nil { - panic(TypeError{ - Key: kpath(key, keytail), - Type: target.Type(), - Err: err, - }) - } -} - -func parseBool(key, keytail string, values []string, target reflect.Value) { - primitive(key, keytail, target.Type(), values) - - switch values[0] { - case "true", "1", "on": - target.SetBool(true) - case "false", "0", "": - target.SetBool(false) - default: - panic(TypeError{ - Key: kpath(key, keytail), - Type: target.Type(), - }) - } -} - -func parseInt(key, keytail string, values []string, target reflect.Value) { - t := target.Type() - primitive(key, keytail, t, values) - - i, err := strconv.ParseInt(values[0], 10, t.Bits()) - if err != nil { - panic(TypeError{ - Key: kpath(key, keytail), - Type: t, - Err: err, - }) - } - target.SetInt(i) -} - -func parseUint(key, keytail string, values []string, target reflect.Value) { - t := target.Type() - primitive(key, keytail, t, values) - - i, err := strconv.ParseUint(values[0], 10, t.Bits()) - if err != nil { - panic(TypeError{ - Key: kpath(key, keytail), - Type: t, - Err: err, - }) - } - target.SetUint(i) -} - -func parseFloat(key, keytail string, values []string, target reflect.Value) { - t := target.Type() - primitive(key, keytail, t, values) - - f, err := strconv.ParseFloat(values[0], t.Bits()) - if err != nil { - panic(TypeError{ - Key: kpath(key, keytail), - Type: t, - Err: err, - }) - } - - target.SetFloat(f) -} - -func parseString(key, keytail string, values []string, target reflect.Value) { - primitive(key, keytail, target.Type(), values) - - target.SetString(values[0]) -} - -func parseSlice(key, keytail string, values []string, target reflect.Value) { - t := target.Type() - - // BUG(carl): We currently do not handle slices of nested types. If - // support is needed, the implementation probably could be fleshed out. - if keytail != "[]" { - panic(NestingError{ - Key: kpath(key, keytail), - Type: t, - Nesting: keytail, - }) - } - - slice := reflect.MakeSlice(t, len(values), len(values)) - kp := kpath(key, keytail) - for i := range values { - // We actually cheat a little bit and modify the key so we can - // generate better debugging messages later - key := fmt.Sprintf("%s[%d]", kp, i) - parse(key, "", values[i:i+1], slice.Index(i)) - } - target.Set(slice) -} - -func parseMap(key, keytail string, values []string, target reflect.Value) { - t := target.Type() - mapkey, maptail := keyed(t, key, keytail) - - // BUG(carl): We don't support any map keys except strings, although - // there's no reason we shouldn't be able to throw the value through our - // unparsing stack. - var mk reflect.Value - if t.Key().Kind() == reflect.String { - mk = reflect.ValueOf(mapkey).Convert(t.Key()) - } else { - pebkac("key for map %v isn't a string (it's a %v).", t, t.Key()) - } - - if target.IsNil() { - target.Set(reflect.MakeMap(t)) - } - - val := target.MapIndex(mk) - if !val.IsValid() || !val.CanSet() { - // It's a teensy bit annoying that the value returned by - // MapIndex isn't Set()table if the key exists. - val = reflect.New(t.Elem()).Elem() - } - parse(key, maptail, values, val) - target.SetMapIndex(mk, val) -} - -func parseStruct(key, keytail string, values []string, target reflect.Value) { - t := target.Type() - sk, skt := keyed(t, key, keytail) - cache := cacheStruct(t) - - parseStructField(cache, key, sk, skt, values, target) -} - -func parsePtr(key, keytail string, values []string, target reflect.Value) { - t := target.Type() - - if target.IsNil() { - target.Set(reflect.New(t.Elem())) - } - parse(key, keytail, values, target.Elem()) -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/param/pebkac_test.go b/Godeps/_workspace/src/github.com/zenazn/goji/param/pebkac_test.go deleted file mode 100644 index 71d64eb..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/param/pebkac_test.go +++ /dev/null @@ -1,58 +0,0 @@ -package param - -import ( - "net/url" - "strings" - "testing" -) - -type Bad struct { - Unknown interface{} -} - -type Bad2 struct { - Unknown *interface{} -} - -type Bad3 struct { - BadMap map[int]int -} - -// These tests are not parallel so we can frob pebkac behavior in an isolated -// way - -func assertPebkac(t *testing.T, err error) { - if err == nil { - t.Error("Expected PEBKAC error message") - } else if !strings.HasSuffix(err.Error(), yourFault) { - t.Errorf("Expected PEBKAC error, but got: %v", err) - } -} - -func TestBadInputs(t *testing.T) { - pebkacTesting = true - - err := Parse(url.Values{"Unknown": {"4"}}, Bad{}) - assertPebkac(t, err) - - b := &Bad{} - err = Parse(url.Values{"Unknown": {"4"}}, &b) - assertPebkac(t, err) - - pebkacTesting = false -} - -func TestBadTypes(t *testing.T) { - pebkacTesting = true - - err := Parse(url.Values{"Unknown": {"4"}}, &Bad{}) - assertPebkac(t, err) - - err = Parse(url.Values{"Unknown": {"4"}}, &Bad2{}) - assertPebkac(t, err) - - err = Parse(url.Values{"BadMap[llama]": {"4"}}, &Bad3{}) - assertPebkac(t, err) - - pebkacTesting = false -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/param/struct.go b/Godeps/_workspace/src/github.com/zenazn/goji/param/struct.go deleted file mode 100644 index 8af3c08..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/param/struct.go +++ /dev/null @@ -1,121 +0,0 @@ -package param - -import ( - "reflect" - "strings" - "sync" -) - -// We decode a lot of structs (since it's the top-level thing this library -// decodes) and it takes a fair bit of work to reflect upon the struct to figure -// out what we want to do. Instead of doing this on every invocation, we cache -// metadata about each struct the first time we see it. The upshot is that we -// save some work every time. The downside is we are forced to briefly acquire -// a lock to access the cache in a thread-safe way. If this ever becomes a -// bottleneck, both the lock and the cache can be sharded or something. -type structCache map[string]cacheLine -type cacheLine struct { - offset int - parse func(string, string, []string, reflect.Value) -} - -var cacheLock sync.RWMutex -var cache = make(map[reflect.Type]structCache) - -func cacheStruct(t reflect.Type) structCache { - cacheLock.RLock() - sc, ok := cache[t] - cacheLock.RUnlock() - - if ok { - return sc - } - - // It's okay if two people build struct caches simultaneously - sc = make(structCache) - for i := 0; i < t.NumField(); i++ { - sf := t.Field(i) - // Only unexported fields have a PkgPath; we want to only cache - // exported fields. - if sf.PkgPath != "" { - continue - } - name := extractName(sf) - if name != "-" { - sc[name] = cacheLine{i, extractHandler(t, sf)} - } - } - - cacheLock.Lock() - cache[t] = sc - cacheLock.Unlock() - - return sc -} - -// Extract the name of the given struct field, looking at struct tags as -// appropriate. -func extractName(sf reflect.StructField) string { - name := sf.Tag.Get("param") - if name == "" { - name = sf.Tag.Get("json") - idx := strings.IndexRune(name, ',') - if idx >= 0 { - name = name[:idx] - } - } - if name == "" { - name = sf.Name - } - - return name -} - -func extractHandler(s reflect.Type, sf reflect.StructField) func(string, string, []string, reflect.Value) { - if reflect.PtrTo(sf.Type).Implements(textUnmarshalerType) { - return parseTextUnmarshaler - } - - switch sf.Type.Kind() { - case reflect.Bool: - return parseBool - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return parseInt - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - return parseUint - case reflect.Float32, reflect.Float64: - return parseFloat - case reflect.Map: - return parseMap - case reflect.Ptr: - return parsePtr - case reflect.Slice: - return parseSlice - case reflect.String: - return parseString - case reflect.Struct: - return parseStruct - - default: - pebkac("struct %v has illegal field %q (type %v, kind %v).", - s, sf.Name, sf.Type, sf.Type.Kind()) - return nil - } -} - -// We have to parse two types of structs: ones at the top level, whose keys -// don't have square brackets around them, and nested structs, which do. -func parseStructField(cache structCache, key, sk, keytail string, values []string, target reflect.Value) { - l, ok := cache[sk] - if !ok { - panic(KeyError{ - FullKey: key, - Key: kpath(key, keytail), - Type: target.Type(), - Field: sk, - }) - } - f := target.Field(l.offset) - - l.parse(key, keytail, values, f) -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/param/struct_test.go b/Godeps/_workspace/src/github.com/zenazn/goji/param/struct_test.go deleted file mode 100644 index ecba3e2..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/param/struct_test.go +++ /dev/null @@ -1,106 +0,0 @@ -package param - -import ( - "reflect" - "testing" -) - -type Fruity struct { - A bool - B int `json:"banana"` - C uint `param:"cherry"` - D float64 `json:"durian" param:"dragonfruit"` - E int `json:"elderberry" param:"-"` - F map[string]int `json:"-" param:"fig"` - G *int `json:"grape,omitempty"` - H []int `param:"honeydew" json:"huckleberry"` - I string `foobar:"iyokan"` - J Cheesy `param:"jackfruit" cheese:"jarlsberg"` -} - -type Cheesy struct { - A int `param:"affinois"` - B int `param:"brie"` - C int `param:"camembert"` - D int `param:"delice d'argental"` -} - -type Private struct { - Public, private int -} - -var fruityType = reflect.TypeOf(Fruity{}) -var cheesyType = reflect.TypeOf(Cheesy{}) -var privateType = reflect.TypeOf(Private{}) - -var fruityNames = []string{ - "A", "banana", "cherry", "dragonfruit", "-", "fig", "grape", "honeydew", - "I", "jackfruit", -} - -var fruityCache = map[string]cacheLine{ - "A": {0, parseBool}, - "banana": {1, parseInt}, - "cherry": {2, parseUint}, - "dragonfruit": {3, parseFloat}, - "fig": {5, parseMap}, - "grape": {6, parsePtr}, - "honeydew": {7, parseSlice}, - "I": {8, parseString}, - "jackfruit": {9, parseStruct}, -} - -func assertEqual(t *testing.T, what string, e, a interface{}) { - if !reflect.DeepEqual(e, a) { - t.Errorf("Expected %s to be %v, was actually %v", what, e, a) - } -} - -func TestNames(t *testing.T) { - t.Parallel() - - for i, val := range fruityNames { - name := extractName(fruityType.Field(i)) - assertEqual(t, "tag", val, name) - } -} - -func TestCacheStruct(t *testing.T) { - t.Parallel() - - sc := cacheStruct(fruityType) - - if len(sc) != len(fruityCache) { - t.Errorf("Cache has %d keys, but expected %d", len(sc), - len(fruityCache)) - } - - for k, v := range fruityCache { - sck, ok := sc[k] - if !ok { - t.Errorf("Could not find key %q in cache", k) - continue - } - if sck.offset != v.offset { - t.Errorf("Cache for %q: expected offset %d but got %d", - k, sck.offset, v.offset) - } - // We want to compare function pointer equality, and this - // appears to be the only way - a := reflect.ValueOf(sck.parse) - b := reflect.ValueOf(v.parse) - if a.Pointer() != b.Pointer() { - t.Errorf("Parse mismatch for %q: %v, expected %v", k, a, - b) - } - } -} - -func TestPrivate(t *testing.T) { - t.Parallel() - - sc := cacheStruct(privateType) - if len(sc) != 1 { - t.Error("Expected Private{} to have one cachable field") - } -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/web/atomic.go b/Godeps/_workspace/src/github.com/zenazn/goji/web/atomic.go deleted file mode 100644 index 795d8e5..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/web/atomic.go +++ /dev/null @@ -1,18 +0,0 @@ -// +build !appengine - -package web - -import ( - "sync/atomic" - "unsafe" -) - -func (rt *router) getMachine() *routeMachine { - ptr := (*unsafe.Pointer)(unsafe.Pointer(&rt.machine)) - sm := (*routeMachine)(atomic.LoadPointer(ptr)) - return sm -} -func (rt *router) setMachine(m *routeMachine) { - ptr := (*unsafe.Pointer)(unsafe.Pointer(&rt.machine)) - atomic.StorePointer(ptr, unsafe.Pointer(m)) -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/web/atomic_appengine.go b/Godeps/_workspace/src/github.com/zenazn/goji/web/atomic_appengine.go deleted file mode 100644 index 027127a..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/web/atomic_appengine.go +++ /dev/null @@ -1,14 +0,0 @@ -// +build appengine - -package web - -func (rt *router) getMachine() *routeMachine { - rt.lock.Lock() - defer rt.lock.Unlock() - return rt.machine -} - -// We always hold the lock when calling setMachine. -func (rt *router) setMachine(m *routeMachine) { - rt.machine = m -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/web/bench_test.go b/Godeps/_workspace/src/github.com/zenazn/goji/web/bench_test.go deleted file mode 100644 index 57ecf41..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/web/bench_test.go +++ /dev/null @@ -1,153 +0,0 @@ -package web - -import ( - "crypto/rand" - "encoding/base64" - mrand "math/rand" - "net/http" - "testing" -) - -/* -The core benchmarks here are based on cypriss's mux benchmarks, which can be -found here: -https://github.com/cypriss/golang-mux-benchmark - -They happen to play very well into Goji's router's strengths. -*/ - -type nilRouter struct{} - -var helloWorld = []byte("Hello world!\n") - -func (_ nilRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) { - w.Write(helloWorld) -} - -type nilResponse struct{} - -func (_ nilResponse) Write(buf []byte) (int, error) { - return len(buf), nil -} -func (_ nilResponse) Header() http.Header { - return nil -} -func (_ nilResponse) WriteHeader(code int) { -} - -func trivialMiddleware(h http.Handler) http.Handler { - fn := func(w http.ResponseWriter, r *http.Request) { - h.ServeHTTP(w, r) - } - return http.HandlerFunc(fn) -} - -var w nilResponse - -func addRoutes(m *Mux, prefix string) { - m.Get(prefix, nilRouter{}) - m.Post(prefix, nilRouter{}) - m.Get(prefix+"/:id", nilRouter{}) - m.Put(prefix+"/:id", nilRouter{}) - m.Delete(prefix+"/:id", nilRouter{}) -} - -func randString() string { - var buf [6]byte - rand.Reader.Read(buf[:]) - return base64.URLEncoding.EncodeToString(buf[:]) -} - -func genPrefixes(n int) []string { - p := make([]string, n) - for i := range p { - p[i] = "/" + randString() - } - return p -} - -func genRequests(prefixes []string) []*http.Request { - rs := make([]*http.Request, 5*len(prefixes)) - for i, prefix := range prefixes { - rs[5*i+0], _ = http.NewRequest("GET", prefix, nil) - rs[5*i+1], _ = http.NewRequest("POST", prefix, nil) - rs[5*i+2], _ = http.NewRequest("GET", prefix+"/foo", nil) - rs[5*i+3], _ = http.NewRequest("PUT", prefix+"/foo", nil) - rs[5*i+4], _ = http.NewRequest("DELETE", prefix+"/foo", nil) - } - return rs -} - -func permuteRequests(reqs []*http.Request) []*http.Request { - out := make([]*http.Request, len(reqs)) - perm := mrand.Perm(len(reqs)) - for i, req := range reqs { - out[perm[i]] = req - } - return out -} - -func benchN(b *testing.B, n int) { - m := New() - prefixes := genPrefixes(n) - for _, prefix := range prefixes { - addRoutes(m, prefix) - } - reqs := permuteRequests(genRequests(prefixes)) - - b.ResetTimer() - b.ReportAllocs() - for i := 0; i < b.N; i++ { - m.ServeHTTP(w, reqs[i%len(reqs)]) - } -} - -func benchM(b *testing.B, n int) { - m := New() - m.Get("/", nilRouter{}) - for i := 0; i < n; i++ { - m.Use(trivialMiddleware) - } - r, _ := http.NewRequest("GET", "/", nil) - - b.ResetTimer() - b.ReportAllocs() - for i := 0; i < b.N; i++ { - m.ServeHTTP(w, r) - } -} - -func BenchmarkStatic(b *testing.B) { - m := New() - m.Get("/", nilRouter{}) - r, _ := http.NewRequest("GET", "/", nil) - - b.ResetTimer() - b.ReportAllocs() - for i := 0; i < b.N; i++ { - m.ServeHTTP(w, r) - } -} - -func BenchmarkRoute5(b *testing.B) { - benchN(b, 1) -} -func BenchmarkRoute50(b *testing.B) { - benchN(b, 10) -} -func BenchmarkRoute500(b *testing.B) { - benchN(b, 100) -} -func BenchmarkRoute5000(b *testing.B) { - benchN(b, 1000) -} - -func BenchmarkMiddleware1(b *testing.B) { - benchM(b, 1) -} -func BenchmarkMiddleware10(b *testing.B) { - benchM(b, 10) -} -func BenchmarkMiddleware100(b *testing.B) { - benchM(b, 100) -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/web/fast_router.go b/Godeps/_workspace/src/github.com/zenazn/goji/web/fast_router.go deleted file mode 100644 index b6f52b1..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/web/fast_router.go +++ /dev/null @@ -1,265 +0,0 @@ -package web - -/* -This file implements a fast router by encoding a list of routes first into a -pseudo-trie, then encoding that pseudo-trie into a state machine realized as -a routing bytecode. - -The most interesting part of this router is not its speed (it is quite fast), -but the guarantees it provides. In a naive router, routes are examined one after -another until a match is found, and this is the programming model we want to -support. For any given request ("GET /hello/carl"), there is a list of -"plausible" routes: routes which match the method ("GET"), and which have a -prefix that is a prefix of the requested path ("/" and "/hello/", for instance, -but not "/foobar"). Patterns also have some amount of arbitrary code associated -with them, which tells us whether or not the route matched. Just like the naive -router, our goal is to call each plausible pattern, in the order they were -added, until we find one that matches. The "fast" part here is being smart about -which non-plausible routes we can skip. - -First, we sort routes using a pairwise comparison function: sorting occurs as -normal on the prefixes, with the caveat that a route may not be moved past a -route that might also match the same string. Among other things, this means -we're forced to use particularly dumb sorting algorithms, but it only has to -happen once, and there probably aren't even that many routes to begin with. This -logic appears inline in the router's handle() function. - -We then build a pseudo-trie from the sorted list of routes. It's not quite a -normal trie because there are certain routes we cannot reorder around other -routes (since we're providing identical semantics to the naive router), but it's -close enough and the basic idea is the same. - -Finally, we lower this psuedo-trie from its tree representation to a state -machine bytecode. The bytecode is pretty simple: it contains up to three bytes, -a choice of a bunch of flags, and an index. The state machine is pretty simple: -if the bytes match the next few bytes after the cursor, the instruction matches, -and the state machine advances to the next instruction. If it does not match, it -jumps to the instruction at the index. Various flags modify this basic behavior, -the documentation for which can be found below. - -The thing we're optimizing for here over pretty much everything else is memory -locality. We make an effort to lay out both the trie child selection logic and -the matching of long strings consecutively in memory, making both operations -very cheap. In fact, our matching logic isn't particularly asymptotically good, -but in practice the benefits of memory locality outweigh just about everything -else. - -Unfortunately, the code implementing all of this is pretty bad (both inefficient -and hard to read). Maybe someday I'll come and take a second pass at it. -*/ -type state struct { - mode smMode - bs [3]byte - i int32 -} -type stateMachine []state - -type smMode uint8 - -// Many combinations of smModes don't make sense, but since this is interal to -// the library I don't feel like documenting them. -const ( - // The two low bits of the mode are used as a length of how many bytes - // of bs are used. If the length is 0, the node is treated as a - // wildcard. - smLengthMask smMode = 3 -) - -const ( - // Jump to the given index on a match. Ordinarily, the state machine - // will jump to the state given by the index if the characters do not - // match. - smJumpOnMatch smMode = 4 << iota - // The index is the index of a route to try. If running the route fails, - // the state machine advances by one. - smRoute - // Reset the state machine's cursor into the input string to the state's - // index value. - smSetCursor - // If this bit is set, the machine transitions into a non-accepting - // state if it matches. - smFail -) - -type trie struct { - prefix string - children []trieSegment -} - -// A trie segment is a route matching this point (or -1), combined with a list -// of trie children that follow that route. -type trieSegment struct { - route int - children []trie -} - -func buildTrie(routes []route, dp, dr int) trie { - var t trie - ts := trieSegment{-1, nil} - for i, r := range routes { - if len(r.prefix) != dp { - continue - } - - if i == 0 { - ts.route = 0 - } else { - subroutes := routes[ts.route+1 : i] - ts.children = buildTrieSegment(subroutes, dp, dr+ts.route+1) - t.children = append(t.children, ts) - ts = trieSegment{i, nil} - } - } - - // This could be a little DRYer... - subroutes := routes[ts.route+1:] - ts.children = buildTrieSegment(subroutes, dp, dr+ts.route+1) - t.children = append(t.children, ts) - - for i := range t.children { - if t.children[i].route != -1 { - t.children[i].route += dr - } - } - - return t -} - -func commonPrefix(s1, s2 string) string { - if len(s1) > len(s2) { - return commonPrefix(s2, s1) - } - for i := 0; i < len(s1); i++ { - if s1[i] != s2[i] { - return s1[:i] - } - } - return s1 -} - -func buildTrieSegment(routes []route, dp, dr int) []trie { - if len(routes) == 0 { - return nil - } - var tries []trie - - start := 0 - p := routes[0].prefix[dp:] - for i := 1; i < len(routes); i++ { - ip := routes[i].prefix[dp:] - cp := commonPrefix(p, ip) - if len(cp) == 0 { - t := buildTrie(routes[start:i], dp+len(p), dr+start) - t.prefix = p - tries = append(tries, t) - start = i - p = ip - } else { - p = cp - } - } - - t := buildTrie(routes[start:], dp+len(p), dr+start) - t.prefix = p - return append(tries, t) -} - -// This is a bit confusing, since the encode method on a trie deals exclusively -// with trieSegments (i.e., its children), and vice versa. -// -// These methods are also hideously inefficient, both in terms of memory usage -// and algorithmic complexity. If it ever becomes a problem, maybe we can do -// something smarter than stupid O(N^2) appends, but to be honest, I bet N is -// small (it almost always is :P) and we only do it once at boot anyways. - -func (t trie) encode(dp, off int) stateMachine { - ms := make([]stateMachine, len(t.children)) - subs := make([]stateMachine, len(t.children)) - var l, msl, subl int - - for i, ts := range t.children { - ms[i], subs[i] = ts.encode(dp, 0) - msl += len(ms[i]) - l += len(ms[i]) + len(subs[i]) - } - - l++ - - m := make(stateMachine, 0, l) - for i, mm := range ms { - for j := range mm { - if mm[j].mode&(smRoute|smSetCursor) != 0 { - continue - } - - mm[j].i += int32(off + msl + subl + 1) - } - m = append(m, mm...) - subl += len(subs[i]) - } - - m = append(m, state{mode: smJumpOnMatch, i: -1}) - - msl = 0 - for i, sub := range subs { - msl += len(ms[i]) - for j := range sub { - if sub[j].mode&(smRoute|smSetCursor) != 0 { - continue - } - if sub[j].i == -1 { - sub[j].i = int32(off + msl) - } else { - sub[j].i += int32(off + len(m)) - } - } - m = append(m, sub...) - } - - return m -} - -func (ts trieSegment) encode(dp, off int) (me stateMachine, sub stateMachine) { - o := 1 - if ts.route != -1 { - o++ - } - me = make(stateMachine, len(ts.children)+o) - - me[0] = state{mode: smSetCursor, i: int32(dp)} - if ts.route != -1 { - me[1] = state{mode: smRoute, i: int32(ts.route)} - } - - for i, t := range ts.children { - p := t.prefix - - bc := copy(me[i+o].bs[:], p) - me[i+o].mode = smMode(bc) | smJumpOnMatch - me[i+o].i = int32(off + len(sub)) - - for len(p) > bc { - var bs [3]byte - p = p[bc:] - bc = copy(bs[:], p) - sub = append(sub, state{bs: bs, mode: smMode(bc), i: -1}) - } - - sub = append(sub, t.encode(dp+len(t.prefix), off+len(sub))...) - } - return -} - -func compile(routes []route) stateMachine { - if len(routes) == 0 { - return nil - } - t := buildTrie(routes, 0, 0) - m := t.encode(0, 0) - for i := range m { - if m[i].i == -1 { - m[i].mode = m[i].mode | smFail - } - } - return m -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/web/func_equal.go b/Godeps/_workspace/src/github.com/zenazn/goji/web/func_equal.go deleted file mode 100644 index 3206b04..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/web/func_equal.go +++ /dev/null @@ -1,38 +0,0 @@ -package web - -import ( - "reflect" -) - -func isFunc(fn interface{}) bool { - return reflect.ValueOf(fn).Kind() == reflect.Func -} - -/* -This is more than a little sketchtacular. Go's rules for function pointer -equality are pretty restrictive: nil function pointers always compare equal, and -all other pointer types never do. However, this is pretty limiting: it means -that we can't let people reference the middleware they've given us since we have -no idea which function they're referring to. - -To get better data out of Go, we sketch on the representation of interfaces. We -happen to know that interfaces are pairs of pointers: one to the real data, one -to data about the type. Therefore, two interfaces, including two function -interface{}'s, point to exactly the same objects iff their interface -representations are identical. And it turns out this is sufficient for our -purposes. - -If you're curious, you can read more about the representation of functions here: -http://golang.org/s/go11func -We're in effect comparing the pointers of the indirect layer. -*/ -func funcEqual(a, b interface{}) bool { - if !isFunc(a) || !isFunc(b) { - panic("funcEqual: type error!") - } - - av := reflect.ValueOf(&a).Elem() - bv := reflect.ValueOf(&b).Elem() - - return av.InterfaceData() == bv.InterfaceData() -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/web/func_equal_test.go b/Godeps/_workspace/src/github.com/zenazn/goji/web/func_equal_test.go deleted file mode 100644 index daf8d9a..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/web/func_equal_test.go +++ /dev/null @@ -1,84 +0,0 @@ -package web - -import ( - "testing" -) - -// To tell you the truth, I'm not actually sure how many of these cases are -// needed. Presumably someone with more patience than I could comb through -// http://golang.org/s/go11func and figure out what all the different cases I -// ought to test are, but I think this test includes all the cases I care about -// and is at least reasonably thorough. - -func a() string { - return "A" -} -func b() string { - return "B" -} -func mkFn(s string) func() string { - return func() string { - return s - } -} - -var c = mkFn("C") -var d = mkFn("D") -var e = a -var f = c -var g = mkFn("D") - -type Type string - -func (t *Type) String() string { - return string(*t) -} - -var t1 = Type("hi") -var t2 = Type("bye") -var t1f = t1.String -var t2f = t2.String - -var funcEqualTests = []struct { - a, b func() string - result bool -}{ - {a, a, true}, - {a, b, false}, - {b, b, true}, - {a, c, false}, - {c, c, true}, - {c, d, false}, - {a, e, true}, - {a, f, false}, - {c, f, true}, - {e, f, false}, - {d, g, false}, - {t1f, t1f, true}, - {t1f, t2f, false}, -} - -func TestFuncEqual(t *testing.T) { - t.Parallel() - - for _, test := range funcEqualTests { - r := funcEqual(test.a, test.b) - if r != test.result { - t.Errorf("funcEqual(%v, %v) should have been %v", - test.a, test.b, test.result) - } - } - h := mkFn("H") - i := h - j := mkFn("H") - k := a - if !funcEqual(h, i) { - t.Errorf("h and i should have been equal") - } - if funcEqual(h, j) { - t.Errorf("h and j should not have been equal") - } - if !funcEqual(a, k) { - t.Errorf("a and k should not have been equal") - } -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware.go b/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware.go deleted file mode 100644 index a91b9ad..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware.go +++ /dev/null @@ -1,195 +0,0 @@ -package web - -import ( - "fmt" - "log" - "net/http" - "sync" -) - -// Maximum size of the pool of spare middleware stacks -const mPoolSize = 32 - -type mLayer struct { - fn func(*C, http.Handler) http.Handler - orig interface{} -} - -type mStack struct { - lock sync.Mutex - stack []mLayer - pool chan *cStack - router internalRouter -} - -type internalRouter interface { - route(*C, http.ResponseWriter, *http.Request) -} - -/* -Constructing a middleware stack involves a lot of allocations: at the very least -each layer will have to close over the layer after (inside) it, and perhaps a -context object. Instead of doing this on every request, let's cache fully -assembled middleware stacks (the "c" stands for "cached"). - -A lot of the complexity here (in particular the "pool" parameter, and the -behavior of release() and invalidate() below) is due to the fact that when the -middleware stack is mutated we need to create a "cache barrier," where no -cStack created before the middleware stack mutation is returned to the active -cache pool (and is therefore eligible for subsequent reuse). The way we do this -is a bit ugly: each cStack maintains a pointer to the pool it originally came -from, and will only return itself to that pool. If the mStack's pool has been -rotated since then (meaning that this cStack is invalid), it will either try -(and likely fail) to insert itself into the stale pool, or it will drop the -cStack on the floor. -*/ -type cStack struct { - C - m http.Handler - pool chan *cStack -} - -func (s *cStack) ServeHTTP(w http.ResponseWriter, r *http.Request) { - s.C = C{} - s.m.ServeHTTP(w, r) -} -func (s *cStack) ServeHTTPC(c C, w http.ResponseWriter, r *http.Request) { - s.C = c - s.m.ServeHTTP(w, r) -} - -func (m *mStack) appendLayer(fn interface{}) { - ml := mLayer{orig: fn} - switch fn.(type) { - case func(http.Handler) http.Handler: - unwrapped := fn.(func(http.Handler) http.Handler) - ml.fn = func(c *C, h http.Handler) http.Handler { - return unwrapped(h) - } - case func(*C, http.Handler) http.Handler: - ml.fn = fn.(func(*C, http.Handler) http.Handler) - default: - log.Fatalf(`Unknown middleware type %v. Expected a function `+ - `with signature "func(http.Handler) http.Handler" or `+ - `"func(*web.C, http.Handler) http.Handler".`, fn) - } - m.stack = append(m.stack, ml) -} - -func (m *mStack) findLayer(l interface{}) int { - for i, middleware := range m.stack { - if funcEqual(l, middleware.orig) { - return i - } - } - return -1 -} - -func (m *mStack) invalidate() { - m.pool = make(chan *cStack, mPoolSize) -} - -func (m *mStack) newStack() *cStack { - m.lock.Lock() - defer m.lock.Unlock() - - cs := cStack{} - router := m.router - - cs.m = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - router.route(&cs.C, w, r) - }) - for i := len(m.stack) - 1; i >= 0; i-- { - cs.m = m.stack[i].fn(&cs.C, cs.m) - } - - return &cs -} - -func (m *mStack) alloc() *cStack { - // This is a little sloppy: this is only safe if this pointer - // dereference is atomic. Maybe someday I'll replace it with - // sync/atomic, but for now I happen to know that on all the - // architectures I care about it happens to be atomic. - p := m.pool - var cs *cStack - select { - case cs = <-p: - // This can happen if we race against an invalidation. It's - // completely peaceful, so long as we assume we can grab a cStack before - // our stack blows out. - if cs == nil { - return m.alloc() - } - default: - cs = m.newStack() - } - - cs.pool = p - return cs -} - -func (m *mStack) release(cs *cStack) { - cs.C = C{} - if cs.pool != m.pool { - return - } - select { - case cs.pool <- cs: - default: - } -} - -// Append the given middleware to the middleware stack. See the documentation -// for type Mux for a list of valid middleware types. -// -// No attempt is made to enforce the uniqueness of middlewares. -func (m *mStack) Use(middleware interface{}) { - m.lock.Lock() - defer m.lock.Unlock() - m.appendLayer(middleware) - m.invalidate() -} - -// Insert the given middleware immediately before a given existing middleware in -// the stack. See the documentation for type Mux for a list of valid middleware -// types. Returns an error if no middleware has the name given by "before." -// -// No attempt is made to enforce the uniqueness of middlewares. If the insertion -// point is ambiguous, the first (outermost) one is chosen. -func (m *mStack) Insert(middleware, before interface{}) error { - m.lock.Lock() - defer m.lock.Unlock() - i := m.findLayer(before) - if i < 0 { - return fmt.Errorf("web: unknown middleware %v", before) - } - - m.appendLayer(middleware) - inserted := m.stack[len(m.stack)-1] - copy(m.stack[i+1:], m.stack[i:]) - m.stack[i] = inserted - - m.invalidate() - return nil -} - -// Remove the given middleware from the middleware stack. Returns an error if -// no such middleware can be found. -// -// If the name of the middleware to delete is ambiguous, the first (outermost) -// one is chosen. -func (m *mStack) Abandon(middleware interface{}) error { - m.lock.Lock() - defer m.lock.Unlock() - i := m.findLayer(middleware) - if i < 0 { - return fmt.Errorf("web: unknown middleware %v", middleware) - } - - copy(m.stack[i:], m.stack[i+1:]) - m.stack = m.stack[:len(m.stack)-1 : len(m.stack)] - - m.invalidate() - return nil -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware/envinit.go b/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware/envinit.go deleted file mode 100644 index 79d2313..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware/envinit.go +++ /dev/null @@ -1,26 +0,0 @@ -package middleware - -import ( - "net/http" - - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/zenazn/goji/web" -) - -// EnvInit is a middleware that allocates an environment map if one does not -// already exist. This is necessary because Goji does not guarantee that Env is -// present when running middleware (it avoids forcing the map allocation). Note -// that other middleware should check Env for nil in order to maximize -// compatibility (when EnvInit is not used, or when another middleware layer -// blanks out Env), but for situations in which the user controls the middleware -// stack and knows EnvInit is present, this middleware can eliminate a lot of -// boilerplate. -func EnvInit(c *web.C, h http.Handler) http.Handler { - fn := func(w http.ResponseWriter, r *http.Request) { - if c.Env == nil { - c.Env = make(map[string]interface{}) - } - h.ServeHTTP(w, r) - } - - return http.HandlerFunc(fn) -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware/logger.go b/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware/logger.go deleted file mode 100644 index 7d9bf24..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware/logger.go +++ /dev/null @@ -1,80 +0,0 @@ -package middleware - -import ( - "bytes" - "log" - "net/http" - "time" - - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/zenazn/goji/web" -) - -// Logger is a middleware that logs the start and end of each request, along -// with some useful data about what was requested, what the response status was, -// and how long it took to return. When standard output is a TTY, Logger will -// print in color, otherwise it will print in black and white. -// -// Logger prints a request ID if one is provided. -func Logger(c *web.C, h http.Handler) http.Handler { - fn := func(w http.ResponseWriter, r *http.Request) { - reqID := GetReqID(*c) - - printStart(reqID, r) - - lw := wrapWriter(w) - - t1 := time.Now() - h.ServeHTTP(lw, r) - lw.maybeWriteHeader() - t2 := time.Now() - - printEnd(reqID, lw, t2.Sub(t1)) - } - - return http.HandlerFunc(fn) -} - -func printStart(reqID string, r *http.Request) { - var buf bytes.Buffer - - if reqID != "" { - cW(&buf, bBlack, "[%s] ", reqID) - } - buf.WriteString("Started ") - cW(&buf, bMagenta, "%s ", r.Method) - cW(&buf, nBlue, "%q ", r.URL.String()) - buf.WriteString("from ") - buf.WriteString(r.RemoteAddr) - - log.Print(buf.String()) -} - -func printEnd(reqID string, w writerProxy, dt time.Duration) { - var buf bytes.Buffer - - if reqID != "" { - cW(&buf, bBlack, "[%s] ", reqID) - } - buf.WriteString("Returning ") - if w.status() < 200 { - cW(&buf, bBlue, "%03d", w.status()) - } else if w.status() < 300 { - cW(&buf, bGreen, "%03d", w.status()) - } else if w.status() < 400 { - cW(&buf, bCyan, "%03d", w.status()) - } else if w.status() < 500 { - cW(&buf, bYellow, "%03d", w.status()) - } else { - cW(&buf, bRed, "%03d", w.status()) - } - buf.WriteString(" in ") - if dt < 500*time.Millisecond { - cW(&buf, nGreen, "%s", dt) - } else if dt < 5*time.Second { - cW(&buf, nYellow, "%s", dt) - } else { - cW(&buf, nRed, "%s", dt) - } - - log.Print(buf.String()) -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware/middleware.go b/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware/middleware.go deleted file mode 100644 index 23cfde2..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware/middleware.go +++ /dev/null @@ -1,4 +0,0 @@ -/* -Package middleware provides several standard middleware implementations. -*/ -package middleware diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware/nocache.go b/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware/nocache.go deleted file mode 100644 index ae3d260..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware/nocache.go +++ /dev/null @@ -1,55 +0,0 @@ -package middleware - -import ( - "net/http" - "time" -) - -// Unix epoch time -var epoch = time.Unix(0, 0).Format(time.RFC1123) - -// Taken from https://github.com/mytrile/nocache -var noCacheHeaders = map[string]string{ - "Expires": epoch, - "Cache-Control": "no-cache, private, max-age=0", - "Pragma": "no-cache", - "X-Accel-Expires": "0", -} - -var etagHeaders = []string{ - "ETag", - "If-Modified-Since", - "If-Match", - "If-None-Match", - "If-Range", - "If-Unmodified-Since", -} - -// NoCache is a simple piece of middleware that sets a number of HTTP headers to prevent -// a router (or subrouter) from being cached by an upstream proxy and/or client. -// -// As per http://wiki.nginx.org/HttpProxyModule - NoCache sets: -// Expires: Thu, 01 Jan 1970 00:00:00 UTC -// Cache-Control: no-cache, private, max-age=0 -// X-Accel-Expires: 0 -// Pragma: no-cache (for HTTP/1.0 proxies/clients) -func NoCache(h http.Handler) http.Handler { - fn := func(w http.ResponseWriter, r *http.Request) { - - // Delete any ETag headers that may have been set - for _, v := range etagHeaders { - if r.Header.Get(v) != "" { - r.Header.Del(v) - } - } - - // Set our NoCache headers - for k, v := range noCacheHeaders { - w.Header().Set(k, v) - } - - h.ServeHTTP(w, r) - } - - return http.HandlerFunc(fn) -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware/nocache_test.go b/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware/nocache_test.go deleted file mode 100644 index e7a4188..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware/nocache_test.go +++ /dev/null @@ -1,29 +0,0 @@ -package middleware - -import ( - "net/http" - "net/http/httptest" - "testing" - - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/zenazn/goji/web" -) - -func TestNoCache(t *testing.T) { - - rr := httptest.NewRecorder() - s := web.New() - - s.Use(NoCache) - r, err := http.NewRequest("GET", "/", nil) - if err != nil { - t.Fatal(err) - } - - s.ServeHTTP(rr, r) - - for k, v := range noCacheHeaders { - if rr.HeaderMap[k][0] != v { - t.Errorf("%s header not set by middleware.", k) - } - } -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware/options.go b/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware/options.go deleted file mode 100644 index 0f4c33d..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware/options.go +++ /dev/null @@ -1,97 +0,0 @@ -package middleware - -import ( - "net/http" - "strings" - - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/zenazn/goji/web" -) - -type autoOptionsState int - -const ( - aosInit autoOptionsState = iota - aosHeaderWritten - aosProxying -) - -// I originally used an httptest.ResponseRecorder here, but package httptest -// adds a flag which I'm not particularly eager to expose. This is essentially a -// ResponseRecorder that has been specialized for the purpose at hand to avoid -// the httptest dependency. -type autoOptionsProxy struct { - w http.ResponseWriter - c *web.C - state autoOptionsState -} - -func (p *autoOptionsProxy) Header() http.Header { - return p.w.Header() -} - -func (p *autoOptionsProxy) Write(buf []byte) (int, error) { - switch p.state { - case aosInit: - p.state = aosHeaderWritten - case aosProxying: - return len(buf), nil - } - return p.w.Write(buf) -} - -func (p *autoOptionsProxy) WriteHeader(code int) { - methods := getValidMethods(*p.c) - switch p.state { - case aosInit: - if methods != nil && code == http.StatusNotFound { - p.state = aosProxying - break - } - p.state = aosHeaderWritten - fallthrough - default: - p.w.WriteHeader(code) - return - } - - methods = addMethod(methods, "OPTIONS") - p.w.Header().Set("Allow", strings.Join(methods, ", ")) - p.w.WriteHeader(http.StatusOK) -} - -// AutomaticOptions automatically return an appropriate "Allow" header when the -// request method is OPTIONS and the request would have otherwise been 404'd. -func AutomaticOptions(c *web.C, h http.Handler) http.Handler { - fn := func(w http.ResponseWriter, r *http.Request) { - if r.Method == "OPTIONS" { - w = &autoOptionsProxy{c: c, w: w} - } - - h.ServeHTTP(w, r) - } - - return http.HandlerFunc(fn) -} - -func getValidMethods(c web.C) []string { - if c.Env == nil { - return nil - } - v, ok := c.Env[web.ValidMethodsKey] - if !ok { - return nil - } - if methods, ok := v.([]string); ok { - return methods - } - return nil -} - -func addMethod(methods []string, method string) []string { - for _, m := range methods { - if m == method { - return methods - } - } - return append(methods, method) -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware/options_test.go b/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware/options_test.go deleted file mode 100644 index 630c6d7..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware/options_test.go +++ /dev/null @@ -1,112 +0,0 @@ -package middleware - -import ( - "net/http" - "net/http/httptest" - "testing" - - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/zenazn/goji/web" -) - -func testOptions(r *http.Request, f func(*web.C, http.ResponseWriter, *http.Request)) *httptest.ResponseRecorder { - var c web.C - - h := func(w http.ResponseWriter, r *http.Request) { - f(&c, w, r) - } - m := AutomaticOptions(&c, http.HandlerFunc(h)) - w := httptest.NewRecorder() - m.ServeHTTP(w, r) - - return w -} - -var optionsTestEnv = map[string]interface{}{ - web.ValidMethodsKey: []string{ - "hello", - "world", - }, -} - -func TestAutomaticOptions(t *testing.T) { - t.Parallel() - - // Shouldn't interfere with normal requests - r, _ := http.NewRequest("GET", "/", nil) - rr := testOptions(r, - func(c *web.C, w http.ResponseWriter, r *http.Request) { - w.Write([]byte{'h', 'i'}) - }, - ) - if rr.Code != http.StatusOK { - t.Errorf("status is %d, not 200", rr.Code) - } - if rr.Body.String() != "hi" { - t.Errorf("body was %q, should be %q", rr.Body.String(), "hi") - } - allow := rr.HeaderMap.Get("Allow") - if allow != "" { - t.Errorf("Allow header was set to %q, should be empty", allow) - } - - // If we respond non-404 to an OPTIONS request, also don't interfere - r, _ = http.NewRequest("OPTIONS", "/", nil) - rr = testOptions(r, - func(c *web.C, w http.ResponseWriter, r *http.Request) { - c.Env = optionsTestEnv - w.Write([]byte{'h', 'i'}) - }, - ) - if rr.Code != http.StatusOK { - t.Errorf("status is %d, not 200", rr.Code) - } - if rr.Body.String() != "hi" { - t.Errorf("body was %q, should be %q", rr.Body.String(), "hi") - } - allow = rr.HeaderMap.Get("Allow") - if allow != "" { - t.Errorf("Allow header was set to %q, should be empty", allow) - } - - // Provide options if we 404. Make sure we nom the output bytes - r, _ = http.NewRequest("OPTIONS", "/", nil) - rr = testOptions(r, - func(c *web.C, w http.ResponseWriter, r *http.Request) { - c.Env = optionsTestEnv - w.WriteHeader(http.StatusNotFound) - w.Write([]byte{'h', 'i'}) - }, - ) - if rr.Code != http.StatusOK { - t.Errorf("status is %d, not 200", rr.Code) - } - if rr.Body.Len() != 0 { - t.Errorf("body was %q, should be empty", rr.Body.String()) - } - allow = rr.HeaderMap.Get("Allow") - correctHeaders := "hello, world, OPTIONS" - if allow != "hello, world, OPTIONS" { - t.Errorf("Allow header should be %q, was %q", correctHeaders, - allow) - } - - // If we somehow 404 without giving a list of valid options, don't do - // anything - r, _ = http.NewRequest("OPTIONS", "/", nil) - rr = testOptions(r, - func(c *web.C, w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusNotFound) - w.Write([]byte{'h', 'i'}) - }, - ) - if rr.Code != http.StatusNotFound { - t.Errorf("status is %d, not 404", rr.Code) - } - if rr.Body.String() != "hi" { - t.Errorf("body was %q, should be %q", rr.Body.String(), "hi") - } - allow = rr.HeaderMap.Get("Allow") - if allow != "" { - t.Errorf("Allow header was set to %q, should be empty", allow) - } -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware/realip.go b/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware/realip.go deleted file mode 100644 index 8158b72..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware/realip.go +++ /dev/null @@ -1,61 +0,0 @@ -package middleware - -import ( - "net/http" - "strings" - - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/zenazn/goji/web" -) - -// Key the original value of RemoteAddr is stored under. -const OriginalRemoteAddrKey = "originalRemoteAddr" - -var xForwardedFor = http.CanonicalHeaderKey("X-Forwarded-For") -var xRealIP = http.CanonicalHeaderKey("X-Real-IP") - -// RealIP is a middleware that sets a http.Request's RemoteAddr to the results -// of parsing either the X-Forwarded-For header or the X-Real-IP header (in that -// order). It places the original value of RemoteAddr in a context environment -// variable. -// -// This middleware should be inserted fairly early in the middleware stack to -// ensure that subsequent layers (e.g., request loggers) which examine the -// RemoteAddr will see the intended value. -// -// You should only use this middleware if you can trust the headers passed to -// you (in particular, the two headers this middleware uses), for example -// because you have placed a reverse proxy like HAProxy or nginx in front of -// Goji. If your reverse proxies are configured to pass along arbitrary header -// values from the client, or if you use this middleware without a reverse -// proxy, malicious clients will be able to make you very sad (or, depending on -// how you're using RemoteAddr, vulnerable to an attack of some sort). -func RealIP(c *web.C, h http.Handler) http.Handler { - fn := func(w http.ResponseWriter, r *http.Request) { - if rip := realIP(r); rip != "" { - if c.Env == nil { - c.Env = make(map[string]interface{}) - } - c.Env[OriginalRemoteAddrKey] = r.RemoteAddr - r.RemoteAddr = rip - } - h.ServeHTTP(w, r) - } - - return http.HandlerFunc(fn) -} - -func realIP(r *http.Request) string { - var ip string - - if xff := r.Header.Get(xForwardedFor); xff != "" { - i := strings.Index(xff, ", ") - if i == -1 { - i = len(xff) - } - ip = xff[:i] - } else if xrip := r.Header.Get(xRealIP); xrip != "" { - ip = xrip - } - - return ip -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware/recoverer.go b/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware/recoverer.go deleted file mode 100644 index 9698259..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware/recoverer.go +++ /dev/null @@ -1,44 +0,0 @@ -package middleware - -import ( - "bytes" - "log" - "net/http" - "runtime/debug" - - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/zenazn/goji/web" -) - -// Recoverer is a middleware that recovers from panics, logs the panic (and a -// backtrace), and returns a HTTP 500 (Internal Server Error) status if -// possible. -// -// Recoverer prints a request ID if one is provided. -func Recoverer(c *web.C, h http.Handler) http.Handler { - fn := func(w http.ResponseWriter, r *http.Request) { - reqID := GetReqID(*c) - - defer func() { - if err := recover(); err != nil { - printPanic(reqID, err) - debug.PrintStack() - http.Error(w, http.StatusText(500), 500) - } - }() - - h.ServeHTTP(w, r) - } - - return http.HandlerFunc(fn) -} - -func printPanic(reqID string, err interface{}) { - var buf bytes.Buffer - - if reqID != "" { - cW(&buf, bBlack, "[%s] ", reqID) - } - cW(&buf, bRed, "panic: %+v", err) - - log.Print(buf.String()) -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware/request_id.go b/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware/request_id.go deleted file mode 100644 index 3b26c06..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware/request_id.go +++ /dev/null @@ -1,88 +0,0 @@ -package middleware - -import ( - "crypto/rand" - "encoding/base64" - "fmt" - "net/http" - "os" - "strings" - "sync/atomic" - - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/zenazn/goji/web" -) - -// Key to use when setting the request ID. -const RequestIDKey = "reqID" - -var prefix string -var reqid uint64 - -/* -A quick note on the statistics here: we're trying to calculate the chance that -two randomly generated base62 prefixes will collide. We use the formula from -http://en.wikipedia.org/wiki/Birthday_problem - -P[m, n] \approx 1 - e^{-m^2/2n} - -We ballpark an upper bound for $m$ by imagining (for whatever reason) a server -that restarts every second over 10 years, for $m = 86400 * 365 * 10 = 315360000$ - -For a $k$ character base-62 identifier, we have $n(k) = 62^k$ - -Plugging this in, we find $P[m, n(10)] \approx 5.75%$, which is good enough for -our purposes, and is surely more than anyone would ever need in practice -- a -process that is rebooted a handful of times a day for a hundred years has less -than a millionth of a percent chance of generating two colliding IDs. -*/ - -func init() { - hostname, err := os.Hostname() - if hostname == "" || err != nil { - hostname = "localhost" - } - var buf [12]byte - var b64 string - for len(b64) < 10 { - rand.Read(buf[:]) - b64 = base64.StdEncoding.EncodeToString(buf[:]) - b64 = strings.NewReplacer("+", "", "/", "").Replace(b64) - } - - prefix = fmt.Sprintf("%s/%s", hostname, b64[0:10]) -} - -// RequestID is a middleware that injects a request ID into the context of each -// request. A request ID is a string of the form "host.example.com/random-0001", -// where "random" is a base62 random string that uniquely identifies this go -// process, and where the last number is an atomically incremented request -// counter. -func RequestID(c *web.C, h http.Handler) http.Handler { - fn := func(w http.ResponseWriter, r *http.Request) { - if c.Env == nil { - c.Env = make(map[string]interface{}) - } - myid := atomic.AddUint64(&reqid, 1) - c.Env[RequestIDKey] = fmt.Sprintf("%s-%06d", prefix, myid) - - h.ServeHTTP(w, r) - } - - return http.HandlerFunc(fn) -} - -// GetReqID returns a request ID from the given context if one is present. -// Returns the empty string if a request ID cannot be found. -func GetReqID(c web.C) string { - if c.Env == nil { - return "" - } - v, ok := c.Env[RequestIDKey] - if !ok { - return "" - } - if reqID, ok := v.(string); ok { - return reqID - } - return "" -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware/terminal.go b/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware/terminal.go deleted file mode 100644 index db02917..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware/terminal.go +++ /dev/null @@ -1,60 +0,0 @@ -package middleware - -import ( - "bytes" - "fmt" - "os" -) - -var ( - // Normal colors - nBlack = []byte{'\033', '[', '3', '0', 'm'} - nRed = []byte{'\033', '[', '3', '1', 'm'} - nGreen = []byte{'\033', '[', '3', '2', 'm'} - nYellow = []byte{'\033', '[', '3', '3', 'm'} - nBlue = []byte{'\033', '[', '3', '4', 'm'} - nMagenta = []byte{'\033', '[', '3', '5', 'm'} - nCyan = []byte{'\033', '[', '3', '6', 'm'} - nWhite = []byte{'\033', '[', '3', '7', 'm'} - // Bright colors - bBlack = []byte{'\033', '[', '3', '0', ';', '1', 'm'} - bRed = []byte{'\033', '[', '3', '1', ';', '1', 'm'} - bGreen = []byte{'\033', '[', '3', '2', ';', '1', 'm'} - bYellow = []byte{'\033', '[', '3', '3', ';', '1', 'm'} - bBlue = []byte{'\033', '[', '3', '4', ';', '1', 'm'} - bMagenta = []byte{'\033', '[', '3', '5', ';', '1', 'm'} - bCyan = []byte{'\033', '[', '3', '6', ';', '1', 'm'} - bWhite = []byte{'\033', '[', '3', '7', ';', '1', 'm'} - - reset = []byte{'\033', '[', '0', 'm'} -) - -var isTTY bool - -func init() { - // This is sort of cheating: if stdout is a character device, we assume - // that means it's a TTY. Unfortunately, there are many non-TTY - // character devices, but fortunately stdout is rarely set to any of - // them. - // - // We could solve this properly by pulling in a dependency on - // code.google.com/p/go.crypto/ssh/terminal, for instance, but as a - // heuristic for whether to print in color or in black-and-white, I'd - // really rather not. - fi, err := os.Stdout.Stat() - if err == nil { - m := os.ModeDevice | os.ModeCharDevice - isTTY = fi.Mode()&m == m - } -} - -// colorWrite -func cW(buf *bytes.Buffer, color []byte, s string, args ...interface{}) { - if isTTY { - buf.Write(color) - } - fmt.Fprintf(buf, s, args...) - if isTTY { - buf.Write(reset) - } -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware/writer_proxy.go b/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware/writer_proxy.go deleted file mode 100644 index 0142403..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware/writer_proxy.go +++ /dev/null @@ -1,83 +0,0 @@ -package middleware - -import ( - "bufio" - "io" - "net" - "net/http" -) - -func wrapWriter(w http.ResponseWriter) writerProxy { - _, cn := w.(http.CloseNotifier) - _, fl := w.(http.Flusher) - _, hj := w.(http.Hijacker) - _, rf := w.(io.ReaderFrom) - - bw := basicWriter{ResponseWriter: w} - if cn && fl && hj && rf { - return &fancyWriter{bw} - } - return &bw -} - -type writerProxy interface { - http.ResponseWriter - maybeWriteHeader() - status() int -} - -type basicWriter struct { - http.ResponseWriter - wroteHeader bool - code int -} - -func (b *basicWriter) WriteHeader(code int) { - if !b.wroteHeader { - b.code = code - b.wroteHeader = true - b.ResponseWriter.WriteHeader(code) - } -} -func (b *basicWriter) Write(buf []byte) (int, error) { - b.maybeWriteHeader() - return b.ResponseWriter.Write(buf) -} -func (b *basicWriter) maybeWriteHeader() { - if !b.wroteHeader { - b.WriteHeader(http.StatusOK) - } -} -func (b *basicWriter) status() int { - return b.code -} -func (b *basicWriter) Unwrap() http.ResponseWriter { - return b.ResponseWriter -} - -type fancyWriter struct { - basicWriter -} - -func (f *fancyWriter) CloseNotify() <-chan bool { - cn := f.basicWriter.ResponseWriter.(http.CloseNotifier) - return cn.CloseNotify() -} -func (f *fancyWriter) Flush() { - fl := f.basicWriter.ResponseWriter.(http.Flusher) - fl.Flush() -} -func (f *fancyWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { - hj := f.basicWriter.ResponseWriter.(http.Hijacker) - return hj.Hijack() -} -func (f *fancyWriter) ReadFrom(r io.Reader) (int64, error) { - rf := f.basicWriter.ResponseWriter.(io.ReaderFrom) - f.basicWriter.maybeWriteHeader() - return rf.ReadFrom(r) -} - -var _ http.CloseNotifier = &fancyWriter{} -var _ http.Flusher = &fancyWriter{} -var _ http.Hijacker = &fancyWriter{} -var _ io.ReaderFrom = &fancyWriter{} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware_test.go b/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware_test.go deleted file mode 100644 index e52027d..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/web/middleware_test.go +++ /dev/null @@ -1,248 +0,0 @@ -package web - -import ( - "net/http" - "net/http/httptest" - "testing" - "time" -) - -type iRouter func(*C, http.ResponseWriter, *http.Request) - -func (i iRouter) route(c *C, w http.ResponseWriter, r *http.Request) { - i(c, w, r) -} - -func makeStack(ch chan string) *mStack { - router := func(c *C, w http.ResponseWriter, r *http.Request) { - ch <- "router" - } - return &mStack{ - stack: make([]mLayer, 0), - pool: make(chan *cStack, mPoolSize), - router: iRouter(router), - } -} - -func chanWare(ch chan string, s string) func(http.Handler) http.Handler { - return func(h http.Handler) http.Handler { - fn := func(w http.ResponseWriter, r *http.Request) { - ch <- s - h.ServeHTTP(w, r) - } - return http.HandlerFunc(fn) - } -} - -func simpleRequest(ch chan string, st *mStack) { - defer func() { - ch <- "end" - }() - r, _ := http.NewRequest("GET", "/", nil) - w := httptest.NewRecorder() - cs := st.alloc() - defer st.release(cs) - - cs.ServeHTTP(w, r) -} - -func assertOrder(t *testing.T, ch chan string, strings ...string) { - for i, s := range strings { - var v string - select { - case v = <-ch: - case <-time.After(5 * time.Millisecond): - t.Fatalf("Expected %q as %d'th value, but timed out", s, - i+1) - } - if s != v { - t.Errorf("%d'th value was %q, expected %q", i+1, v, s) - } - } -} - -func TestSimple(t *testing.T) { - t.Parallel() - - ch := make(chan string) - st := makeStack(ch) - st.Use(chanWare(ch, "one")) - st.Use(chanWare(ch, "two")) - go simpleRequest(ch, st) - assertOrder(t, ch, "one", "two", "router", "end") -} - -func TestTypes(t *testing.T) { - t.Parallel() - - ch := make(chan string) - st := makeStack(ch) - st.Use(func(h http.Handler) http.Handler { - return h - }) - st.Use(func(c *C, h http.Handler) http.Handler { - return h - }) -} - -func TestAddMore(t *testing.T) { - t.Parallel() - - ch := make(chan string) - st := makeStack(ch) - st.Use(chanWare(ch, "one")) - go simpleRequest(ch, st) - assertOrder(t, ch, "one", "router", "end") - - st.Use(chanWare(ch, "two")) - go simpleRequest(ch, st) - assertOrder(t, ch, "one", "two", "router", "end") - - st.Use(chanWare(ch, "three")) - st.Use(chanWare(ch, "four")) - go simpleRequest(ch, st) - assertOrder(t, ch, "one", "two", "three", "four", "router", "end") -} - -func TestInsert(t *testing.T) { - t.Parallel() - - ch := make(chan string) - st := makeStack(ch) - one := chanWare(ch, "one") - two := chanWare(ch, "two") - st.Use(one) - st.Use(two) - go simpleRequest(ch, st) - assertOrder(t, ch, "one", "two", "router", "end") - - err := st.Insert(chanWare(ch, "sloth"), chanWare(ch, "squirrel")) - if err == nil { - t.Error("Expected error when referencing unknown middleware") - } - - st.Insert(chanWare(ch, "middle"), two) - err = st.Insert(chanWare(ch, "start"), one) - if err != nil { - t.Fatal(err) - } - go simpleRequest(ch, st) - assertOrder(t, ch, "start", "one", "middle", "two", "router", "end") -} - -func TestAbandon(t *testing.T) { - t.Parallel() - - ch := make(chan string) - st := makeStack(ch) - one := chanWare(ch, "one") - two := chanWare(ch, "two") - three := chanWare(ch, "three") - st.Use(one) - st.Use(two) - st.Use(three) - go simpleRequest(ch, st) - assertOrder(t, ch, "one", "two", "three", "router", "end") - - st.Abandon(two) - go simpleRequest(ch, st) - assertOrder(t, ch, "one", "three", "router", "end") - - err := st.Abandon(chanWare(ch, "panda")) - if err == nil { - t.Error("Expected error when deleting unknown middleware") - } - - st.Abandon(one) - st.Abandon(three) - go simpleRequest(ch, st) - assertOrder(t, ch, "router", "end") - - st.Use(one) - go simpleRequest(ch, st) - assertOrder(t, ch, "one", "router", "end") -} - -// This is a pretty sketchtacular test -func TestCaching(t *testing.T) { - ch := make(chan string) - st := makeStack(ch) - cs1 := st.alloc() - cs2 := st.alloc() - if cs1 == cs2 { - t.Fatal("cs1 and cs2 are the same") - } - st.release(cs2) - cs3 := st.alloc() - if cs2 != cs3 { - t.Fatalf("Expected cs2 to equal cs3") - } - st.release(cs1) - st.release(cs3) - cs4 := st.alloc() - cs5 := st.alloc() - if cs4 != cs1 { - t.Fatal("Expected cs4 to equal cs1") - } - if cs5 != cs3 { - t.Fatal("Expected cs5 to equal cs3") - } -} - -func TestInvalidation(t *testing.T) { - ch := make(chan string) - st := makeStack(ch) - cs1 := st.alloc() - cs2 := st.alloc() - st.release(cs1) - st.invalidate() - cs3 := st.alloc() - if cs3 == cs1 { - t.Fatal("Expected cs3 to be fresh, instead got cs1") - } - st.release(cs2) - cs4 := st.alloc() - if cs4 == cs2 { - t.Fatal("Expected cs4 to be fresh, instead got cs2") - } -} - -func TestContext(t *testing.T) { - router := func(c *C, w http.ResponseWriter, r *http.Request) { - if c.Env["reqID"].(int) != 2 { - t.Error("Request id was not 2 :(") - } - } - st := mStack{ - stack: make([]mLayer, 0), - pool: make(chan *cStack, mPoolSize), - router: iRouter(router), - } - st.Use(func(c *C, h http.Handler) http.Handler { - fn := func(w http.ResponseWriter, r *http.Request) { - if c.Env != nil || c.URLParams != nil { - t.Error("Expected a clean context") - } - c.Env = make(map[string]interface{}) - c.Env["reqID"] = 1 - - h.ServeHTTP(w, r) - } - return http.HandlerFunc(fn) - }) - - st.Use(func(c *C, h http.Handler) http.Handler { - fn := func(w http.ResponseWriter, r *http.Request) { - if c.Env == nil { - t.Error("Expected env from last middleware") - } - c.Env["reqID"] = c.Env["reqID"].(int) + 1 - - h.ServeHTTP(w, r) - } - return http.HandlerFunc(fn) - }) - ch := make(chan string) - go simpleRequest(ch, &st) - assertOrder(t, ch, "end") -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/web/mux.go b/Godeps/_workspace/src/github.com/zenazn/goji/web/mux.go deleted file mode 100644 index a8e9bc6..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/web/mux.go +++ /dev/null @@ -1,87 +0,0 @@ -package web - -import ( - "net/http" -) - -/* -Mux is an HTTP multiplexer, much like net/http's ServeMux. - -Routes may be added using any of the various HTTP-method-specific functions. -When processing a request, when iterating in insertion order the first route -that matches both the request's path and method is used. - -There are two other differences worth mentioning between web.Mux and -http.ServeMux. First, string patterns (i.e., Sinatra-like patterns) must match -exactly: the "rooted subtree" behavior of ServeMux is not implemented. Secondly, -unlike ServeMux, Mux does not support Host-specific patterns. - -If you require any of these features, remember that you are free to mix and -match muxes at any part of the stack. - -In order to provide a sane API, many functions on Mux take interface{}'s. This -is obviously not a very satisfying solution, but it's probably the best we can -do for now. Instead of duplicating documentation on each method, the types -accepted by those functions are documented here. - -A middleware (the untyped parameter in Use() and Insert()) must be one of the -following types: - - func(http.Handler) http.Handler - - func(c *web.C, http.Handler) http.Handler -All of the route-adding functions on Mux take two untyped parameters: pattern -and handler. Pattern must be one of the following types: - - string. It will be interpreted as a Sinatra-like pattern. In - particular, the following syntax is recognized: - - a path segment starting with with a colon will match any - string placed at that position. e.g., "/:name" will match - "/carl", binding "name" to "carl". - - a pattern ending with an asterisk will match any prefix of - that route. For instance, "/admin/*" will match "/admin/" and - "/admin/secret/lair". This is similar to Sinatra's wildcard, - but may only appear at the very end of the string and is - therefore significantly less powerful. - - regexp.Regexp. The library assumes that it is a Perl-style regexp that - is anchored on the left (i.e., the beginning of the string). If your - regexp is not anchored on the left, a hopefully-identical - left-anchored regexp will be created and used instead. - - web.Pattern -Handler must be one of the following types: - - http.Handler - - web.Handler - - func(w http.ResponseWriter, r *http.Request) - - func(c web.C, w http.ResponseWriter, r *http.Request) -*/ -type Mux struct { - mStack - router -} - -// New creates a new Mux without any routes or middleware. -func New() *Mux { - mux := Mux{ - mStack: mStack{ - stack: make([]mLayer, 0), - pool: make(chan *cStack, mPoolSize), - }, - router: router{ - routes: make([]route, 0), - notFound: parseHandler(http.NotFound), - }, - } - mux.mStack.router = &mux.router - return &mux -} - -func (m *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request) { - stack := m.mStack.alloc() - stack.ServeHTTP(w, r) - m.mStack.release(stack) -} - -// ServeHTTPC creates a context dependent request with the given Mux. Satisfies -// the web.Handler interface. -func (m *Mux) ServeHTTPC(c C, w http.ResponseWriter, r *http.Request) { - stack := m.mStack.alloc() - stack.ServeHTTPC(c, w, r) - m.mStack.release(stack) -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/web/mux_test.go b/Godeps/_workspace/src/github.com/zenazn/goji/web/mux_test.go deleted file mode 100644 index 1854524..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/web/mux_test.go +++ /dev/null @@ -1,45 +0,0 @@ -package web - -import ( - "net/http" - "net/http/httptest" - "testing" -) - -// Sanity check types -var _ http.Handler = &Mux{} -var _ Handler = &Mux{} - -// There's... really not a lot to do here. - -func TestIfItWorks(t *testing.T) { - t.Parallel() - - m := New() - ch := make(chan string, 1) - - m.Get("/hello/:name", func(c C, w http.ResponseWriter, r *http.Request) { - greeting := "Hello " - if c.Env != nil { - if g, ok := c.Env["greeting"]; ok { - greeting = g.(string) - } - } - ch <- greeting + c.URLParams["name"] - }) - - r, _ := http.NewRequest("GET", "/hello/carl", nil) - m.ServeHTTP(httptest.NewRecorder(), r) - out := <-ch - if out != "Hello carl" { - t.Errorf(`Unexpected response %q, expected "Hello carl"`, out) - } - - r, _ = http.NewRequest("GET", "/hello/bob", nil) - env := map[string]interface{}{"greeting": "Yo "} - m.ServeHTTPC(C{Env: env}, httptest.NewRecorder(), r) - out = <-ch - if out != "Yo bob" { - t.Errorf(`Unexpected response %q, expected "Yo bob"`, out) - } -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/web/pattern.go b/Godeps/_workspace/src/github.com/zenazn/goji/web/pattern.go deleted file mode 100644 index be4ef34..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/web/pattern.go +++ /dev/null @@ -1,249 +0,0 @@ -package web - -import ( - "bytes" - "fmt" - "log" - "net/http" - "regexp" - "regexp/syntax" - "strings" -) - -type regexpPattern struct { - re *regexp.Regexp - prefix string - names []string -} - -func (p regexpPattern) Prefix() string { - return p.prefix -} -func (p regexpPattern) Match(r *http.Request, c *C) bool { - return p.match(r, c, false) -} -func (p regexpPattern) Run(r *http.Request, c *C) { - p.match(r, c, false) -} - -func (p regexpPattern) match(r *http.Request, c *C, dryrun bool) bool { - matches := p.re.FindStringSubmatch(r.URL.Path) - if matches == nil || len(matches) == 0 { - return false - } - - if c == nil || dryrun || len(matches) == 1 { - return true - } - - if c.URLParams == nil { - c.URLParams = make(map[string]string, len(matches)-1) - } - for i := 1; i < len(matches); i++ { - c.URLParams[p.names[i]] = matches[i] - } - return true -} - -func (p regexpPattern) String() string { - return fmt.Sprintf("regexpPattern(%v)", p.re) -} - -/* -I'm sorry, dear reader. I really am. - -The problem here is to take an arbitrary regular expression and: -1. return a regular expression that is just like it, but left-anchored, - preferring to return the original if possible. -2. determine a string literal prefix that all matches of this regular expression - have, much like regexp.Regexp.Prefix(). Unfortunately, Prefix() does not work - in the presence of anchors, so we need to write it ourselves. - -What this actually means is that we need to sketch on the internals of the -standard regexp library to forcefully extract the information we want. - -Unfortunately, regexp.Regexp hides a lot of its state, so our abstraction is -going to be pretty leaky. The biggest leak is that we blindly assume that all -regular expressions are perl-style, not POSIX. This is probably Mostly True, and -I think most users of the library probably won't be able to notice. -*/ -func sketchOnRegex(re *regexp.Regexp) (*regexp.Regexp, string) { - rawRe := re.String() - sRe, err := syntax.Parse(rawRe, syntax.Perl) - if err != nil { - log.Printf("WARN(web): unable to parse regexp %v as perl. "+ - "This route might behave unexpectedly.", re) - return re, "" - } - sRe = sRe.Simplify() - p, err := syntax.Compile(sRe) - if err != nil { - log.Printf("WARN(web): unable to compile regexp %v. This "+ - "route might behave unexpectedly.", re) - return re, "" - } - if p.StartCond()&syntax.EmptyBeginText == 0 { - // I hope doing this is always legal... - newRe, err := regexp.Compile(`\A` + rawRe) - if err != nil { - log.Printf("WARN(web): unable to create a left-"+ - "anchored regexp from %v. This route might "+ - "behave unexpectedly", re) - return re, "" - } - re = newRe - } - - // Run the regular expression more or less by hand :( - pc := uint32(p.Start) - atStart := true - i := &p.Inst[pc] - var buf bytes.Buffer -Sadness: - for { - switch i.Op { - case syntax.InstEmptyWidth: - if !atStart { - break Sadness - } - case syntax.InstCapture, syntax.InstNop: - // nop! - case syntax.InstRune, syntax.InstRune1, syntax.InstRuneAny, - syntax.InstRuneAnyNotNL: - - atStart = false - if len(i.Rune) != 1 || - syntax.Flags(i.Arg)&syntax.FoldCase != 0 { - break Sadness - } - buf.WriteRune(i.Rune[0]) - default: - break Sadness - } - pc = i.Out - i = &p.Inst[pc] - } - return re, buf.String() -} - -func parseRegexpPattern(re *regexp.Regexp) regexpPattern { - re, prefix := sketchOnRegex(re) - rnames := re.SubexpNames() - // We have to make our own copy since package regexp forbids us - // from scribbling over the slice returned by SubexpNames(). - names := make([]string, len(rnames)) - for i, rname := range rnames { - if rname == "" { - rname = fmt.Sprintf("$%d", i) - } - names[i] = rname - } - return regexpPattern{ - re: re, - prefix: prefix, - names: names, - } -} - -type stringPattern struct { - raw string - pats []string - literals []string - isPrefix bool -} - -func (s stringPattern) Prefix() string { - return s.literals[0] -} -func (s stringPattern) Match(r *http.Request, c *C) bool { - return s.match(r, c, true) -} -func (s stringPattern) Run(r *http.Request, c *C) { - s.match(r, c, false) -} -func (s stringPattern) match(r *http.Request, c *C, dryrun bool) bool { - path := r.URL.Path - var matches map[string]string - if !dryrun && len(s.pats) > 0 { - matches = make(map[string]string, len(s.pats)) - } - for i := 0; i < len(s.pats); i++ { - sli := s.literals[i] - if !strings.HasPrefix(path, sli) { - return false - } - path = path[len(sli):] - - m := 0 - for ; m < len(path); m++ { - if path[m] == '/' { - break - } - } - if m == 0 { - // Empty strings are not matches, otherwise routes like - // "/:foo" would match the path "/" - return false - } - if !dryrun { - matches[s.pats[i]] = path[:m] - } - path = path[m:] - } - // There's exactly one more literal than pat. - if s.isPrefix { - if !strings.HasPrefix(path, s.literals[len(s.pats)]) { - return false - } - } else { - if path != s.literals[len(s.pats)] { - return false - } - } - - if c == nil || dryrun { - return true - } - - if c.URLParams == nil { - c.URLParams = matches - } else { - for k, v := range matches { - c.URLParams[k] = v - } - } - return true -} - -func (s stringPattern) String() string { - return fmt.Sprintf("stringPattern(%q, %v)", s.raw, s.isPrefix) -} - -var patternRe = regexp.MustCompile(`/:([^/]+)`) - -func parseStringPattern(s string) stringPattern { - var isPrefix bool - // Routes that end in an asterisk ("*") are prefix routes - if len(s) > 0 && s[len(s)-1] == '*' { - s = s[:len(s)-1] - isPrefix = true - } - - matches := patternRe.FindAllStringSubmatchIndex(s, -1) - pats := make([]string, len(matches)) - literals := make([]string, len(matches)+1) - n := 0 - for i, match := range matches { - a, b := match[2], match[3] - literals[i] = s[n : a-1] // Need to leave off the colon - pats[i] = s[a:b] - n = b - } - literals[len(matches)] = s[n:] - return stringPattern{ - raw: s, - pats: pats, - literals: literals, - isPrefix: isPrefix, - } -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/web/pattern_test.go b/Godeps/_workspace/src/github.com/zenazn/goji/web/pattern_test.go deleted file mode 100644 index 6b2575f..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/web/pattern_test.go +++ /dev/null @@ -1,177 +0,0 @@ -package web - -import ( - "net/http" - "reflect" - "regexp" - "testing" -) - -func pt(url string, match bool, params map[string]string) patternTest { - req, err := http.NewRequest("GET", url, nil) - if err != nil { - panic(err) - } - - return patternTest{ - r: req, - match: match, - c: &C{}, - cout: &C{URLParams: params}, - } -} - -type patternTest struct { - r *http.Request - match bool - c *C - cout *C -} - -var patternTests = []struct { - pat Pattern - prefix string - tests []patternTest -}{ - // Regexp tests - {parseRegexpPattern(regexp.MustCompile("^/hello$")), - "/hello", []patternTest{ - pt("/hello", true, nil), - pt("/hell", false, nil), - pt("/hello/", false, nil), - pt("/hello/world", false, nil), - pt("/world", false, nil), - }}, - {parseRegexpPattern(regexp.MustCompile("^/hello/(?P[a-z]+)$")), - "/hello/", []patternTest{ - pt("/hello/world", true, map[string]string{ - "name": "world", - }), - pt("/hello/", false, nil), - pt("/hello/my/love", false, nil), - }}, - {parseRegexpPattern(regexp.MustCompile(`^/a(?P\d+)/b(?P\d+)/?$`)), - "/a", []patternTest{ - pt("/a1/b2", true, map[string]string{ - "a": "1", - "b": "2", - }), - pt("/a9001/b007/", true, map[string]string{ - "a": "9001", - "b": "007", - }), - pt("/a/b", false, nil), - pt("/a", false, nil), - pt("/squirrel", false, nil), - }}, - {parseRegexpPattern(regexp.MustCompile(`^/hello/([a-z]+)$`)), - "/hello/", []patternTest{ - pt("/hello/world", true, map[string]string{ - "$1": "world", - }), - pt("/hello/", false, nil), - }}, - {parseRegexpPattern(regexp.MustCompile("/hello")), - "/hello", []patternTest{ - pt("/hello", true, nil), - pt("/hell", false, nil), - pt("/hello/", true, nil), - pt("/hello/world", true, nil), - pt("/world/hello", false, nil), - }}, - - // String pattern tests - {parseStringPattern("/hello"), - "/hello", []patternTest{ - pt("/hello", true, nil), - pt("/hell", false, nil), - pt("/hello/", false, nil), - pt("/hello/world", false, nil), - }}, - {parseStringPattern("/hello/:name"), - "/hello/", []patternTest{ - pt("/hello/world", true, map[string]string{ - "name": "world", - }), - pt("/hell", false, nil), - pt("/hello/", false, nil), - pt("/hello/my/love", false, nil), - }}, - {parseStringPattern("/a/:a/b/:b"), - "/a/", []patternTest{ - pt("/a/1/b/2", true, map[string]string{ - "a": "1", - "b": "2", - }), - pt("/a", false, nil), - pt("/a//b/", false, nil), - pt("/a/1/b/2/3", false, nil), - }}, - - // String prefix tests - {parseStringPattern("/user/:user*"), - "/user/", []patternTest{ - pt("/user/bob", true, map[string]string{ - "user": "bob", - }), - pt("/user/bob/friends/123", true, map[string]string{ - "user": "bob", - }), - pt("/user/", false, nil), - pt("/user//", false, nil), - }}, - {parseStringPattern("/user/:user/*"), - "/user/", []patternTest{ - pt("/user/bob/friends/123", true, map[string]string{ - "user": "bob", - }), - pt("/user/bob", false, nil), - pt("/user/", false, nil), - pt("/user//", false, nil), - }}, - {parseStringPattern("/user/:user/friends*"), - "/user/", []patternTest{ - pt("/user/bob/friends", true, map[string]string{ - "user": "bob", - }), - pt("/user/bob/friends/123", true, map[string]string{ - "user": "bob", - }), - // This is a little unfortunate - pt("/user/bob/friends123", true, map[string]string{ - "user": "bob", - }), - pt("/user/bob/enemies", false, nil), - }}, -} - -func TestPatterns(t *testing.T) { - t.Parallel() - - for _, pt := range patternTests { - p := pt.pat.Prefix() - if p != pt.prefix { - t.Errorf("Expected prefix %q for %v, got %q", pt.prefix, - pt.pat, p) - } else { - for _, test := range pt.tests { - runTest(t, pt.pat, test) - } - } - } -} - -func runTest(t *testing.T, p Pattern, test patternTest) { - result := p.Match(test.r, test.c) - if result != test.match { - t.Errorf("Expected match(%v, %#v) to return %v", p, - test.r.URL.Path, test.match) - return - } - p.Run(test.r, test.c) - - if !reflect.DeepEqual(test.c, test.cout) { - t.Errorf("Expected a context of %v, instead got %v", test.cout, - test.c) - } -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/web/router.go b/Godeps/_workspace/src/github.com/zenazn/goji/web/router.go deleted file mode 100644 index cc52d96..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/web/router.go +++ /dev/null @@ -1,411 +0,0 @@ -package web - -import ( - "log" - "net/http" - "regexp" - "sort" - "strings" - "sync" -) - -type method int - -const ( - mCONNECT method = 1 << iota - mDELETE - mGET - mHEAD - mOPTIONS - mPATCH - mPOST - mPUT - mTRACE - // We only natively support the methods above, but we pass through other - // methods. This constant pretty much only exists for the sake of mALL. - mIDK - - mALL method = mCONNECT | mDELETE | mGET | mHEAD | mOPTIONS | mPATCH | - mPOST | mPUT | mTRACE | mIDK -) - -// The key used to communicate to the NotFound handler what methods would have -// been allowed if they'd been provided. -const ValidMethodsKey = "goji.web.validMethods" - -var validMethodsMap = map[string]method{ - "CONNECT": mCONNECT, - "DELETE": mDELETE, - "GET": mGET, - "HEAD": mHEAD, - "OPTIONS": mOPTIONS, - "PATCH": mPATCH, - "POST": mPOST, - "PUT": mPUT, - "TRACE": mTRACE, -} - -type route struct { - // Theory: most real world routes have a string prefix which is both - // cheap(-ish) to test against and pretty selective. And, conveniently, - // both regexes and string patterns give us this out-of-box. - prefix string - method method - pattern Pattern - handler Handler -} - -type router struct { - lock sync.Mutex - routes []route - notFound Handler - machine *routeMachine -} - -// A Pattern determines whether or not a given request matches some criteria. -// They are often used in routes, which are essentially (pattern, methodSet, -// handler) tuples. If the method and pattern match, the given handler is used. -// -// Built-in implementations of this interface are used to implement regular -// expression and string matching. -type Pattern interface { - // In practice, most real-world routes have a string prefix that can be - // used to quickly determine if a pattern is an eligible match. The - // router uses the result of this function to optimize away calls to the - // full Match function, which is likely much more expensive to compute. - // If your Pattern does not support prefixes, this function should - // return the empty string. - Prefix() string - // Returns true if the request satisfies the pattern. This function is - // free to examine both the request and the context to make this - // decision. Match should not modify either argument, and since it will - // potentially be called several times over the course of matching a - // request, it should be reasonably efficient. - Match(r *http.Request, c *C) bool - // Run the pattern on the request and context, modifying the context as - // necessary to bind URL parameters or other parsed state. - Run(r *http.Request, c *C) -} - -func parsePattern(p interface{}) Pattern { - switch p.(type) { - case Pattern: - return p.(Pattern) - case *regexp.Regexp: - return parseRegexpPattern(p.(*regexp.Regexp)) - case string: - return parseStringPattern(p.(string)) - default: - log.Fatalf("Unknown pattern type %v. Expected a web.Pattern, "+ - "regexp.Regexp, or a string.", p) - } - panic("log.Fatalf does not return") -} - -type netHTTPWrap struct { - http.Handler -} - -func (h netHTTPWrap) ServeHTTP(w http.ResponseWriter, r *http.Request) { - h.Handler.ServeHTTP(w, r) -} -func (h netHTTPWrap) ServeHTTPC(c C, w http.ResponseWriter, r *http.Request) { - h.Handler.ServeHTTP(w, r) -} - -func parseHandler(h interface{}) Handler { - switch h.(type) { - case Handler: - return h.(Handler) - case http.Handler: - return netHTTPWrap{h.(http.Handler)} - case func(c C, w http.ResponseWriter, r *http.Request): - f := h.(func(c C, w http.ResponseWriter, r *http.Request)) - return HandlerFunc(f) - case func(w http.ResponseWriter, r *http.Request): - f := h.(func(w http.ResponseWriter, r *http.Request)) - return netHTTPWrap{http.HandlerFunc(f)} - default: - log.Fatalf("Unknown handler type %v. Expected a web.Handler, "+ - "a http.Handler, or a function with signature func(C, "+ - "http.ResponseWriter, *http.Request) or "+ - "func(http.ResponseWriter, *http.Request)", h) - } - panic("log.Fatalf does not return") -} - -func httpMethod(mname string) method { - if method, ok := validMethodsMap[mname]; ok { - return method - } - return mIDK -} - -type routeMachine struct { - sm stateMachine - routes []route -} - -func matchRoute(route route, m method, ms *method, r *http.Request, c *C) bool { - if !route.pattern.Match(r, c) { - return false - } - *ms |= route.method - - if route.method&m != 0 { - route.pattern.Run(r, c) - return true - } - return false -} - -func (rm routeMachine) route(c *C, w http.ResponseWriter, r *http.Request) (method, bool) { - m := httpMethod(r.Method) - var methods method - p := r.URL.Path - - if len(rm.sm) == 0 { - return methods, false - } - - var i int - for { - sm := rm.sm[i].mode - if sm&smSetCursor != 0 { - si := rm.sm[i].i - p = r.URL.Path[si:] - i++ - continue - } - - length := int(sm & smLengthMask) - match := false - if length <= len(p) { - bs := rm.sm[i].bs - switch length { - case 3: - if p[2] != bs[2] { - break - } - fallthrough - case 2: - if p[1] != bs[1] { - break - } - fallthrough - case 1: - if p[0] != bs[0] { - break - } - fallthrough - case 0: - p = p[length:] - match = true - } - } - - if match && sm&smRoute != 0 { - si := rm.sm[i].i - if matchRoute(rm.routes[si], m, &methods, r, c) { - rm.routes[si].handler.ServeHTTPC(*c, w, r) - return 0, true - } else { - i++ - } - } else if (match && sm&smJumpOnMatch != 0) || - (!match && sm&smJumpOnMatch == 0) { - - if sm&smFail != 0 { - return methods, false - } - i = int(rm.sm[i].i) - } else { - i++ - } - } - - return methods, false -} - -// Compile the list of routes into bytecode. This only needs to be done once -// after all the routes have been added, and will be called automatically for -// you (at some performance cost on the first request) if you do not call it -// explicitly. -func (rt *router) Compile() *routeMachine { - rt.lock.Lock() - defer rt.lock.Unlock() - sm := routeMachine{ - sm: compile(rt.routes), - routes: rt.routes, - } - rt.setMachine(&sm) - return &sm -} - -func (rt *router) route(c *C, w http.ResponseWriter, r *http.Request) { - rm := rt.getMachine() - if rm == nil { - rm = rt.Compile() - } - - methods, ok := rm.route(c, w, r) - if ok { - return - } - - if methods == 0 { - rt.notFound.ServeHTTPC(*c, w, r) - return - } - - var methodsList = make([]string, 0) - for mname, meth := range validMethodsMap { - if methods&meth != 0 { - methodsList = append(methodsList, mname) - } - } - sort.Strings(methodsList) - - if c.Env == nil { - c.Env = map[string]interface{}{ - ValidMethodsKey: methodsList, - } - } else { - c.Env[ValidMethodsKey] = methodsList - } - rt.notFound.ServeHTTPC(*c, w, r) -} - -func (rt *router) handleUntyped(p interface{}, m method, h interface{}) { - pat := parsePattern(p) - rt.handle(pat, m, parseHandler(h)) -} - -func (rt *router) handle(p Pattern, m method, h Handler) { - rt.lock.Lock() - defer rt.lock.Unlock() - - // Calculate the sorted insertion point, because there's no reason to do - // swapping hijinks if we're already making a copy. We need to use - // bubble sort because we can only compare adjacent elements. - pp := p.Prefix() - var i int - for i = len(rt.routes); i > 0; i-- { - rip := rt.routes[i-1].prefix - if rip <= pp || strings.HasPrefix(rip, pp) { - break - } - } - - newRoutes := make([]route, len(rt.routes)+1) - copy(newRoutes, rt.routes[:i]) - newRoutes[i] = route{ - prefix: pp, - method: m, - pattern: p, - handler: h, - } - copy(newRoutes[i+1:], rt.routes[i:]) - - rt.setMachine(nil) - rt.routes = newRoutes -} - -// This is a bit silly, but I've renamed the method receivers in the public -// functions here "m" instead of the standard "rt", since they will eventually -// be shown on the documentation for the Mux that they are included in. - -/* -Dispatch to the given handler when the pattern matches, regardless of HTTP -method. See the documentation for type Mux for a description of what types are -accepted for pattern and handler. - -This method is commonly used to implement sub-routing: an admin application, for -instance, can expose a single handler that is attached to the main Mux by -calling Handle("/admin*", adminHandler) or similar. Note that this function -doesn't strip this prefix from the path before forwarding it on (e.g., the -handler will see the full path, including the "/admin" part), but this -functionality can easily be performed by an extra middleware layer. -*/ -func (rt *router) Handle(pattern interface{}, handler interface{}) { - rt.handleUntyped(pattern, mALL, handler) -} - -// Dispatch to the given handler when the pattern matches and the HTTP method is -// CONNECT. See the documentation for type Mux for a description of what types -// are accepted for pattern and handler. -func (rt *router) Connect(pattern interface{}, handler interface{}) { - rt.handleUntyped(pattern, mCONNECT, handler) -} - -// Dispatch to the given handler when the pattern matches and the HTTP method is -// DELETE. See the documentation for type Mux for a description of what types -// are accepted for pattern and handler. -func (rt *router) Delete(pattern interface{}, handler interface{}) { - rt.handleUntyped(pattern, mDELETE, handler) -} - -// Dispatch to the given handler when the pattern matches and the HTTP method is -// GET. See the documentation for type Mux for a description of what types are -// accepted for pattern and handler. -// -// All GET handlers also transparently serve HEAD requests, since net/http will -// take care of all the fiddly bits for you. If you wish to provide an alternate -// implementation of HEAD, you should add a handler explicitly and place it -// above your GET handler. -func (rt *router) Get(pattern interface{}, handler interface{}) { - rt.handleUntyped(pattern, mGET|mHEAD, handler) -} - -// Dispatch to the given handler when the pattern matches and the HTTP method is -// HEAD. See the documentation for type Mux for a description of what types are -// accepted for pattern and handler. -func (rt *router) Head(pattern interface{}, handler interface{}) { - rt.handleUntyped(pattern, mHEAD, handler) -} - -// Dispatch to the given handler when the pattern matches and the HTTP method is -// OPTIONS. See the documentation for type Mux for a description of what types -// are accepted for pattern and handler. -func (rt *router) Options(pattern interface{}, handler interface{}) { - rt.handleUntyped(pattern, mOPTIONS, handler) -} - -// Dispatch to the given handler when the pattern matches and the HTTP method is -// PATCH. See the documentation for type Mux for a description of what types are -// accepted for pattern and handler. -func (rt *router) Patch(pattern interface{}, handler interface{}) { - rt.handleUntyped(pattern, mPATCH, handler) -} - -// Dispatch to the given handler when the pattern matches and the HTTP method is -// POST. See the documentation for type Mux for a description of what types are -// accepted for pattern and handler. -func (rt *router) Post(pattern interface{}, handler interface{}) { - rt.handleUntyped(pattern, mPOST, handler) -} - -// Dispatch to the given handler when the pattern matches and the HTTP method is -// PUT. See the documentation for type Mux for a description of what types are -// accepted for pattern and handler. -func (rt *router) Put(pattern interface{}, handler interface{}) { - rt.handleUntyped(pattern, mPUT, handler) -} - -// Dispatch to the given handler when the pattern matches and the HTTP method is -// TRACE. See the documentation for type Mux for a description of what types are -// accepted for pattern and handler. -func (rt *router) Trace(pattern interface{}, handler interface{}) { - rt.handleUntyped(pattern, mTRACE, handler) -} - -// Set the fallback (i.e., 404) handler for this mux. See the documentation for -// type Mux for a description of what types are accepted for handler. -// -// As a convenience, the context environment variable "goji.web.validMethods" -// (also available as the constant ValidMethodsKey) will be set to the list of -// HTTP methods that could have been routed had they been provided on an -// otherwise identical request. -func (rt *router) NotFound(handler interface{}) { - rt.notFound = parseHandler(handler) -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/web/router_test.go b/Godeps/_workspace/src/github.com/zenazn/goji/web/router_test.go deleted file mode 100644 index 59955cb..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/web/router_test.go +++ /dev/null @@ -1,316 +0,0 @@ -package web - -import ( - "net/http" - "net/http/httptest" - "reflect" - "regexp" - "testing" - "time" -) - -// These tests can probably be DRY'd up a bunch - -func makeRouter() *router { - return &router{ - routes: make([]route, 0), - notFound: parseHandler(http.NotFound), - } -} - -func chHandler(ch chan string, s string) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - ch <- s - }) -} - -var methods = []string{"CONNECT", "DELETE", "GET", "HEAD", "OPTIONS", "PATCH", - "POST", "PUT", "TRACE", "OTHER"} - -func TestMethods(t *testing.T) { - t.Parallel() - rt := makeRouter() - ch := make(chan string, 1) - - rt.Connect("/", chHandler(ch, "CONNECT")) - rt.Delete("/", chHandler(ch, "DELETE")) - rt.Head("/", chHandler(ch, "HEAD")) - rt.Get("/", chHandler(ch, "GET")) - rt.Options("/", chHandler(ch, "OPTIONS")) - rt.Patch("/", chHandler(ch, "PATCH")) - rt.Post("/", chHandler(ch, "POST")) - rt.Put("/", chHandler(ch, "PUT")) - rt.Trace("/", chHandler(ch, "TRACE")) - rt.Handle("/", chHandler(ch, "OTHER")) - - for _, method := range methods { - r, _ := http.NewRequest(method, "/", nil) - w := httptest.NewRecorder() - rt.route(&C{}, w, r) - select { - case val := <-ch: - if val != method { - t.Errorf("Got %q, expected %q", val, method) - } - case <-time.After(5 * time.Millisecond): - t.Errorf("Timeout waiting for method %q", method) - } - } -} - -type testPattern struct{} - -func (t testPattern) Prefix() string { - return "" -} - -func (t testPattern) Match(r *http.Request, c *C) bool { - return true -} -func (t testPattern) Run(r *http.Request, c *C) { -} - -var _ Pattern = testPattern{} - -func TestPatternTypes(t *testing.T) { - t.Parallel() - rt := makeRouter() - - rt.Get("/hello/carl", http.NotFound) - rt.Get("/hello/:name", http.NotFound) - rt.Get(regexp.MustCompile(`^/hello/(?P.+)$`), http.NotFound) - rt.Get(testPattern{}, http.NotFound) -} - -type testHandler chan string - -func (t testHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { - t <- "http" -} -func (t testHandler) ServeHTTPC(c C, w http.ResponseWriter, r *http.Request) { - t <- "httpc" -} - -var testHandlerTable = map[string]string{ - "/a": "http fn", - "/b": "http handler", - "/c": "web fn", - "/d": "web handler", - "/e": "httpc", -} - -func TestHandlerTypes(t *testing.T) { - t.Parallel() - rt := makeRouter() - ch := make(chan string, 1) - - rt.Get("/a", func(w http.ResponseWriter, r *http.Request) { - ch <- "http fn" - }) - rt.Get("/b", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - ch <- "http handler" - })) - rt.Get("/c", func(c C, w http.ResponseWriter, r *http.Request) { - ch <- "web fn" - }) - rt.Get("/d", HandlerFunc(func(c C, w http.ResponseWriter, r *http.Request) { - ch <- "web handler" - })) - rt.Get("/e", testHandler(ch)) - - for route, response := range testHandlerTable { - r, _ := http.NewRequest("GET", route, nil) - w := httptest.NewRecorder() - rt.route(&C{}, w, r) - select { - case resp := <-ch: - if resp != response { - t.Errorf("Got %q, expected %q", resp, response) - } - case <-time.After(5 * time.Millisecond): - t.Errorf("Timeout waiting for path %q", route) - } - - } -} - -// The idea behind this test is to comprehensively test if routes are being -// applied in the right order. We define a special pattern type that always -// matches so long as it's greater than or equal to the global test index. By -// incrementing this index, we can invalidate all routes up to some point, and -// therefore test the routing guarantee that Goji provides: for any path P, if -// both A and B match P, and if A was inserted before B, then Goji will route to -// A before it routes to B. -var rsRoutes = []string{ - "/", - "/a", - "/a", - "/b", - "/ab", - "/", - "/ba", - "/b", - "/a", -} - -var rsTests = []struct { - key string - results []int -}{ - {"/", []int{0, 5, 5, 5, 5, 5, -1, -1, -1, -1}}, - {"/a", []int{0, 1, 2, 5, 5, 5, 8, 8, 8, -1}}, - {"/b", []int{0, 3, 3, 3, 5, 5, 7, 7, -1, -1}}, - {"/ab", []int{0, 1, 2, 4, 4, 5, 8, 8, 8, -1}}, - {"/ba", []int{0, 3, 3, 3, 5, 5, 6, 7, -1, -1}}, - {"/c", []int{0, 5, 5, 5, 5, 5, -1, -1, -1, -1}}, - {"nope", []int{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}}, -} - -type rsPattern struct { - i int - counter *int - prefix string - ichan chan int -} - -func (rs rsPattern) Prefix() string { - return rs.prefix -} -func (rs rsPattern) Match(_ *http.Request, _ *C) bool { - return rs.i >= *rs.counter -} -func (rs rsPattern) Run(_ *http.Request, _ *C) { -} - -func (rs rsPattern) ServeHTTP(_ http.ResponseWriter, _ *http.Request) { - rs.ichan <- rs.i -} - -var _ Pattern = rsPattern{} -var _ http.Handler = rsPattern{} - -func TestRouteSelection(t *testing.T) { - t.Parallel() - rt := makeRouter() - counter := 0 - ichan := make(chan int, 1) - rt.NotFound(func(w http.ResponseWriter, r *http.Request) { - ichan <- -1 - }) - - for i, s := range rsRoutes { - pat := rsPattern{ - i: i, - counter: &counter, - prefix: s, - ichan: ichan, - } - rt.Get(pat, pat) - } - - for _, test := range rsTests { - var n int - for counter, n = range test.results { - r, _ := http.NewRequest("GET", test.key, nil) - w := httptest.NewRecorder() - rt.route(&C{}, w, r) - actual := <-ichan - if n != actual { - t.Errorf("Expected %q @ %d to be %d, got %d", - test.key, counter, n, actual) - } - } - } -} - -func TestNotFound(t *testing.T) { - t.Parallel() - rt := makeRouter() - - r, _ := http.NewRequest("post", "/", nil) - w := httptest.NewRecorder() - rt.route(&C{}, w, r) - if w.Code != 404 { - t.Errorf("Expected 404, got %d", w.Code) - } - - rt.NotFound(func(w http.ResponseWriter, r *http.Request) { - http.Error(w, "I'm a teapot!", http.StatusTeapot) - }) - - r, _ = http.NewRequest("POST", "/", nil) - w = httptest.NewRecorder() - rt.route(&C{}, w, r) - if w.Code != http.StatusTeapot { - t.Errorf("Expected a teapot, got %d", w.Code) - } -} - -func TestPrefix(t *testing.T) { - t.Parallel() - rt := makeRouter() - ch := make(chan string, 1) - - rt.Handle("/hello*", func(w http.ResponseWriter, r *http.Request) { - ch <- r.URL.Path - }) - - r, _ := http.NewRequest("GET", "/hello/world", nil) - w := httptest.NewRecorder() - rt.route(&C{}, w, r) - select { - case val := <-ch: - if val != "/hello/world" { - t.Errorf("Got %q, expected /hello/world", val) - } - case <-time.After(5 * time.Millisecond): - t.Errorf("Timeout waiting for hello") - } -} - -var validMethodsTable = map[string][]string{ - "/hello/carl": {"DELETE", "GET", "HEAD", "PATCH", "POST", "PUT"}, - "/hello/bob": {"DELETE", "GET", "HEAD", "PATCH", "PUT"}, - "/hola/carl": {"DELETE", "GET", "HEAD", "PUT"}, - "/hola/bob": {"DELETE"}, - "/does/not/compute": {}, -} - -func TestValidMethods(t *testing.T) { - t.Parallel() - rt := makeRouter() - ch := make(chan []string, 1) - - rt.NotFound(func(c C, w http.ResponseWriter, r *http.Request) { - if c.Env == nil { - ch <- []string{} - return - } - methods, ok := c.Env[ValidMethodsKey] - if !ok { - ch <- []string{} - return - } - ch <- methods.([]string) - }) - - rt.Get("/hello/carl", http.NotFound) - rt.Post("/hello/carl", http.NotFound) - rt.Head("/hello/bob", http.NotFound) - rt.Get("/hello/:name", http.NotFound) - rt.Put("/hello/:name", http.NotFound) - rt.Patch("/hello/:name", http.NotFound) - rt.Get("/:greet/carl", http.NotFound) - rt.Put("/:greet/carl", http.NotFound) - rt.Delete("/:greet/:anyone", http.NotFound) - - for path, eMethods := range validMethodsTable { - r, _ := http.NewRequest("BOGUS", path, nil) - rt.route(&C{}, httptest.NewRecorder(), r) - aMethods := <-ch - if !reflect.DeepEqual(eMethods, aMethods) { - t.Errorf("For %q, expected %v, got %v", path, eMethods, - aMethods) - } - } -} diff --git a/Godeps/_workspace/src/github.com/zenazn/goji/web/web.go b/Godeps/_workspace/src/github.com/zenazn/goji/web/web.go deleted file mode 100644 index a69e246..0000000 --- a/Godeps/_workspace/src/github.com/zenazn/goji/web/web.go +++ /dev/null @@ -1,128 +0,0 @@ -/* -Package web is a microframework inspired by Sinatra. - -The underlying philosophy behind this package is that net/http is a very good -HTTP library which is only missing a few features. If you disagree with this -statement (e.g., you think that the interfaces it exposes are not especially -good, or if you're looking for a comprehensive "batteries included" feature -list), you're likely not going to have a good time using this library. In that -spirit, we have attempted wherever possible to be compatible with net/http. You -should be able to insert any net/http compliant handler into this library, or -use this library with any other net/http compliant mux. - -This package attempts to solve three problems that net/http does not. First, it -allows you to specify URL patterns with Sinatra-like named wildcards and -regexps. Second, it allows you to write reconfigurable middleware stacks. And -finally, it allows you to attach additional context to requests, in a manner -that can be manipulated by both compliant middleware and handlers. - -A usage example: - - m := web.New() - -Use your favorite HTTP verbs: - - var legacyFooHttpHandler http.Handler // From elsewhere - m.Get("/foo", legacyFooHttpHandler) - m.Post("/bar", func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte("Hello world!")) - }) - -Bind parameters using either Sinatra-like patterns or regular expressions: - - m.Get("/hello/:name", func(c web.C, w http.ResponseWriter, r *http.Request) { - fmt.Fprintf(w, "Hello, %s!", c.URLParams["name"]) - }) - pattern := regexp.MustCompile(`^/ip/(?P(?:\d{1,3}\.){3}\d{1,3})$`) - m.Get(pattern, func(c web.C, w http.ResponseWriter, r *http.Request) { - fmt.Fprintf(w, "Info for IP address %s:", c.URLParams["ip"]) - }) - -Middleware are functions that wrap http.Handlers, just like you'd use with raw -net/http. Middleware functions can optionally take a context parameter, which -will be threaded throughout the middleware stack and to the final handler, even -if not all of these things do not support contexts. Middleware are encouraged to -use the Env parameter to pass data to other middleware and to the final handler: - - m.Use(func(h http.Handler) http.Handler { - handler := func(w http.ResponseWriter, r *http.Request) { - log.Println("Before request") - h.ServeHTTP(w, r) - log.Println("After request") - } - return http.HandlerFunc(handler) - }) - m.Use(func(c *web.C, h http.Handler) http.Handler { - handler := func(w http.ResponseWriter, r *http.Request) { - cookie, err := r.Cookie("user") - if err == nil { - // Consider using the middleware EnvInit instead - // of repeating the below check - if c.Env == nil { - c.Env = make(map[string]interface{}) - } - c.Env["user"] = cookie.Value - } - h.ServeHTTP(w, r) - } - return http.HandlerFunc(handler) - }) - - m.Get("/baz", func(c web.C, w http.ResponseWriter, r *http.Request) { - if user, ok := c.Env["user"].(string); ok { - w.Write([]byte("Hello " + user)) - } else { - w.Write([]byte("Hello Stranger!")) - } - }) -*/ -package web - -import ( - "net/http" -) - -/* -C is a per-request context object which is threaded through all compliant middleware -layers and to the final request handler. - -As an implementation detail, references to these structs are reused between -requests to reduce allocation churn, but the maps they contain are created fresh -on every request. If you are closing over a context (especially relevant for -middleware), you should not close over either the URLParams or Env objects, -instead accessing them through the context whenever they are required. -*/ -type C struct { - // The parameters parsed by the mux from the URL itself. In most cases, - // will contain a map from programmer-specified identifiers to the - // strings that matched those identifiers, but if a unnamed regex - // capture is used, it will be assigned to the special identifiers "$1", - // "$2", etc. - URLParams map[string]string - // A free-form environment, similar to Rack or PEP 333's environments. - // Middleware layers are encouraged to pass data to downstream layers - // and other handlers using this map, and are even more strongly - // encouraged to document and maybe namespace they keys they use. - Env map[string]interface{} -} - -// Handler is a superset of net/http's http.Handler, which also includes a -// mechanism for serving requests with a context. If your handler does not -// support the use of contexts, we encourage you to use http.Handler instead. -type Handler interface { - http.Handler - ServeHTTPC(C, http.ResponseWriter, *http.Request) -} - -// HandlerFunc is like net/http's http.HandlerFunc, but supports a context -// object. Implements both http.Handler and web.Handler free of charge. -type HandlerFunc func(C, http.ResponseWriter, *http.Request) - -func (h HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) { - h(C{}, w, r) -} - -// ServeHTTPC wraps ServeHTTP with a context parameter. -func (h HandlerFunc) ServeHTTPC(c C, w http.ResponseWriter, r *http.Request) { - h(c, w, r) -} diff --git a/README.md b/README.md index 3451b4a..6032992 100644 --- a/README.md +++ b/README.md @@ -18,13 +18,16 @@ It features: ### Compatibility -Bamboo v0.1.1 supports Marathon 0.6 and Mesos 0.19.x +v0.1.1 supports Marathon 0.6 and Mesos 0.19.x +v0.2.2 supports both DNS and non-DNS proxy ACL rules +v0.2.8 supports both HTTP & TCP via custom Marathon enviroment variables (read below for details) +v0.2.9 supports Marathon 0.7.* (with [http_callback enabled](https://mesosphere.github.io/marathon/docs/rest-api.html#event-subscriptions)) and Mesos 0.21.x +v0.2.11 improves API, deprecate previous API endpoint -Bamboo v0.2.9 supports Marathon 0.7.* (with [http_callback enabled](https://mesosphere.github.io/marathon/docs/rest-api.html#event-subscriptions)) and Mesos 0.21.x. Since v0.2.2, Bamboo supports both DNS and non-DNS proxy ACL rules. v0.2.8 Supports both HTTP & TCP via custom Marathon enviroment variables (read below for details). ### Releases and changelog -Since Marathon API and behaviour may change over time, espeically in this early days. You should expect we aim to catch up those changes, improve design and adding new features. We aim to maintain backwards compatibility when possible. Releases and changelog are maintained in the [releases page](https://github.com/QubitProducts/bamboo/releases). Please read them when upgrading. +Since Marathon API and behaviour may change over time, especially in this early days. You should expect we aim to catch up those changes, improve design and adding new features. We aim to maintain backwards compatibility when possible. Releases and changelog are maintained in the [releases page](https://github.com/QubitProducts/bamboo/releases). Please read them when upgrading. ## Deployment Guide @@ -151,27 +154,27 @@ curl -i http://localhost:8000/api/state #### POST /api/services -Creates a service configuration for a Marathon application ID +Creates a service configuration for a Marathon Application ID ```bash -curl -i -X POST -d '{"id":"/app-1","acl":"hdr(host) -i app-1.example.com"}' http://localhost:8000/api/services +curl -i -X POST -d '{"id":"/ExampleAppGroup/app1","acl":"hdr(host) -i app-1.example.com"}' http://localhost:8000/api/services ``` #### PUT /api/services/:id -Updates an existing service configuraiton for a Marathon application. `:id` is URI encoded Marathon application ID +Updates an existing service configuration for a Marathon application. `:id` is Marathon Application ID ```bash -curl -i -X PUT -d '{"id":"/app-1", "acl":"path_beg -i /group/app-1"}' http://localhost:8000/api/services/%252Fapp-1 +curl -i -X PUT -d '{"id":"/ExampleAppGroup/app1", "acl":"path_beg -i /group/app-1"}' http://localhost:8000/api/services//ExampleAppGroup/app1 ``` #### DELETE /api/services/:id -Deletes an existing service configuration. `:id` is URI encoded Marathon application ID +Deletes an existing service configuration. `:id` Marathon Application ID ```bash -curl -i -X DELETE http://localhost:8000/api/services/%252Fapp-1 +curl -i -X DELETE http://localhost:8000/api/services//ExampleAppGroup/app1 ``` #### GET /status diff --git a/VERSION b/VERSION index 1866a36..d3b5ba4 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.2.9 +0.2.11 diff --git a/api/service.go b/api/service.go index 9e134d1..8fbef37 100644 --- a/api/service.go +++ b/api/service.go @@ -5,10 +5,9 @@ import ( "errors" "io/ioutil" "net/http" - "net/url" + "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/go-martini/martini" zk "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk" - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/zenazn/goji/web" conf "github.com/QubitProducts/bamboo/configuration" "github.com/QubitProducts/bamboo/services/service" ) @@ -46,15 +45,18 @@ func (d *ServiceAPI) Create(w http.ResponseWriter, r *http.Request) { responseJSON(w, serviceModel) } -func (d *ServiceAPI) Put(c web.C, w http.ResponseWriter, r *http.Request) { - identifier, _ := url.QueryUnescape(c.URLParams["id"]) +func (d *ServiceAPI) Put(params martini.Params, w http.ResponseWriter, r *http.Request) { + + identity := params["_1"] + println(identity) + serviceModel, err := extractServiceModel(r) if err != nil { responseError(w, err.Error()) return } - _, err1 := service.Put(d.Zookeeper, d.Config.Bamboo.Zookeeper, identifier, serviceModel.Acl) + _, err1 := service.Put(d.Zookeeper, d.Config.Bamboo.Zookeeper, identity, serviceModel.Acl) if err1 != nil { responseError(w, err1.Error()) return @@ -63,9 +65,8 @@ func (d *ServiceAPI) Put(c web.C, w http.ResponseWriter, r *http.Request) { responseJSON(w, serviceModel) } -func (d *ServiceAPI) Delete(c web.C, w http.ResponseWriter, r *http.Request) { - identifier, _ := url.QueryUnescape(c.URLParams["id"]) - err := service.Delete(d.Zookeeper, d.Config.Bamboo.Zookeeper, identifier) +func (d *ServiceAPI) Delete(params martini.Params, w http.ResponseWriter, r *http.Request) { + err := service.Delete(d.Zookeeper, d.Config.Bamboo.Zookeeper, params["_1"]) if err != nil { responseError(w, err.Error()) return diff --git a/main/bamboo/bamboo.go b/main/bamboo/bamboo.go index a0853f6..569e703 100644 --- a/main/bamboo/bamboo.go +++ b/main/bamboo/bamboo.go @@ -13,10 +13,10 @@ import ( "syscall" "time" + "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/go-martini/martini" "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/kardianos/osext" "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/natefinch/lumberjack" "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk" - "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/zenazn/goji" "github.com/QubitProducts/bamboo/api" "github.com/QubitProducts/bamboo/configuration" "github.com/QubitProducts/bamboo/qzk" @@ -28,10 +28,12 @@ import ( */ var configFilePath string var logPath string +var serverBindPort string func init() { flag.StringVar(&configFilePath, "config", "config/development.json", "Full path of the configuration JSON file") flag.StringVar(&logPath, "log", "", "Log path to a file. Default logs to stdout") + flag.StringVar(&serverBindPort, "bind", ":8000", "Bind HTTP server to a specific port") } func main() { @@ -69,7 +71,10 @@ func main() { handlers := event_bus.Handlers{Conf: &conf, Zookeeper: zkConn} eventBus.Register(handlers.MarathonEventHandler) eventBus.Register(handlers.ServiceEventHandler) - eventBus.Publish(event_bus.MarathonEvent { EventType: "bamboo_startup", Timestamp: time.Now().Format(time.RFC3339) }) + eventBus.Publish(event_bus.MarathonEvent{EventType: "bamboo_startup", Timestamp: time.Now().Format(time.RFC3339)}) + + // Handle gracefully exit + registerOSSignals() // Start server initServer(&conf, zkConn, eventBus) @@ -82,24 +87,26 @@ func initServer(conf *configuration.Configuration, conn *zk.Conn, eventBus *even conf.StatsD.Increment(1.0, "restart", 1) // Status live information - goji.Get("/status", api.HandleStatus) - - // State API - goji.Get("/api/state", stateAPI.Get) - - // Service API - goji.Get("/api/services", serviceAPI.All) - goji.Post("/api/services", serviceAPI.Create) - goji.Put("/api/services/:id", serviceAPI.Put) - goji.Delete("/api/services/:id", serviceAPI.Delete) - goji.Post("/api/marathon/event_callback", eventSubAPI.Callback) + router := martini.Classic() + router.Get("/status", api.HandleStatus) + + // API + router.Group("/api", func(api martini.Router) { + // State API + api.Get("/state", stateAPI.Get) + // Service API + api.Get("/services", serviceAPI.All) + api.Post("/services", serviceAPI.Create) + api.Put("/services/**", serviceAPI.Put) + api.Delete("/services/**", serviceAPI.Delete) + api.Post("/marathon/event_callback", eventSubAPI.Callback) + }) // Static pages - goji.Get("/*", http.FileServer(http.Dir(path.Join(executableFolder(), "webapp")))) + router.Use(martini.Static(path.Join(executableFolder(), "webapp"))) registerMarathonEvent(conf) - - goji.Serve() + router.RunOnAddr(serverBindPort) } // Get current executable folder path @@ -176,3 +183,14 @@ func configureLog() { }, os.Stdout)) } } + +func registerOSSignals() { + c := make(chan os.Signal, 1) + signal.Notify(c, os.Interrupt) + go func() { + for _ = range c { + log.Println("Server Stopped") + os.Exit(0) + } + }() +} diff --git a/package.json b/package.json index 37171bb..1e154b7 100644 --- a/package.json +++ b/package.json @@ -31,7 +31,7 @@ }, "napa": { "angular-strap": "mgcrea/angular-strap#v2.0.5", - "angular": "angular/bower-angular#v1.2.22-build.376+sha.93b0c2d", + "angular": "angular/bower-angular#v1.2.22", "angular-animate": "angular/bower-angular-animate#v1.2.22-build.376+sha.93b0c2d", "angular-resource": "angular/bower-angular-resource#v1.2.22-build.376+sha.93b0c2d", "angular-ui-router": "angular-ui/ui-router#0.2.10" diff --git a/services/service/service.go b/services/service/service.go index e0a4e92..6759300 100644 --- a/services/service/service.go +++ b/services/service/service.go @@ -2,7 +2,7 @@ package service import ( "net/url" - + "strings" "github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk" conf "github.com/QubitProducts/bamboo/configuration" ) @@ -43,7 +43,7 @@ func All(conn *zk.Conn, zkConf conf.Zookeeper) (map[string]Service, error) { http://zookeeper.apache.org/doc/trunk/zookeeperProgrammers.html#sc_ACLPermissions */ func Create(conn *zk.Conn, zkConf conf.Zookeeper, appId string, domainValue string) (string, error) { - path := concatPath(zkConf.Path, appId) + path := concatPath(zkConf.Path, validateAppId(appId)) resPath, err := conn.Create(path, []byte(domainValue), 0, defaultACL()) if err != nil { return "", err @@ -53,12 +53,17 @@ func Create(conn *zk.Conn, zkConf conf.Zookeeper, appId string, domainValue stri } func Put(conn *zk.Conn, zkConf conf.Zookeeper, appId string, domainValue string) (*zk.Stat, error) { - path := concatPath(zkConf.Path, appId) - stats, err := conn.Set(path, []byte(domainValue), -1) + path := concatPath(zkConf.Path, validateAppId(appId)) + err := ensurePathExists(conn, path) + if err != nil { + return nil, err + } + stats, err := conn.Set(path, []byte(domainValue), -1) if err != nil { return nil, err } + // Force triger an event on parent conn.Set(zkConf.Path, []byte{}, -1) @@ -66,7 +71,7 @@ func Put(conn *zk.Conn, zkConf conf.Zookeeper, appId string, domainValue string) } func Delete(conn *zk.Conn, zkConf conf.Zookeeper, appId string) error { - path := concatPath(zkConf.Path, appId) + path := concatPath(zkConf.Path, validateAppId(appId)) return conn.Delete(path, -1) } @@ -92,6 +97,14 @@ func defaultACL() []zk.ACL { return []zk.ACL{zk.ACL{Perms: zk.PermAll, Scheme: "world", ID: "anyone"}} } +func validateAppId(appId string) string { + if strings.HasPrefix(appId, "/") { + return appId + } else { + return "/" + appId + } +} + func escapeSlashes(id string) string { return url.QueryEscape(id) } diff --git a/webapp/app/components/resources/service-resource.js b/webapp/app/components/resources/service-resource.js index 6746fb5..dadff33 100644 --- a/webapp/app/components/resources/service-resource.js +++ b/webapp/app/components/resources/service-resource.js @@ -11,11 +11,6 @@ module.exports = ["$resource", function ($resource) { destroy: { method: "DELETE", params: { id: "@id"} } }); - var encodeId = function (params) { - params.id = encodeURIComponent(params.id); - return params; - }; - return { all: function () { return index.get().$promise; @@ -24,13 +19,13 @@ module.exports = ["$resource", function ($resource) { create: function (params) { return index.create(params).$promise; }, - + update: function (params) { - return entity.update(encodeId(params)).$promise; + return entity.update(params).$promise; }, destroy: function (params) { - return entity.destroy(encodeId(params)).$promise; + return entity.destroy(params).$promise; } } }]; \ No newline at end of file diff --git a/webapp/dist/main-app.js b/webapp/dist/main-app.js index 8b1fc40..59b10bd 100644 --- a/webapp/dist/main-app.js +++ b/webapp/dist/main-app.js @@ -18,20 +18,20 @@ module.exports=require('ziotlU'); module.exports=require('HlZQrA'); },{}],10:[function(require,module,exports){ (function (global){ -(function(){function n(n,r,t){for(var e=(t||0)-1,u=n?n.length:0;++e-1?0:-1:r?0:-1}function t(n){var r=this.cache,t=typeof n;if("boolean"==t||null==n)r[n]=!0;else{"number"!=t&&"string"!=t&&(t="object");var e="number"==t?n:m+n,u=r[t]||(r[t]={});"object"==t?(u[e]||(u[e]=[])).push(n):u[e]=!0}}function e(n){return n.charCodeAt(0)}function u(n,r){for(var t=n.criteria,e=r.criteria,u=-1,o=t.length;++ui||"undefined"==typeof a)return 1;if(i>a||"undefined"==typeof i)return-1}}return n.index-r.index}function o(n){var r=-1,e=n.length,u=n[0],o=n[e/2|0],a=n[e-1];if(u&&"object"==typeof u&&o&&"object"==typeof o&&a&&"object"==typeof a)return!1;var i=f();i["false"]=i["null"]=i["true"]=i.undefined=!1;var l=f();for(l.array=n,l.cache=i,l.push=t;++ru?0:u);++e=b&&a===n,l=[];if(f){var p=o(e);p?(a=r,e=p):f=!1}for(;++u-1:void 0});return u.pop(),o.pop(),b&&(l(u),l(o)),a}function tr(n,r,t,e,u){(Xe(r)?Qr:iu)(r,function(r,o){var a,i,f=r,l=n[o];if(r&&((i=Xe(r))||fu(r))){for(var c=e.length;c--;)if(a=e[c]==r){l=u[c];break}if(!a){var p;t&&(f=t(l,r),(p="undefined"!=typeof f)&&(l=f)),p||(l=i?Xe(l)?l:[]:fu(l)?l:{}),e.push(r),u.push(l),p||tr(l,r,t,e,u)}}else t&&(f=t(l,r),"undefined"==typeof f&&(f=r)),"undefined"!=typeof f&&(l=f);n[o]=l})}function er(n,r){return n+Ie(Ge()*(r-n+1))}function ur(t,e,u){var a=-1,f=fr(),p=t?t.length:0,s=[],v=!e&&p>=b&&f===n,h=u||v?i():s;if(v){var g=o(h);f=r,h=g}for(;++a3&&"function"==typeof r[t-2])var e=Q(r[--t-1],r[t--],2);else t>2&&"function"==typeof r[t-1]&&(e=r[--t]);for(var u=p(arguments,1,t),o=-1,a=i(),f=i();++ot?Ue(0,o+t):t)||0,Xe(n)?a=u(n,r,t)>-1:"number"==typeof o?a=($r(n)?n.indexOf(r,t):u(n,r,t))>-1:iu(n,function(n){return++e>=t?!(a=n===r):void 0}),a}function Vr(n,r,t){var e=!0;r=h.createCallback(r,t,3);var u=-1,o=n?n.length:0;if("number"==typeof o)for(;++uo&&(o=f)}else r=null==r&&$r(n)?e:h.createCallback(r,t,3),Qr(n,function(n,t,e){var a=r(n,t,e);a>u&&(u=a,o=n)});return o}function rt(n,r,t){var u=1/0,o=u;if("function"!=typeof r&&t&&t[r]===n&&(r=null),null==r&&Xe(n))for(var a=-1,i=n.length;++af&&(o=f)}else r=null==r&&$r(n)?e:h.createCallback(r,t,3),Qr(n,function(n,t,e){var a=r(n,t,e);u>a&&(u=a,o=n)});return o}function tt(n,r,t,e){if(!n)return t;var u=arguments.length<3;r=h.createCallback(r,e,4);var o=-1,a=n.length;if("number"==typeof a)for(u&&(t=n[++o]);++oe?Ue(0,u+e):e||0}else if(e){var o=Ot(r,t);return r[o]===t?o:-1}return n(r,t,e)}function bt(n,r,t){var e=0,u=n?n.length:0;if("number"!=typeof r&&null!=r){var o=u;for(r=h.createCallback(r,t,3);o--&&r(n[o],o,n);)e++}else e=null==r||t?1:r||e;return p(n,0,Me(Ue(0,u-e),u))}function dt(){for(var t=[],e=-1,u=arguments.length,a=i(),f=fr(),p=f===n,s=i();++e=b&&o(e?t[e]:s)))}var h=t[0],g=-1,y=h?h.length:0,m=[];n:for(;++gt?Ue(0,e+t):Me(t,e-1))+1);e--;)if(n[e]===r)return e;return-1}function jt(n){for(var r=arguments,t=0,e=r.length,u=n?n.length:0;++tu;){var a=u+o>>>1;t(n[a])1?arguments:arguments[0],r=-1,t=n?nt(su(n,"length")):0,e=ve(0>t?0:t);++r2?ar(n,17,p(arguments,2),null,r):ar(n,1,null,null,r)}function $t(n){for(var r=arguments.length>1?nr(arguments,!0,!1,1):_r(n),t=-1,e=r.length;++t2?ar(r,19,p(arguments,2),null,n):ar(r,3,null,null,n)}function Bt(){for(var n=arguments,r=n.length;r--;)if(!Er(n[r]))throw new je;return function(){for(var r=arguments,t=n.length;t--;)r=[n[t].apply(this,r)];return r[0]}}function Wt(n,r){return r="number"==typeof r?r:+r||n.length,ar(n,4,null,null,null,r)}function qt(n,r,t){var e,u,o,a,i,f,l,c=0,p=!1,s=!0;if(!Er(n))throw new je;if(r=Ue(0,r)||0,t===!0){var h=!0;s=!1}else Ir(t)&&(h=t.leading,p="maxWait"in t&&(Ue(r,t.maxWait)||0),s="trailing"in t?t.trailing:s);var g=function(){var t=r-(hu()-a);if(0>=t){u&&Ee(u);var p=l;u=f=l=v,p&&(c=hu(),o=n.apply(i,e),f||u||(e=i=null))}else f=$e(g,t)},y=function(){f&&Ee(f),u=f=l=v,(s||p!==r)&&(c=hu(),o=n.apply(i,e),f||u||(e=i=null))};return function(){if(e=arguments,a=hu(),i=this,l=s&&(f||!h),p===!1)var t=h&&!f;else{u||h||(c=a);var v=p-(a-c),m=0>=v;m?(u&&(u=Ee(u)),c=a,o=n.apply(i,e)):u||(u=$e(y,v))}return m&&f?f=Ee(f):f||r===p||(f=$e(g,r)),t&&(m=!0,o=n.apply(i,e)),!m||f||u||(e=i=null),o}}function zt(n){if(!Er(n))throw new je;var r=p(arguments,1);return $e(function(){n.apply(v,r)},1)}function Lt(n,r){if(!Er(n))throw new je;var t=p(arguments,2);return $e(function(){n.apply(v,t)},r)}function Pt(n,r){if(!Er(n))throw new je;var t=function(){var e=t.cache,u=r?r.apply(this,arguments):m+arguments[0];return De.call(e,u)?e[u]:e[u]=n.apply(this,arguments)};return t.cache={},t}function Kt(n){var r,t;if(!Er(n))throw new je;return function(){return r?t:(r=!0,t=n.apply(this,arguments),n=null,t)}}function Ut(n){return ar(n,16,p(arguments,1))}function Mt(n){return ar(n,32,null,p(arguments,1))}function Vt(n,r,t){var e=!0,u=!0;if(!Er(n))throw new je;return t===!1?e=!1:Ir(t)&&(e="leading"in t?t.leading:e,u="trailing"in t?t.trailing:u),U.leading=e,U.maxWait=r,U.trailing=u,qt(n,r,U)}function Gt(n,r){return ar(r,16,[n])}function Ht(n){return function(){return n}}function Jt(n,r,t){var e=typeof n;if(null==n||"function"==e)return Q(n,r,t);if("object"!=e)return re(n);var u=Ze(n),o=u[0],a=n[o];return 1!=u.length||a!==a||Ir(a)?function(r){for(var t=u.length,e=!1;t--&&(e=rr(r[u[t]],n[u[t]],null,!0)););return e}:function(n){var r=n[o];return a===r&&(0!==a||1/a==1/r)}}function Qt(n){return null==n?"":we(n).replace(eu,ir)}function Xt(n){return n}function Yt(n,r,t){var e=!0,u=r&&_r(r);r&&(t||u.length)||(null==t&&(t=r),o=g,r=n,n=h,u=_r(r)),t===!1?e=!1:Ir(t)&&"chain"in t&&(e=t.chain);var o=n,a=Er(o);Qr(u,function(t){var u=n[t]=r[t];a&&(o.prototype[t]=function(){var r=this.__chain__,t=this.__wrapped__,a=[t];Te.apply(a,arguments);var i=u.apply(n,a);if(e||r){if(t===i&&Ir(i))return this;i=new o(i),i.__chain__=r}return i})})}function Zt(){return t._=Ce,this}function ne(){}function re(n){return function(r){return r[n]}}function te(n,r,t){var e=null==n,u=null==r;if(null==t&&("boolean"==typeof n&&u?(t=n,n=1):u||"boolean"!=typeof r||(t=r,u=!0)),e&&u&&(r=1),n=+n||0,u?(r=n,n=0):r=+r||0,t||n%1||r%1){var o=Ge();return Me(n+o*(r-n+parseFloat("1e-"+((o+"").length-1))),r)}return er(n,r)}function ee(n,r){if(n){var t=n[r];return Er(t)?n[r]():t}}function ue(n,r,t){var e=h.templateSettings;n=we(n||""),t=ou({},t,e);var u,o=ou({},t.imports,e.imports),i=Ze(o),f=Kr(o),l=0,c=t.interpolate||E,p="__p += '",s=_e((t.escape||E).source+"|"+c.source+"|"+(c===N?x:E).source+"|"+(t.evaluate||E).source+"|$","g");n.replace(s,function(r,t,e,o,i,f){return e||(e=o),p+=n.slice(l,f).replace(S,a),t&&(p+="' +\n__e("+t+") +\n'"),i&&(u=!0,p+="';\n"+i+";\n__p += '"),e&&(p+="' +\n((__t = ("+e+")) == null ? '' : __t) +\n'"),l=f+r.length,r}),p+="';\n";var g=t.variable,y=g;y||(g="obj",p="with ("+g+") {\n"+p+"\n}\n"),p=(u?p.replace(w,""):p).replace(j,"$1").replace(k,"$1;"),p="function("+g+") {\n"+(y?"":g+" || ("+g+" = {});\n")+"var __t, __p = '', __e = _.escape"+(u?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+p+"return __p\n}";var m="\n/*\n//# sourceURL="+(t.sourceURL||"/lodash/template/source["+D++ +"]")+"\n*/";try{var b=ye(i,"return "+p+m).apply(v,f)}catch(d){throw d.source=p,d}return r?b(r):(b.source=p,b)}function oe(n,r,t){n=(n=+n)>-1?n:0;var e=-1,u=ve(n);for(r=Q(r,t,1);++e/g,evaluate:/<%([\s\S]+?)%>/g,interpolate:N,variable:"",imports:{_:h}},qe||(J=function(){function n(){}return function(r){if(Ir(r)){n.prototype=r;var e=new n;n.prototype=null}return e||t.Object()}}());var Qe=We?function(n,r){M.value=r,We(n,"__bindData__",M)}:ne,Xe=ze||function(n){return n&&"object"==typeof n&&"number"==typeof n.length&&Oe.call(n)==$||!1},Ye=function(n){var r,t=n,e=[];if(!t)return e;if(!V[typeof n])return e;for(r in t)De.call(t,r)&&e.push(r);return e},Ze=Ke?function(n){return Ir(n)?Ke(n):[]}:Ye,nu={"&":"&","<":"<",">":">",'"':""","'":"'"},ru=jr(nu),tu=_e("("+Ze(ru).join("|")+")","g"),eu=_e("["+Ze(nu).join("")+"]","g"),uu=function(n,r,t){var e,u=n,o=u;if(!u)return o;var a=arguments,i=0,f="number"==typeof t?2:a.length;if(f>3&&"function"==typeof a[f-2])var l=Q(a[--f-1],a[f--],2);else f>2&&"function"==typeof a[f-1]&&(l=a[--f]);for(;++i/g,R=RegExp("^["+_+"]*0+(?=.$)"),E=/($^)/,I=/\bthis\b/,S=/['\n\r\t\u2028\u2029\\]/g,A=["Array","Boolean","Date","Function","Math","Number","Object","RegExp","String","_","attachEvent","clearTimeout","isFinite","isNaN","parseInt","setTimeout"],D=0,T="[object Arguments]",$="[object Array]",F="[object Boolean]",B="[object Date]",W="[object Function]",q="[object Number]",z="[object Object]",L="[object RegExp]",P="[object String]",K={};K[W]=!1,K[T]=K[$]=K[F]=K[B]=K[q]=K[z]=K[L]=K[P]=!0;var U={leading:!1,maxWait:0,trailing:!1},M={configurable:!1,enumerable:!1,value:null,writable:!1},V={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},G={"\\":"\\","'":"'","\n":"n","\r":"r"," ":"t","\u2028":"u2028","\u2029":"u2029"},H=V[typeof window]&&window||this,J=V[typeof exports]&&exports&&!exports.nodeType&&exports,Q=V[typeof module]&&module&&!module.nodeType&&module,X=Q&&Q.exports===J&&J,Y=V[typeof global]&&global;!Y||Y.global!==Y&&Y.window!==Y||(H=Y);var Z=s();"function"==typeof define&&"object"==typeof define.amd&&define.amd?(H._=Z,define(function(){return Z})):J&&Q?X?(Q.exports=Z)._=Z:J._=Z:H._=Z}).call(this); +(function(){function n(n,r,t){for(var e=(t||0)-1,u=n?n.length:0;++e-1?0:-1:r?0:-1}function t(n){var r=this.cache,t=typeof n;if("boolean"==t||null==n)r[n]=!0;else{"number"!=t&&"string"!=t&&(t="object");var e="number"==t?n:m+n,u=r[t]||(r[t]={});"object"==t?(u[e]||(u[e]=[])).push(n):u[e]=!0}}function e(n){return n.charCodeAt(0)}function u(n,r){for(var t=n.criteria,e=r.criteria,u=-1,o=t.length;++ui||"undefined"==typeof a)return 1;if(i>a||"undefined"==typeof i)return-1}}return n.index-r.index}function o(n){var r=-1,e=n.length,u=n[0],o=n[e/2|0],a=n[e-1];if(u&&"object"==typeof u&&o&&"object"==typeof o&&a&&"object"==typeof a)return!1;var i=f();i["false"]=i["null"]=i["true"]=i.undefined=!1;var l=f();for(l.array=n,l.cache=i,l.push=t;++ru?0:u);++e=b&&a===n,l=[];if(f){var p=o(e);p?(a=r,e=p):f=!1}for(;++u-1:void 0});return u.pop(),o.pop(),b&&(l(u),l(o)),a}function tn(n,r,t,e,u){(Yt(r)?Xn:fe)(r,function(r,o){var a,i,f=r,l=n[o];if(r&&((i=Yt(r))||le(r))){for(var c=e.length;c--;)if(a=e[c]==r){l=u[c];break}if(!a){var p;t&&(f=t(l,r),(p="undefined"!=typeof f)&&(l=f)),p||(l=i?Yt(l)?l:[]:le(l)?l:{}),e.push(r),u.push(l),p||tn(l,r,t,e,u)}}else t&&(f=t(l,r),"undefined"==typeof f&&(f=r)),"undefined"!=typeof f&&(l=f);n[o]=l})}function en(n,r){return n+St(Ht()*(r-n+1))}function un(t,e,u){var a=-1,f=ln(),p=t?t.length:0,s=[],v=!e&&p>=b&&f===n,h=u||v?i():s;if(v){var g=o(h);f=r,h=g}for(;++a3&&"function"==typeof r[t-2])var e=Q(r[--t-1],r[t--],2);else t>2&&"function"==typeof r[t-1]&&(e=r[--t]);for(var u=p(arguments,1,t),o=-1,a=i(),f=i();++ot?Mt(0,o+t):t)||0,Yt(n)?a=u(n,r,t)>-1:"number"==typeof o?a=(Fn(n)?n.indexOf(r,t):u(n,r,t))>-1:fe(n,function(n){return++e>=t?!(a=n===r):void 0}),a}function Gn(n,r,t){var e=!0;r=h.createCallback(r,t,3);var u=-1,o=n?n.length:0;if("number"==typeof o)for(;++uo&&(o=f)}else r=null==r&&Fn(n)?e:h.createCallback(r,t,3),Xn(n,function(n,t,e){var a=r(n,t,e);a>u&&(u=a,o=n)});return o}function tr(n,r,t){var u=1/0,o=u;if("function"!=typeof r&&t&&t[r]===n&&(r=null),null==r&&Yt(n))for(var a=-1,i=n.length;++af&&(o=f)}else r=null==r&&Fn(n)?e:h.createCallback(r,t,3),Xn(n,function(n,t,e){var a=r(n,t,e);u>a&&(u=a,o=n)});return o}function er(n,r,t,e){if(!n)return t;var u=arguments.length<3;r=h.createCallback(r,e,4);var o=-1,a=n.length;if("number"==typeof a)for(u&&(t=n[++o]);++oe?Mt(0,u+e):e||0}else if(e){var o=Nr(r,t);return r[o]===t?o:-1}return n(r,t,e)}function dr(n,r,t){var e=0,u=n?n.length:0;if("number"!=typeof r&&null!=r){var o=u;for(r=h.createCallback(r,t,3);o--&&r(n[o],o,n);)e++}else e=null==r||t?1:r||e;return p(n,0,Vt(Mt(0,u-e),u))}function _r(){for(var t=[],e=-1,u=arguments.length,a=i(),f=ln(),p=f===n,s=i();++e=b&&o(e?t[e]:s)))}var h=t[0],g=-1,y=h?h.length:0,m=[];n:for(;++gt?Mt(0,e+t):Vt(t,e-1))+1);e--;)if(n[e]===r)return e;return-1}function kr(n){for(var r=arguments,t=0,e=r.length,u=n?n.length:0;++tu;){var a=u+o>>>1;t(n[a])1?arguments:arguments[0],r=-1,t=n?rr(ve(n,"length")):0,e=ht(0>t?0:t);++r2?an(n,17,p(arguments,2),null,r):an(n,1,null,null,r)}function Fr(n){for(var r=arguments.length>1?nn(arguments,!0,!1,1):wn(n),t=-1,e=r.length;++t2?an(r,19,p(arguments,2),null,n):an(r,3,null,null,n)}function Wr(){for(var n=arguments,r=n.length;r--;)if(!In(n[r]))throw new kt;return function(){for(var r=arguments,t=n.length;t--;)r=[n[t].apply(this,r)];return r[0]}}function qr(n,r){return r="number"==typeof r?r:+r||n.length,an(n,4,null,null,null,r)}function zr(n,r,t){var e,u,o,a,i,f,l,c=0,p=!1,s=!0;if(!In(n))throw new kt;if(r=Mt(0,r)||0,t===!0){var h=!0;s=!1}else Sn(t)&&(h=t.leading,p="maxWait"in t&&(Mt(r,t.maxWait)||0),s="trailing"in t?t.trailing:s);var g=function(){var t=r-(ge()-a);if(0>=t){u&&It(u);var p=l;u=f=l=v,p&&(c=ge(),o=n.apply(i,e),f||u||(e=i=null))}else f=Ft(g,t)},y=function(){f&&It(f),u=f=l=v,(s||p!==r)&&(c=ge(),o=n.apply(i,e),f||u||(e=i=null))};return function(){if(e=arguments,a=ge(),i=this,l=s&&(f||!h),p===!1)var t=h&&!f;else{u||h||(c=a);var v=p-(a-c),m=0>=v;m?(u&&(u=It(u)),c=a,o=n.apply(i,e)):u||(u=Ft(y,v))}return m&&f?f=It(f):f||r===p||(f=Ft(g,r)),t&&(m=!0,o=n.apply(i,e)),!m||f||u||(e=i=null),o}}function Lr(n){if(!In(n))throw new kt;var r=p(arguments,1);return Ft(function(){n.apply(v,r)},1)}function Pr(n,r){if(!In(n))throw new kt;var t=p(arguments,2);return Ft(function(){n.apply(v,t)},r)}function Kr(n,r){if(!In(n))throw new kt;var t=function(){var e=t.cache,u=r?r.apply(this,arguments):m+arguments[0];return Tt.call(e,u)?e[u]:e[u]=n.apply(this,arguments)};return t.cache={},t}function Ur(n){var r,t;if(!In(n))throw new kt;return function(){return r?t:(r=!0,t=n.apply(this,arguments),n=null,t)}}function Mr(n){return an(n,16,p(arguments,1))}function Vr(n){return an(n,32,null,p(arguments,1))}function Gr(n,r,t){var e=!0,u=!0;if(!In(n))throw new kt;return t===!1?e=!1:Sn(t)&&(e="leading"in t?t.leading:e,u="trailing"in t?t.trailing:u),U.leading=e,U.maxWait=r,U.trailing=u,zr(n,r,U)}function Hr(n,r){return an(r,16,[n])}function Jr(n){return function(){return n}}function Qr(n,r,t){var e=typeof n;if(null==n||"function"==e)return Q(n,r,t);if("object"!=e)return tt(n);var u=ne(n),o=u[0],a=n[o];return 1!=u.length||a!==a||Sn(a)?function(r){for(var t=u.length,e=!1;t--&&(e=rn(r[u[t]],n[u[t]],null,!0)););return e}:function(n){var r=n[o];return a===r&&(0!==a||1/a==1/r)}}function Xr(n){return null==n?"":jt(n).replace(ue,fn)}function Yr(n){return n}function Zr(n,r,t){var e=!0,u=r&&wn(r);r&&(t||u.length)||(null==t&&(t=r),o=g,r=n,n=h,u=wn(r)),t===!1?e=!1:Sn(t)&&"chain"in t&&(e=t.chain);var o=n,a=In(o);Xn(u,function(t){var u=n[t]=r[t];a&&(o.prototype[t]=function(){var r=this.__chain__,t=this.__wrapped__,a=[t];$t.apply(a,arguments);var i=u.apply(n,a);if(e||r){if(t===i&&Sn(i))return this;i=new o(i),i.__chain__=r}return i})})}function nt(){return t._=Ot,this}function rt(){}function tt(n){return function(r){return r[n]}}function et(n,r,t){var e=null==n,u=null==r;if(null==t&&("boolean"==typeof n&&u?(t=n,n=1):u||"boolean"!=typeof r||(t=r,u=!0)),e&&u&&(r=1),n=+n||0,u?(r=n,n=0):r=+r||0,t||n%1||r%1){var o=Ht();return Vt(n+o*(r-n+parseFloat("1e-"+((o+"").length-1))),r)}return en(n,r)}function ut(n,r){if(n){var t=n[r];return In(t)?n[r]():t}}function ot(n,r,t){var e=h.templateSettings;n=jt(n||""),t=ae({},t,e);var u,o=ae({},t.imports,e.imports),i=ne(o),f=Un(o),l=0,c=t.interpolate||E,p="__p += '",s=wt((t.escape||E).source+"|"+c.source+"|"+(c===N?x:E).source+"|"+(t.evaluate||E).source+"|$","g");n.replace(s,function(r,t,e,o,i,f){return e||(e=o),p+=n.slice(l,f).replace(S,a),t&&(p+="' +\n__e("+t+") +\n'"),i&&(u=!0,p+="';\n"+i+";\n__p += '"),e&&(p+="' +\n((__t = ("+e+")) == null ? '' : __t) +\n'"),l=f+r.length,r}),p+="';\n";var g=t.variable,y=g;y||(g="obj",p="with ("+g+") {\n"+p+"\n}\n"),p=(u?p.replace(w,""):p).replace(j,"$1").replace(k,"$1;"),p="function("+g+") {\n"+(y?"":g+" || ("+g+" = {});\n")+"var __t, __p = '', __e = _.escape"+(u?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+p+"return __p\n}";var m="\n/*\n//# sourceURL="+(t.sourceURL||"/lodash/template/source["+D++ +"]")+"\n*/";try{var b=mt(i,"return "+p+m).apply(v,f)}catch(d){throw d.source=p,d}return r?b(r):(b.source=p,b)}function at(n,r,t){n=(n=+n)>-1?n:0;var e=-1,u=ht(n);for(r=Q(r,t,1);++e/g,evaluate:/<%([\s\S]+?)%>/g,interpolate:N,variable:"",imports:{_:h}},zt||(J=function(){function n(){}return function(r){if(Sn(r)){n.prototype=r;var e=new n;n.prototype=null}return e||t.Object()}}());var Xt=qt?function(n,r){M.value=r,qt(n,"__bindData__",M)}:rt,Yt=Lt||function(n){return n&&"object"==typeof n&&"number"==typeof n.length&&Nt.call(n)==$||!1},Zt=function(n){var r,t=n,e=[];if(!t)return e;if(!V[typeof n])return e;for(r in t)Tt.call(t,r)&&e.push(r);return e},ne=Ut?function(n){return Sn(n)?Ut(n):[]}:Zt,re={"&":"&","<":"<",">":">",'"':""","'":"'"},te=kn(re),ee=wt("("+ne(te).join("|")+")","g"),ue=wt("["+ne(re).join("")+"]","g"),oe=function(n,r,t){var e,u=n,o=u;if(!u)return o;var a=arguments,i=0,f="number"==typeof t?2:a.length;if(f>3&&"function"==typeof a[f-2])var l=Q(a[--f-1],a[f--],2);else f>2&&"function"==typeof a[f-1]&&(l=a[--f]);for(;++i/g,R=RegExp("^["+_+"]*0+(?=.$)"),E=/($^)/,I=/\bthis\b/,S=/['\n\r\t\u2028\u2029\\]/g,A=["Array","Boolean","Date","Function","Math","Number","Object","RegExp","String","_","attachEvent","clearTimeout","isFinite","isNaN","parseInt","setTimeout"],D=0,T="[object Arguments]",$="[object Array]",F="[object Boolean]",B="[object Date]",W="[object Function]",q="[object Number]",z="[object Object]",L="[object RegExp]",P="[object String]",K={};K[W]=!1,K[T]=K[$]=K[F]=K[B]=K[q]=K[z]=K[L]=K[P]=!0;var U={leading:!1,maxWait:0,trailing:!1},M={configurable:!1,enumerable:!1,value:null,writable:!1},V={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},G={"\\":"\\","'":"'","\n":"n","\r":"r"," ":"t","\u2028":"u2028","\u2029":"u2029"},H=V[typeof window]&&window||this,J=V[typeof exports]&&exports&&!exports.nodeType&&exports,Q=V[typeof module]&&module&&!module.nodeType&&module,X=Q&&Q.exports===J&&J,Y=V[typeof global]&&global;!Y||Y.global!==Y&&Y.window!==Y||(H=Y);var Z=s();"function"==typeof define&&"object"==typeof define.amd&&define.amd?(H._=Z,define(function(){return Z})):J&&Q?X?(Q.exports=Z)._=Z:J._=Z:H._=Z}).call(this); }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],11:[function(require,module,exports){ var ServiceListModule=require("./components/service-list/service-list.js"),ServiceFormModule=require("./components/service-form/service-form.js"),bambooApp=angular.module("bamboo",[ServiceListModule.name,ServiceFormModule.name]).factory("State",require("./components/resources/state-resource")).factory("Service",require("./components/resources/service-resource")).run(["$templateCache",function(e){e.put("bamboo/modal-confirm",require("./components/modal/modal-confirm.html"))}]);module.exports=bambooApp; },{"./components/modal/modal-confirm.html":12,"./components/resources/service-resource":13,"./components/resources/state-resource":14,"./components/service-form/service-form.js":19,"./components/service-list/service-list.js":26}],12:[function(require,module,exports){ module.exports=''; },{}],13:[function(require,module,exports){ -module.exports=["$resource",function(e){var r=e("/api/services",{},{get:{method:"GET"},create:{method:"POST"}}),t=e("/api/services/:id",{id:"@id"},{update:{method:"PUT",params:{id:"@id"}},destroy:{method:"DELETE",params:{id:"@id"}}}),i=function(e){return e.id=encodeURIComponent(e.id),e};return{all:function(){return r.get().$promise},create:function(e){return r.create(e).$promise},update:function(e){return t.update(i(e)).$promise},destroy:function(e){return t.destroy(i(e)).$promise}}}]; +module.exports=["$resource",function(e){var r=e("/api/services",{},{get:{method:"GET"},create:{method:"POST"}}),t=e("/api/services/:id",{id:"@id"},{update:{method:"PUT",params:{id:"@id"}},destroy:{method:"DELETE",params:{id:"@id"}}});return{all:function(){return r.get().$promise},create:function(e){return r.create(e).$promise},update:function(e){return t.update(e).$promise},destroy:function(e){return t.destroy(e).$promise}}}]; },{}],14:[function(require,module,exports){ module.exports=["$resource",function(e){var r=e("/api/state",{});return{get:function(){return r.get().$promise}}}]; },{}],15:[function(require,module,exports){ module.exports=function(){return{restrict:"AE",template:'',scope:{serviceId:"="},controller:["$scope","Service","$modal","$rootScope",function(e,o,t,n){e.actionName="Delete It!",e.showModal=function(){e.modal=t({title:"Are you sure?",template:"bamboo/modal-confirm",content:"Delete Marathon ID "+e.serviceId,scope:e,show:!0})},e.doAction=function(){o.destroy({id:e.serviceId}).then(function(){e.modal.hide(),e.modal=null,n.$broadcast("services.reset")})}}]}}; },{}],16:[function(require,module,exports){ -module.exports=["Service",function(e){return{restrict:"AE",template:'',scope:{serviceModel:"="},controller:require("./service-form-ctrl.js"),link:function(t){t.actionName="Update",t.disableMarathonIdChange=!0,t.service={id:t.serviceModel.id,acl:t.serviceModel.service.Acl};var o={title:"Edit service configuration",template:"bamboo/modal-confirm",contentTemplate:"bamboo/service-form",scope:t,show:!1,html:!0};t.new=function(){t.showModal(o)},t.makeRequest=function(t){return e.update(t)}}}}]; +module.exports=["Service",function(e){return{restrict:"AE",template:'',scope:{serviceModel:"="},controller:require("./service-form-ctrl.js"),link:function(t){t.actionName="Update",t.disableMarathonIdChange=!0,t.service={id:t.serviceModel.id,acl:t.serviceModel.service.Acl};var o={title:"Edit service configuration",template:"bamboo/modal-confirm",contentTemplate:"bamboo/service-form",scope:t,show:!1,html:!0};t["new"]=function(){t.showModal(o)},t.makeRequest=function(t){return e.update(t)}}}}]; },{"./service-form-ctrl.js":17}],17:[function(require,module,exports){ module.exports=["$scope","$modal","$rootScope",function(o,e,n){o.showModal=function(n){var a;o.modal=a=e(n),a.$promise.then(a.show)},o.loading=!1;var a=function(){o.errors=null},i=function(){o.loading=!1,o.modal.hide(),o.modal=null,n.$broadcast("services.reset")},d=function(e){o.loading=!1,o.errors=e.data};o.doAction=function(){a(),o.loading=!0,o.makeRequest({id:o.service.id,acl:o.service.acl}).then(i,d)}}]; },{}],18:[function(require,module,exports){ @@ -39,7 +39,7 @@ module.exports='
\n
New';return'"},scope:{serviceModel:"=?"},link:function(t){t.actionName="Create",t.service={id:t.serviceModel?t.serviceModel.id||"":"",acl:""};var r={title:"Create new service configuration",template:"bamboo/modal-confirm",contentTemplate:"bamboo/service-form",scope:t,animation:"am-fade-and-scale",show:!1,html:!0};t.new=function(){t.showModal(r)},t.makeRequest=function(t){return e.create(t)}}}}]; +module.exports=["Service",function(e){return{restrict:"AE",controller:require("./service-form-ctrl.js"),template:function(e,t){var r=t.hasOwnProperty("text")?t.text:' New';return'"},scope:{serviceModel:"=?"},link:function(t){t.actionName="Create",t.service={id:t.serviceModel?t.serviceModel.id||"":"",acl:""};var r={title:"Create new service configuration",template:"bamboo/modal-confirm",contentTemplate:"bamboo/service-form",scope:t,animation:"am-fade-and-scale",show:!1,html:!0};t["new"]=function(){t.showModal(r)},t.makeRequest=function(t){return e.create(t)}}}}]; },{"./service-form-ctrl.js":17}],21:[function(require,module,exports){ module.exports=function(){return{restrict:"AE",replace:!0,scope:{serviceModel:"="},controller:["$scope",function(e){e.instancesCount=function(){return e.serviceModel.app?e.serviceModel.app.Tasks.length:"-"}}],template:require("./service-item.html")}}; },{"./service-item.html":22}],22:[function(require,module,exports){