Merge branch 'develop'
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Manu Mtz-Almeida · committed by Manu Mtz-Almeida · parents bd2c864, 66fa43f · Browse files · 69 files·+6043 added−1712 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
69 files+6043 added−1712 removed
- other:+6043 added−1712 removed
Provenance
- Commit
9163ee5- Tree
6be23e4- Author
Manu Mtz-Almeida <manu.valladolid@gmail.com>- Committer
Manu Mtz-Almeida <manu.valladolid@gmail.com>- Parent 1
bd2c864- Parent 2
66fa43f
69 files changed+6043 added−1712 removed
added:binding/binding_test.go+96 added
1+// Copyright 2014 Manu Martinez-Almeida. All rights reserved.2+// Use of this source code is governed by a MIT style3+// license that can be found in the LICENSE file.4+5+package binding6+7+import (8+ "bytes"9+ "net/http"10+ "testing"11+12+ "github.com/stretchr/testify/assert"13+)14+15+type FooStruct struct {16+ Foo string `json:"foo" form:"foo" xml:"foo" binding:"required"`17+}18+19+func TestBindingDefault(t *testing.T) {20+ assert.Equal(t, Default("GET", ""), Form)21+ assert.Equal(t, Default("GET", MIMEJSON), Form)22+23+ assert.Equal(t, Default("POST", MIMEJSON), JSON)24+ assert.Equal(t, Default("PUT", MIMEJSON), JSON)25+26+ assert.Equal(t, Default("POST", MIMEXML), XML)27+ assert.Equal(t, Default("PUT", MIMEXML2), XML)28+29+ assert.Equal(t, Default("POST", MIMEPOSTForm), Form)30+ assert.Equal(t, Default("DELETE", MIMEPOSTForm), Form)31+}32+33+func TestBindingJSON(t *testing.T) {34+ testBodyBinding(t,35+ JSON, "json",36+ "/", "/",37+ `{"foo": "bar"}`, `{"bar": "foo"}`)38+}39+40+func TestBindingForm(t *testing.T) {41+ testFormBinding(t, "POST",42+ "/", "/",43+ "foo=bar", "bar=foo")44+}45+46+func TestBindingForm2(t *testing.T) {47+ testFormBinding(t, "GET",48+ "/?foo=bar", "/?bar=foo",49+ "", "")50+}51+52+func TestBindingXML(t *testing.T) {53+ testBodyBinding(t,54+ XML, "xml",55+ "/", "/",56+ "<map><foo>bar</foo></map>", "<map><bar>foo</bar></map>")57+}58+59+func testFormBinding(t *testing.T, method, path, badPath, body, badBody string) {60+ b := Form61+ assert.Equal(t, b.Name(), "query")62+63+ obj := FooStruct{}64+ req := requestWithBody(method, path, body)65+ if method == "POST" {66+ req.Header.Add("Content-Type", MIMEPOSTForm)67+ }68+ err := b.Bind(req, &obj)69+ assert.NoError(t, err)70+ assert.Equal(t, obj.Foo, "bar")71+72+ obj = FooStruct{}73+ req = requestWithBody(method, badPath, badBody)74+ err = JSON.Bind(req, &obj)75+ assert.Error(t, err)76+}77+78+func testBodyBinding(t *testing.T, b Binding, name, path, badPath, body, badBody string) {79+ assert.Equal(t, b.Name(), name)80+81+ obj := FooStruct{}82+ req := requestWithBody("POST", path, body)83+ err := b.Bind(req, &obj)84+ assert.NoError(t, err)85+ assert.Equal(t, obj.Foo, "bar")86+87+ obj = FooStruct{}88+ req = requestWithBody("POST", badPath, badBody)89+ err = JSON.Bind(req, &obj)90+ assert.Error(t, err)91+}92+93+func requestWithBody(method, path, body string) (req *http.Request) {94+ req, _ = http.NewRequest(method, path, bytes.NewBufferString(body))95+ return96+}modified:binding/binding.go+35 added-256 removed
3 unmodified lines4 5 package binding6 7 import (8- "encoding/json"9- "encoding/xml"10- "errors"8 "net/http"12- "reflect"13- "strconv"14- "strings"15-)9 17-type (18- Binding interface {19- Bind(*http.Request, interface{}) error20- }21-22- // JSON binding23- jsonBinding struct{}24-25- // XML binding26- xmlBinding struct{}27-28- // form binding29- formBinding struct{}30-31- // multipart form binding32- multipartFormBinding struct{}10+ "gopkg.in/bluesuncorp/validator.v5"11 )12 35-const MAX_MEMORY = 1 * 1024 * 102436-37-var (38- JSON = jsonBinding{}39- XML = xmlBinding{}40- Form = formBinding{} // todo41- MultipartForm = multipartFormBinding{}13+const (14+ MIMEJSON = "application/json"15+ MIMEHTML = "text/html"16+ MIMEXML = "application/xml"17+ MIMEXML2 = "text/xml"18+ MIMEPlain = "text/plain"19+ MIMEPOSTForm = "application/x-www-form-urlencoded"20+ MIMEMultipartPOSTForm = "multipart/form-data"21 )22 44-func (_ jsonBinding) Bind(req *http.Request, obj interface{}) error {45- decoder := json.NewDecoder(req.Body)46- if err := decoder.Decode(obj); err == nil {47- return Validate(obj)48- } else {49- return err50- }23+type Binding interface {24+ Name() string25+ Bind(*http.Request, interface{}) error26 }27 53-func (_ xmlBinding) Bind(req *http.Request, obj interface{}) error {54- decoder := xml.NewDecoder(req.Body)55- if err := decoder.Decode(obj); err == nil {56- return Validate(obj)57- } else {58- return err59- }60-}28+var validate = validator.New("binding", validator.BakedInValidators)29 62-func (_ formBinding) Bind(req *http.Request, obj interface{}) error {63- if err := req.ParseForm(); err != nil {64- return err65- }66- if err := mapForm(obj, req.Form); err != nil {67- return err68- }69- return Validate(obj)70-}30+var (31+ JSON = jsonBinding{}32+ XML = xmlBinding{}33+ Form = formBinding{}34+)35 72-func (_ multipartFormBinding) Bind(req *http.Request, obj interface{}) error {73- if err := req.ParseMultipartForm(MAX_MEMORY); err != nil {74- return err75- }76- if err := mapForm(obj, req.Form); err != nil {77- return err78- }79- return Validate(obj)80-}81-82-func mapForm(ptr interface{}, form map[string][]string) error {83- typ := reflect.TypeOf(ptr).Elem()84- formStruct := reflect.ValueOf(ptr).Elem()85- for i := 0; i < typ.NumField(); i++ {86- typeField := typ.Field(i)87- if inputFieldName := typeField.Tag.Get("form"); inputFieldName != "" {88- structField := formStruct.Field(i)89- if !structField.CanSet() {90- continue91- }92-93- inputValue, exists := form[inputFieldName]94- if !exists {95- continue96- }97- numElems := len(inputValue)98- if structField.Kind() == reflect.Slice && numElems > 0 {99- sliceOf := structField.Type().Elem().Kind()100- slice := reflect.MakeSlice(structField.Type(), numElems, numElems)101- for i := 0; i < numElems; i++ {102- if err := setWithProperType(sliceOf, inputValue[i], slice.Index(i)); err != nil {103- return err104- }105- }106- formStruct.Field(i).Set(slice)107- } else {108- if err := setWithProperType(typeField.Type.Kind(), inputValue[0], structField); err != nil {109- return err110- }111- }36+func Default(method, contentType string) Binding {37+ if method == "GET" {38+ return Form39+ } else {40+ switch contentType {41+ case MIMEJSON:42+ return JSON43+ case MIMEXML, MIMEXML2:44+ return XML45+ default:46+ return Form47 }48 }114- return nil49 }50 117-func setIntField(val string, bitSize int, structField reflect.Value) error {118- if val == "" {119- val = "0"51+func ValidateField(f interface{}, tag string) error {52+ if err := validate.Field(f, tag); err != nil {53+ return error(err)54 }121-122- intVal, err := strconv.ParseInt(val, 10, bitSize)123- if err == nil {124- structField.SetInt(intVal)125- }126-127- return err128-}129-130-func setUintField(val string, bitSize int, structField reflect.Value) error {131- if val == "" {132- val = "0"133- }134-135- uintVal, err := strconv.ParseUint(val, 10, bitSize)136- if err == nil {137- structField.SetUint(uintVal)138- }139-140- return err141-}142-143-func setWithProperType(valueKind reflect.Kind, val string, structField reflect.Value) error {144- switch valueKind {145- case reflect.Int:146- return setIntField(val, 0, structField)147- case reflect.Int8:148- return setIntField(val, 8, structField)149- case reflect.Int16:150- return setIntField(val, 16, structField)151- case reflect.Int32:152- return setIntField(val, 32, structField)153- case reflect.Int64:154- return setIntField(val, 64, structField)155- case reflect.Uint:156- return setUintField(val, 0, structField)157- case reflect.Uint8:158- return setUintField(val, 8, structField)159- case reflect.Uint16:160- return setUintField(val, 16, structField)161- case reflect.Uint32:162- return setUintField(val, 32, structField)163- case reflect.Uint64:164- return setUintField(val, 64, structField)165- case reflect.Bool:166- if val == "" {167- val = "false"168- }169- boolVal, err := strconv.ParseBool(val)170- if err != nil {171- return err172- } else {173- structField.SetBool(boolVal)174- }175- case reflect.Float32:176- if val == "" {177- val = "0.0"178- }179- floatVal, err := strconv.ParseFloat(val, 32)180- if err != nil {181- return err182- } else {183- structField.SetFloat(floatVal)184- }185- case reflect.Float64:186- if val == "" {187- val = "0.0"188- }189- floatVal, err := strconv.ParseFloat(val, 64)190- if err != nil {191- return err192- } else {193- structField.SetFloat(floatVal)194- }195- case reflect.String:196- structField.SetString(val)197- }55 return nil56 }57 201-// Don't pass in pointers to bind to. Can lead to bugs. See:202-// https://github.com/codegangsta/martini-contrib/issues/40203-// https://github.com/codegangsta/martini-contrib/pull/34#issuecomment-29683659204-func ensureNotPointer(obj interface{}) {205- if reflect.TypeOf(obj).Kind() == reflect.Ptr {206- panic("Pointers are not accepted as binding models")58+func Validate(obj interface{}) error {59+ if err := validate.Struct(obj); err != nil {60+ return error(err)61 }208-}209-210-func Validate(obj interface{}, parents ...string) error {211- typ := reflect.TypeOf(obj)212- val := reflect.ValueOf(obj)213-214- if typ.Kind() == reflect.Ptr {215- typ = typ.Elem()216- val = val.Elem()217- }218-219- switch typ.Kind() {220- case reflect.Struct:221- for i := 0; i < typ.NumField(); i++ {222- field := typ.Field(i)223-224- // Allow ignored and unexported fields in the struct225- if len(field.PkgPath) > 0 || field.Tag.Get("form") == "-" {226- continue227- }228-229- fieldValue := val.Field(i).Interface()230- zero := reflect.Zero(field.Type).Interface()231-232- if strings.Index(field.Tag.Get("binding"), "required") > -1 {233- fieldType := field.Type.Kind()234- if fieldType == reflect.Struct {235- if reflect.DeepEqual(zero, fieldValue) {236- return errors.New("Required " + field.Name)237- }238- err := Validate(fieldValue, field.Name)239- if err != nil {240- return err241- }242- } else if reflect.DeepEqual(zero, fieldValue) {243- if len(parents) > 0 {244- return errors.New("Required " + field.Name + " on " + parents[0])245- } else {246- return errors.New("Required " + field.Name)247- }248- } else if fieldType == reflect.Slice && field.Type.Elem().Kind() == reflect.Struct {249- err := Validate(fieldValue)250- if err != nil {251- return err252- }253- }254- } else {255- fieldType := field.Type.Kind()256- if fieldType == reflect.Struct {257- if reflect.DeepEqual(zero, fieldValue) {258- continue259- }260- err := Validate(fieldValue, field.Name)261- if err != nil {262- return err263- }264- } else if fieldType == reflect.Slice && field.Type.Elem().Kind() == reflect.Struct {265- err := Validate(fieldValue, field.Name)266- if err != nil {267- return err268- }269- }270- }271- }272- case reflect.Slice:273- for i := 0; i < val.Len(); i++ {274- fieldValue := val.Index(i).Interface()275- err := Validate(fieldValue)276- if err != nil {277- return err278- }279- }280- default:281- return nil282- }62 return nil63 }added:binding/form_mapping.go+139 added
1+// Copyright 2014 Manu Martinez-Almeida. All rights reserved.2+// Use of this source code is governed by a MIT style3+// license that can be found in the LICENSE file.4+5+package binding6+7+import (8+ "errors"9+ "reflect"10+ "strconv"11+)12+13+func mapForm(ptr interface{}, form map[string][]string) error {14+ typ := reflect.TypeOf(ptr).Elem()15+ val := reflect.ValueOf(ptr).Elem()16+ for i := 0; i < typ.NumField(); i++ {17+ typeField := typ.Field(i)18+ structField := val.Field(i)19+ if !structField.CanSet() {20+ continue21+ }22+23+ inputFieldName := typeField.Tag.Get("form")24+ if inputFieldName == "" {25+ inputFieldName = typeField.Name26+ }27+ inputValue, exists := form[inputFieldName]28+ if !exists {29+ continue30+ }31+32+ numElems := len(inputValue)33+ if structField.Kind() == reflect.Slice && numElems > 0 {34+ sliceOf := structField.Type().Elem().Kind()35+ slice := reflect.MakeSlice(structField.Type(), numElems, numElems)36+ for i := 0; i < numElems; i++ {37+ if err := setWithProperType(sliceOf, inputValue[i], slice.Index(i)); err != nil {38+ return err39+ }40+ }41+ val.Field(i).Set(slice)42+ } else {43+ if err := setWithProperType(typeField.Type.Kind(), inputValue[0], structField); err != nil {44+ return err45+ }46+ }47+48+ }49+ return nil50+}51+52+func setWithProperType(valueKind reflect.Kind, val string, structField reflect.Value) error {53+ switch valueKind {54+ case reflect.Int:55+ return setIntField(val, 0, structField)56+ case reflect.Int8:57+ return setIntField(val, 8, structField)58+ case reflect.Int16:59+ return setIntField(val, 16, structField)60+ case reflect.Int32:61+ return setIntField(val, 32, structField)62+ case reflect.Int64:63+ return setIntField(val, 64, structField)64+ case reflect.Uint:65+ return setUintField(val, 0, structField)66+ case reflect.Uint8:67+ return setUintField(val, 8, structField)68+ case reflect.Uint16:69+ return setUintField(val, 16, structField)70+ case reflect.Uint32:71+ return setUintField(val, 32, structField)72+ case reflect.Uint64:73+ return setUintField(val, 64, structField)74+ case reflect.Bool:75+ return setBoolField(val, structField)76+ case reflect.Float32:77+ return setFloatField(val, 32, structField)78+ case reflect.Float64:79+ return setFloatField(val, 64, structField)80+ case reflect.String:81+ structField.SetString(val)82+ default:83+ return errors.New("Unknown type")84+ }85+ return nil86+}87+88+func setIntField(val string, bitSize int, field reflect.Value) error {89+ if val == "" {90+ val = "0"91+ }92+ intVal, err := strconv.ParseInt(val, 10, bitSize)93+ if err == nil {94+ field.SetInt(intVal)95+ }96+ return err97+}98+99+func setUintField(val string, bitSize int, field reflect.Value) error {100+ if val == "" {101+ val = "0"102+ }103+ uintVal, err := strconv.ParseUint(val, 10, bitSize)104+ if err == nil {105+ field.SetUint(uintVal)106+ }107+ return err108+}109+110+func setBoolField(val string, field reflect.Value) error {111+ if val == "" {112+ val = "false"113+ }114+ boolVal, err := strconv.ParseBool(val)115+ if err == nil {116+ field.SetBool(boolVal)117+ }118+ return nil119+}120+121+func setFloatField(val string, bitSize int, field reflect.Value) error {122+ if val == "" {123+ val = "0.0"124+ }125+ floatVal, err := strconv.ParseFloat(val, bitSize)126+ if err == nil {127+ field.SetFloat(floatVal)128+ }129+ return err130+}131+132+// Don't pass in pointers to bind to. Can lead to bugs. See:133+// https://github.com/codegangsta/martini-contrib/issues/40134+// https://github.com/codegangsta/martini-contrib/pull/34#issuecomment-29683659135+func ensureNotPointer(obj interface{}) {136+ if reflect.TypeOf(obj).Kind() == reflect.Ptr {137+ panic("Pointers are not accepted as binding models")138+ }139+}added:binding/form.go+23 added
1+// Copyright 2014 Manu Martinez-Almeida. All rights reserved.2+// Use of this source code is governed by a MIT style3+// license that can be found in the LICENSE file.4+5+package binding6+7+import "net/http"8+9+type formBinding struct{}10+11+func (_ formBinding) Name() string {12+ return "query"13+}14+15+func (_ formBinding) Bind(req *http.Request, obj interface{}) error {16+ if err := req.ParseForm(); err != nil {17+ return err18+ }19+ if err := mapForm(obj, req.Form); err != nil {20+ return err21+ }22+ return Validate(obj)23+}added:binding/json.go+25 added
1+// Copyright 2014 Manu Martinez-Almeida. All rights reserved.2+// Use of this source code is governed by a MIT style3+// license that can be found in the LICENSE file.4+5+package binding6+7+import (8+ "encoding/json"9+10+ "net/http"11+)12+13+type jsonBinding struct{}14+15+func (_ jsonBinding) Name() string {16+ return "json"17+}18+19+func (_ jsonBinding) Bind(req *http.Request, obj interface{}) error {20+ decoder := json.NewDecoder(req.Body)21+ if err := decoder.Decode(obj); err != nil {22+ return err23+ }24+ return Validate(obj)25+}added:binding/validate_test.go+53 added
1+// Copyright 2014 Manu Martinez-Almeida. All rights reserved.2+// Use of this source code is governed by a MIT style3+// license that can be found in the LICENSE file.4+5+package binding6+7+import (8+ "testing"9+10+ "github.com/stretchr/testify/assert"11+)12+13+type struct1 struct {14+ Value float64 `binding:"required"`15+}16+17+type struct2 struct {18+ RequiredValue string `binding:"required"`19+ Value float6420+}21+22+type struct3 struct {23+ Integer int24+ String string25+ BasicSlice []int26+ Boolean bool27+28+ RequiredInteger int `binding:"required"`29+ RequiredString string `binding:"required"`30+ RequiredAnotherStruct struct1 `binding:"required"`31+ RequiredBasicSlice []int `binding:"required"`32+ RequiredComplexSlice []struct2 `binding:"required"`33+ RequiredBoolean bool `binding:"required"`34+}35+36+func createStruct() struct3 {37+ return struct3{38+ RequiredInteger: 2,39+ RequiredString: "hello",40+ RequiredAnotherStruct: struct1{1.5},41+ RequiredBasicSlice: []int{1, 2, 3, 4},42+ RequiredComplexSlice: []struct2{43+ {RequiredValue: "A"},44+ {RequiredValue: "B"},45+ },46+ RequiredBoolean: true,47+ }48+}49+50+func TestValidateGoodObject(t *testing.T) {51+ test := createStruct()52+ assert.Nil(t, Validate(&test))53+}added:binding/xml.go+24 added
1+// Copyright 2014 Manu Martinez-Almeida. All rights reserved.2+// Use of this source code is governed by a MIT style3+// license that can be found in the LICENSE file.4+5+package binding6+7+import (8+ "encoding/xml"9+ "net/http"10+)11+12+type xmlBinding struct{}13+14+func (_ xmlBinding) Name() string {15+ return "xml"16+}17+18+func (_ xmlBinding) Bind(req *http.Request, obj interface{}) error {19+ decoder := xml.NewDecoder(req.Body)20+ if err := decoder.Decode(obj); err != nil {21+ return err22+ }23+ return Validate(obj)24+}added:examples/basic/main.go+56 added
1+package main2+3+import (4+ "github.com/gin-gonic/gin"5+)6+7+var DB = make(map[string]string)8+9+func main() {10+ r := gin.Default()11+12+ // Ping test13+ r.GET("/ping", func(c *gin.Context) {14+ c.String(200, "pong")15+ })16+17+ // Get user value18+ r.GET("/user/:name", func(c *gin.Context) {19+ user := c.Params.ByName("name")20+ value, ok := DB[user]21+ if ok {22+ c.JSON(200, gin.H{"user": user, "value": value})23+ } else {24+ c.JSON(200, gin.H{"user": user, "status": "no value"})25+ }26+ })27+28+ // Authorized group (uses gin.BasicAuth() middleware)29+ // Same than:30+ // authorized := r.Group("/")31+ // authorized.Use(gin.BasicAuth(gin.Credentials{32+ // "foo": "bar",33+ // "manu": "123",34+ //}))35+ authorized := r.Group("/", gin.BasicAuth(gin.Accounts{36+ "foo": "bar", // user:foo password:bar37+ "manu": "123", // user:manu password:12338+ }))39+40+ authorized.POST("admin", func(c *gin.Context) {41+ user := c.MustGet(gin.AuthUserKey).(string)42+43+ // Parse JSON44+ var json struct {45+ Value string `json:"value" binding:"required"`46+ }47+48+ if c.Bind(&json) == nil {49+ DB[user] = json.Value50+ c.JSON(200, gin.H{"status": "ok"})51+ }52+ })53+54+ // Listen and Server in 0.0.0.0:808055+ r.Run(":8080")56+}deleted:examples/pluggable_renderer/example_pongo2.go-58 removed
1-package main2-3-import (4- "github.com/flosch/pongo2"5- "github.com/gin-gonic/gin"6- "net/http"7-)8-9-type pongoRender struct {10- cache map[string]*pongo2.Template11-}12-13-func newPongoRender() *pongoRender {14- return &pongoRender{map[string]*pongo2.Template{}}15-}16-17-func writeHeader(w http.ResponseWriter, code int, contentType string) {18- if code >= 0 {19- w.Header().Set("Content-Type", contentType)20- w.WriteHeader(code)21- }22-}23-24-func (p *pongoRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {25- file := data[0].(string)26- ctx := data[1].(pongo2.Context)27- var t *pongo2.Template28-29- if tmpl, ok := p.cache[file]; ok {30- t = tmpl31- } else {32- tmpl, err := pongo2.FromFile(file)33- if err != nil {34- return err35- }36- p.cache[file] = tmpl37- t = tmpl38- }39- writeHeader(w, code, "text/html")40- return t.ExecuteWriter(ctx, w)41-}42-43-func main() {44- r := gin.Default()45- r.HTMLRender = newPongoRender()46-47- r.GET("/index", func(c *gin.Context) {48- name := c.Request.FormValue("name")49- ctx := pongo2.Context{50- "title": "Gin meets pongo2 !",51- "name": name,52- }53- c.HTML(200, "index.html", ctx)54- })55-56- // Listen and server on 0.0.0.0:808057- r.Run(":8080")58-}deleted:examples/pluggable_renderer/index.html-12 removed
123456789101112<!DOCTYPE html><html lang="ja"> <head> <meta charset="utf-8"> <title>{{ title }}</title> <meta name="keywords" content=""> <meta name="description" content=""> </head> <body> Hello {{ name }} ! </body></html>added:examples/realtime-advanced/resources/static/epoch.min.css+1 added
1+.epoch .axis path,.epoch .axis line{shape-rendering:crispEdges;}.epoch .axis.canvas .tick line{shape-rendering:geometricPrecision;}div#_canvas_css_reference{width:0;height:0;position:absolute;top:-1000px;left:-1000px;}div#_canvas_css_reference svg{position:absolute;width:0;height:0;top:-1000px;left:-1000px;}.epoch{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:12pt;}.epoch .axis path,.epoch .axis line{fill:none;stroke:#000;}.epoch .axis .tick text{font-size:9pt;}.epoch .line{fill:none;stroke-width:2px;}.epoch.sparklines .line{stroke-width:1px;}.epoch .area{stroke:none;}.epoch .arc.pie{stroke:#fff;stroke-width:1.5px;}.epoch .arc.pie text{stroke:none;fill:white;font-size:9pt;}.epoch .gauge-labels .value{text-anchor:middle;font-size:140%;fill:#666;}.epoch.gauge-tiny{width:120px;height:90px;}.epoch.gauge-tiny .gauge-labels .value{font-size:80%;}.epoch.gauge-tiny .gauge .arc.outer{stroke-width:2px;}.epoch.gauge-small{width:180px;height:135px;}.epoch.gauge-small .gauge-labels .value{font-size:120%;}.epoch.gauge-small .gauge .arc.outer{stroke-width:3px;}.epoch.gauge-medium{width:240px;height:180px;}.epoch.gauge-medium .gauge .arc.outer{stroke-width:3px;}.epoch.gauge-large{width:320px;height:240px;}.epoch.gauge-large .gauge-labels .value{font-size:180%;}.epoch .gauge .arc.outer{stroke-width:4px;stroke:#666;}.epoch .gauge .arc.inner{stroke-width:1px;stroke:#555;}.epoch .gauge .tick{stroke-width:1px;stroke:#555;}.epoch .gauge .needle{fill:orange;}.epoch .gauge .needle-base{fill:#666;}.epoch div.ref.category1,.epoch.category10 div.ref.category1{background-color:#1f77b4;}.epoch .category1 .line,.epoch.category10 .category1 .line{stroke:#1f77b4;}.epoch .category1 .area,.epoch .category1 .dot,.epoch.category10 .category1 .area,.epoch.category10 .category1 .dot{fill:#1f77b4;stroke:rgba(0, 0, 0, 0);}.epoch .arc.category1 path,.epoch.category10 .arc.category1 path{fill:#1f77b4;}.epoch .bar.category1,.epoch.category10 .bar.category1{fill:#1f77b4;}.epoch div.ref.category2,.epoch.category10 div.ref.category2{background-color:#ff7f0e;}.epoch .category2 .line,.epoch.category10 .category2 .line{stroke:#ff7f0e;}.epoch .category2 .area,.epoch .category2 .dot,.epoch.category10 .category2 .area,.epoch.category10 .category2 .dot{fill:#ff7f0e;stroke:rgba(0, 0, 0, 0);}.epoch .arc.category2 path,.epoch.category10 .arc.category2 path{fill:#ff7f0e;}.epoch .bar.category2,.epoch.category10 .bar.category2{fill:#ff7f0e;}.epoch div.ref.category3,.epoch.category10 div.ref.category3{background-color:#2ca02c;}.epoch .category3 .line,.epoch.category10 .category3 .line{stroke:#2ca02c;}.epoch .category3 .area,.epoch .category3 .dot,.epoch.category10 .category3 .area,.epoch.category10 .category3 .dot{fill:#2ca02c;stroke:rgba(0, 0, 0, 0);}.epoch .arc.category3 path,.epoch.category10 .arc.category3 path{fill:#2ca02c;}.epoch .bar.category3,.epoch.category10 .bar.category3{fill:#2ca02c;}.epoch div.ref.category4,.epoch.category10 div.ref.category4{background-color:#d62728;}.epoch .category4 .line,.epoch.category10 .category4 .line{stroke:#d62728;}.epoch .category4 .area,.epoch .category4 .dot,.epoch.category10 .category4 .area,.epoch.category10 .category4 .dot{fill:#d62728;stroke:rgba(0, 0, 0, 0);}.epoch .arc.category4 path,.epoch.category10 .arc.category4 path{fill:#d62728;}.epoch .bar.category4,.epoch.category10 .bar.category4{fill:#d62728;}.epoch div.ref.category5,.epoch.category10 div.ref.category5{background-color:#9467bd;}.epoch .category5 .line,.epoch.category10 .category5 .line{stroke:#9467bd;}.epoch .category5 .area,.epoch .category5 .dot,.epoch.category10 .category5 .area,.epoch.category10 .category5 .dot{fill:#9467bd;stroke:rgba(0, 0, 0, 0);}.epoch .arc.category5 path,.epoch.category10 .arc.category5 path{fill:#9467bd;}.epoch .bar.category5,.epoch.category10 .bar.category5{fill:#9467bd;}.epoch div.ref.category6,.epoch.category10 div.ref.category6{background-color:#8c564b;}.epoch .category6 .line,.epoch.category10 .category6 .line{stroke:#8c564b;}.epoch .category6 .area,.epoch .category6 .dot,.epoch.category10 .category6 .area,.epoch.category10 .category6 .dot{fill:#8c564b;stroke:rgba(0, 0, 0, 0);}.epoch .arc.category6 path,.epoch.category10 .arc.category6 path{fill:#8c564b;}.epoch .bar.category6,.epoch.category10 .bar.category6{fill:#8c564b;}.epoch div.ref.category7,.epoch.category10 div.ref.category7{background-color:#e377c2;}.epoch .category7 .line,.epoch.category10 .category7 .line{stroke:#e377c2;}.epoch .category7 .area,.epoch .category7 .dot,.epoch.category10 .category7 .area,.epoch.category10 .category7 .dot{fill:#e377c2;stroke:rgba(0, 0, 0, 0);}.epoch .arc.category7 path,.epoch.category10 .arc.category7 path{fill:#e377c2;}.epoch .bar.category7,.epoch.category10 .bar.category7{fill:#e377c2;}.epoch div.ref.category8,.epoch.category10 div.ref.category8{background-color:#7f7f7f;}.epoch .category8 .line,.epoch.category10 .category8 .line{stroke:#7f7f7f;}.epoch .category8 .area,.epoch .category8 .dot,.epoch.category10 .category8 .area,.epoch.category10 .category8 .dot{fill:#7f7f7f;stroke:rgba(0, 0, 0, 0);}.epoch .arc.category8 path,.epoch.category10 .arc.category8 path{fill:#7f7f7f;}.epoch .bar.category8,.epoch.category10 .bar.category8{fill:#7f7f7f;}.epoch div.ref.category9,.epoch.category10 div.ref.category9{background-color:#bcbd22;}.epoch .category9 .line,.epoch.category10 .category9 .line{stroke:#bcbd22;}.epoch .category9 .area,.epoch .category9 .dot,.epoch.category10 .category9 .area,.epoch.category10 .category9 .dot{fill:#bcbd22;stroke:rgba(0, 0, 0, 0);}.epoch .arc.category9 path,.epoch.category10 .arc.category9 path{fill:#bcbd22;}.epoch .bar.category9,.epoch.category10 .bar.category9{fill:#bcbd22;}.epoch div.ref.category10,.epoch.category10 div.ref.category10{background-color:#17becf;}.epoch .category10 .line,.epoch.category10 .category10 .line{stroke:#17becf;}.epoch .category10 .area,.epoch .category10 .dot,.epoch.category10 .category10 .area,.epoch.category10 .category10 .dot{fill:#17becf;stroke:rgba(0, 0, 0, 0);}.epoch .arc.category10 path,.epoch.category10 .arc.category10 path{fill:#17becf;}.epoch .bar.category10,.epoch.category10 .bar.category10{fill:#17becf;}.epoch.category20 div.ref.category1{background-color:#1f77b4;}.epoch.category20 .category1 .line{stroke:#1f77b4;}.epoch.category20 .category1 .area,.epoch.category20 .category1 .dot{fill:#1f77b4;stroke:rgba(0, 0, 0, 0);}.epoch.category20 .arc.category1 path{fill:#1f77b4;}.epoch.category20 .bar.category1{fill:#1f77b4;}.epoch.category20 div.ref.category2{background-color:#aec7e8;}.epoch.category20 .category2 .line{stroke:#aec7e8;}.epoch.category20 .category2 .area,.epoch.category20 .category2 .dot{fill:#aec7e8;stroke:rgba(0, 0, 0, 0);}.epoch.category20 .arc.category2 path{fill:#aec7e8;}.epoch.category20 .bar.category2{fill:#aec7e8;}.epoch.category20 div.ref.category3{background-color:#ff7f0e;}.epoch.category20 .category3 .line{stroke:#ff7f0e;}.epoch.category20 .category3 .area,.epoch.category20 .category3 .dot{fill:#ff7f0e;stroke:rgba(0, 0, 0, 0);}.epoch.category20 .arc.category3 path{fill:#ff7f0e;}.epoch.category20 .bar.category3{fill:#ff7f0e;}.epoch.category20 div.ref.category4{background-color:#ffbb78;}.epoch.category20 .category4 .line{stroke:#ffbb78;}.epoch.category20 .category4 .area,.epoch.category20 .category4 .dot{fill:#ffbb78;stroke:rgba(0, 0, 0, 0);}.epoch.category20 .arc.category4 path{fill:#ffbb78;}.epoch.category20 .bar.category4{fill:#ffbb78;}.epoch.category20 div.ref.category5{background-color:#2ca02c;}.epoch.category20 .category5 .line{stroke:#2ca02c;}.epoch.category20 .category5 .area,.epoch.category20 .category5 .dot{fill:#2ca02c;stroke:rgba(0, 0, 0, 0);}.epoch.category20 .arc.category5 path{fill:#2ca02c;}.epoch.category20 .bar.category5{fill:#2ca02c;}.epoch.category20 div.ref.category6{background-color:#98df8a;}.epoch.category20 .category6 .line{stroke:#98df8a;}.epoch.category20 .category6 .area,.epoch.category20 .category6 .dot{fill:#98df8a;stroke:rgba(0, 0, 0, 0);}.epoch.category20 .arc.category6 path{fill:#98df8a;}.epoch.category20 .bar.category6{fill:#98df8a;}.epoch.category20 div.ref.category7{background-color:#d62728;}.epoch.category20 .category7 .line{stroke:#d62728;}.epoch.category20 .category7 .area,.epoch.category20 .category7 .dot{fill:#d62728;stroke:rgba(0, 0, 0, 0);}.epoch.category20 .arc.category7 path{fill:#d62728;}.epoch.category20 .bar.category7{fill:#d62728;}.epoch.category20 div.ref.category8{background-color:#ff9896;}.epoch.category20 .category8 .line{stroke:#ff9896;}.epoch.category20 .category8 .area,.epoch.category20 .category8 .dot{fill:#ff9896;stroke:rgba(0, 0, 0, 0);}.epoch.category20 .arc.category8 path{fill:#ff9896;}.epoch.category20 .bar.category8{fill:#ff9896;}.epoch.category20 div.ref.category9{background-color:#9467bd;}.epoch.category20 .category9 .line{stroke:#9467bd;}.epoch.category20 .category9 .area,.epoch.category20 .category9 .dot{fill:#9467bd;stroke:rgba(0, 0, 0, 0);}.epoch.category20 .arc.category9 path{fill:#9467bd;}.epoch.category20 .bar.category9{fill:#9467bd;}.epoch.category20 div.ref.category10{background-color:#c5b0d5;}.epoch.category20 .category10 .line{stroke:#c5b0d5;}.epoch.category20 .category10 .area,.epoch.category20 .category10 .dot{fill:#c5b0d5;stroke:rgba(0, 0, 0, 0);}.epoch.category20 .arc.category10 path{fill:#c5b0d5;}.epoch.category20 .bar.category10{fill:#c5b0d5;}.epoch.category20 div.ref.category11{background-color:#8c564b;}.epoch.category20 .category11 .line{stroke:#8c564b;}.epoch.category20 .category11 .area,.epoch.category20 .category11 .dot{fill:#8c564b;stroke:rgba(0, 0, 0, 0);}.epoch.category20 .arc.category11 path{fill:#8c564b;}.epoch.category20 .bar.category11{fill:#8c564b;}.epoch.category20 div.ref.category12{background-color:#c49c94;}.epoch.category20 .category12 .line{stroke:#c49c94;}.epoch.category20 .category12 .area,.epoch.category20 .category12 .dot{fill:#c49c94;stroke:rgba(0, 0, 0, 0);}.epoch.category20 .arc.category12 path{fill:#c49c94;}.epoch.category20 .bar.category12{fill:#c49c94;}.epoch.category20 div.ref.category13{background-color:#e377c2;}.epoch.category20 .category13 .line{stroke:#e377c2;}.epoch.category20 .category13 .area,.epoch.category20 .category13 .dot{fill:#e377c2;stroke:rgba(0, 0, 0, 0);}.epoch.category20 .arc.category13 path{fill:#e377c2;}.epoch.category20 .bar.category13{fill:#e377c2;}.epoch.category20 div.ref.category14{background-color:#f7b6d2;}.epoch.category20 .category14 .line{stroke:#f7b6d2;}.epoch.category20 .category14 .area,.epoch.category20 .category14 .dot{fill:#f7b6d2;stroke:rgba(0, 0, 0, 0);}.epoch.category20 .arc.category14 path{fill:#f7b6d2;}.epoch.category20 .bar.category14{fill:#f7b6d2;}.epoch.category20 div.ref.category15{background-color:#7f7f7f;}.epoch.category20 .category15 .line{stroke:#7f7f7f;}.epoch.category20 .category15 .area,.epoch.category20 .category15 .dot{fill:#7f7f7f;stroke:rgba(0, 0, 0, 0);}.epoch.category20 .arc.category15 path{fill:#7f7f7f;}.epoch.category20 .bar.category15{fill:#7f7f7f;}.epoch.category20 div.ref.category16{background-color:#c7c7c7;}.epoch.category20 .category16 .line{stroke:#c7c7c7;}.epoch.category20 .category16 .area,.epoch.category20 .category16 .dot{fill:#c7c7c7;stroke:rgba(0, 0, 0, 0);}.epoch.category20 .arc.category16 path{fill:#c7c7c7;}.epoch.category20 .bar.category16{fill:#c7c7c7;}.epoch.category20 div.ref.category17{background-color:#bcbd22;}.epoch.category20 .category17 .line{stroke:#bcbd22;}.epoch.category20 .category17 .area,.epoch.category20 .category17 .dot{fill:#bcbd22;stroke:rgba(0, 0, 0, 0);}.epoch.category20 .arc.category17 path{fill:#bcbd22;}.epoch.category20 .bar.category17{fill:#bcbd22;}.epoch.category20 div.ref.category18{background-color:#dbdb8d;}.epoch.category20 .category18 .line{stroke:#dbdb8d;}.epoch.category20 .category18 .area,.epoch.category20 .category18 .dot{fill:#dbdb8d;stroke:rgba(0, 0, 0, 0);}.epoch.category20 .arc.category18 path{fill:#dbdb8d;}.epoch.category20 .bar.category18{fill:#dbdb8d;}.epoch.category20 div.ref.category19{background-color:#17becf;}.epoch.category20 .category19 .line{stroke:#17becf;}.epoch.category20 .category19 .area,.epoch.category20 .category19 .dot{fill:#17becf;stroke:rgba(0, 0, 0, 0);}.epoch.category20 .arc.category19 path{fill:#17becf;}.epoch.category20 .bar.category19{fill:#17becf;}.epoch.category20 div.ref.category20{background-color:#9edae5;}.epoch.category20 .category20 .line{stroke:#9edae5;}.epoch.category20 .category20 .area,.epoch.category20 .category20 .dot{fill:#9edae5;stroke:rgba(0, 0, 0, 0);}.epoch.category20 .arc.category20 path{fill:#9edae5;}.epoch.category20 .bar.category20{fill:#9edae5;}.epoch.category20b div.ref.category1{background-color:#393b79;}.epoch.category20b .category1 .line{stroke:#393b79;}.epoch.category20b .category1 .area,.epoch.category20b .category1 .dot{fill:#393b79;stroke:rgba(0, 0, 0, 0);}.epoch.category20b .arc.category1 path{fill:#393b79;}.epoch.category20b .bar.category1{fill:#393b79;}.epoch.category20b div.ref.category2{background-color:#5254a3;}.epoch.category20b .category2 .line{stroke:#5254a3;}.epoch.category20b .category2 .area,.epoch.category20b .category2 .dot{fill:#5254a3;stroke:rgba(0, 0, 0, 0);}.epoch.category20b .arc.category2 path{fill:#5254a3;}.epoch.category20b .bar.category2{fill:#5254a3;}.epoch.category20b div.ref.category3{background-color:#6b6ecf;}.epoch.category20b .category3 .line{stroke:#6b6ecf;}.epoch.category20b .category3 .area,.epoch.category20b .category3 .dot{fill:#6b6ecf;stroke:rgba(0, 0, 0, 0);}.epoch.category20b .arc.category3 path{fill:#6b6ecf;}.epoch.category20b .bar.category3{fill:#6b6ecf;}.epoch.category20b div.ref.category4{background-color:#9c9ede;}.epoch.category20b .category4 .line{stroke:#9c9ede;}.epoch.category20b .category4 .area,.epoch.category20b .category4 .dot{fill:#9c9ede;stroke:rgba(0, 0, 0, 0);}.epoch.category20b .arc.category4 path{fill:#9c9ede;}.epoch.category20b .bar.category4{fill:#9c9ede;}.epoch.category20b div.ref.category5{background-color:#637939;}.epoch.category20b .category5 .line{stroke:#637939;}.epoch.category20b .category5 .area,.epoch.category20b .category5 .dot{fill:#637939;stroke:rgba(0, 0, 0, 0);}.epoch.category20b .arc.category5 path{fill:#637939;}.epoch.category20b .bar.category5{fill:#637939;}.epoch.category20b div.ref.category6{background-color:#8ca252;}.epoch.category20b .category6 .line{stroke:#8ca252;}.epoch.category20b .category6 .area,.epoch.category20b .category6 .dot{fill:#8ca252;stroke:rgba(0, 0, 0, 0);}.epoch.category20b .arc.category6 path{fill:#8ca252;}.epoch.category20b .bar.category6{fill:#8ca252;}.epoch.category20b div.ref.category7{background-color:#b5cf6b;}.epoch.category20b .category7 .line{stroke:#b5cf6b;}.epoch.category20b .category7 .area,.epoch.category20b .category7 .dot{fill:#b5cf6b;stroke:rgba(0, 0, 0, 0);}.epoch.category20b .arc.category7 path{fill:#b5cf6b;}.epoch.category20b .bar.category7{fill:#b5cf6b;}.epoch.category20b div.ref.category8{background-color:#cedb9c;}.epoch.category20b .category8 .line{stroke:#cedb9c;}.epoch.category20b .category8 .area,.epoch.category20b .category8 .dot{fill:#cedb9c;stroke:rgba(0, 0, 0, 0);}.epoch.category20b .arc.category8 path{fill:#cedb9c;}.epoch.category20b .bar.category8{fill:#cedb9c;}.epoch.category20b div.ref.category9{background-color:#8c6d31;}.epoch.category20b .category9 .line{stroke:#8c6d31;}.epoch.category20b .category9 .area,.epoch.category20b .category9 .dot{fill:#8c6d31;stroke:rgba(0, 0, 0, 0);}.epoch.category20b .arc.category9 path{fill:#8c6d31;}.epoch.category20b .bar.category9{fill:#8c6d31;}.epoch.category20b div.ref.category10{background-color:#bd9e39;}.epoch.category20b .category10 .line{stroke:#bd9e39;}.epoch.category20b .category10 .area,.epoch.category20b .category10 .dot{fill:#bd9e39;stroke:rgba(0, 0, 0, 0);}.epoch.category20b .arc.category10 path{fill:#bd9e39;}.epoch.category20b .bar.category10{fill:#bd9e39;}.epoch.category20b div.ref.category11{background-color:#e7ba52;}.epoch.category20b .category11 .line{stroke:#e7ba52;}.epoch.category20b .category11 .area,.epoch.category20b .category11 .dot{fill:#e7ba52;stroke:rgba(0, 0, 0, 0);}.epoch.category20b .arc.category11 path{fill:#e7ba52;}.epoch.category20b .bar.category11{fill:#e7ba52;}.epoch.category20b div.ref.category12{background-color:#e7cb94;}.epoch.category20b .category12 .line{stroke:#e7cb94;}.epoch.category20b .category12 .area,.epoch.category20b .category12 .dot{fill:#e7cb94;stroke:rgba(0, 0, 0, 0);}.epoch.category20b .arc.category12 path{fill:#e7cb94;}.epoch.category20b .bar.category12{fill:#e7cb94;}.epoch.category20b div.ref.category13{background-color:#843c39;}.epoch.category20b .category13 .line{stroke:#843c39;}.epoch.category20b .category13 .area,.epoch.category20b .category13 .dot{fill:#843c39;stroke:rgba(0, 0, 0, 0);}.epoch.category20b .arc.category13 path{fill:#843c39;}.epoch.category20b .bar.category13{fill:#843c39;}.epoch.category20b div.ref.category14{background-color:#ad494a;}.epoch.category20b .category14 .line{stroke:#ad494a;}.epoch.category20b .category14 .area,.epoch.category20b .category14 .dot{fill:#ad494a;stroke:rgba(0, 0, 0, 0);}.epoch.category20b .arc.category14 path{fill:#ad494a;}.epoch.category20b .bar.category14{fill:#ad494a;}.epoch.category20b div.ref.category15{background-color:#d6616b;}.epoch.category20b .category15 .line{stroke:#d6616b;}.epoch.category20b .category15 .area,.epoch.category20b .category15 .dot{fill:#d6616b;stroke:rgba(0, 0, 0, 0);}.epoch.category20b .arc.category15 path{fill:#d6616b;}.epoch.category20b .bar.category15{fill:#d6616b;}.epoch.category20b div.ref.category16{background-color:#e7969c;}.epoch.category20b .category16 .line{stroke:#e7969c;}.epoch.category20b .category16 .area,.epoch.category20b .category16 .dot{fill:#e7969c;stroke:rgba(0, 0, 0, 0);}.epoch.category20b .arc.category16 path{fill:#e7969c;}.epoch.category20b .bar.category16{fill:#e7969c;}.epoch.category20b div.ref.category17{background-color:#7b4173;}.epoch.category20b .category17 .line{stroke:#7b4173;}.epoch.category20b .category17 .area,.epoch.category20b .category17 .dot{fill:#7b4173;stroke:rgba(0, 0, 0, 0);}.epoch.category20b .arc.category17 path{fill:#7b4173;}.epoch.category20b .bar.category17{fill:#7b4173;}.epoch.category20b div.ref.category18{background-color:#a55194;}.epoch.category20b .category18 .line{stroke:#a55194;}.epoch.category20b .category18 .area,.epoch.category20b .category18 .dot{fill:#a55194;stroke:rgba(0, 0, 0, 0);}.epoch.category20b .arc.category18 path{fill:#a55194;}.epoch.category20b .bar.category18{fill:#a55194;}.epoch.category20b div.ref.category19{background-color:#ce6dbd;}.epoch.category20b .category19 .line{stroke:#ce6dbd;}.epoch.category20b .category19 .area,.epoch.category20b .category19 .dot{fill:#ce6dbd;stroke:rgba(0, 0, 0, 0);}.epoch.category20b .arc.category19 path{fill:#ce6dbd;}.epoch.category20b .bar.category19{fill:#ce6dbd;}.epoch.category20b div.ref.category20{background-color:#de9ed6;}.epoch.category20b .category20 .line{stroke:#de9ed6;}.epoch.category20b .category20 .area,.epoch.category20b .category20 .dot{fill:#de9ed6;stroke:rgba(0, 0, 0, 0);}.epoch.category20b .arc.category20 path{fill:#de9ed6;}.epoch.category20b .bar.category20{fill:#de9ed6;}.epoch.category20c div.ref.category1{background-color:#3182bd;}.epoch.category20c .category1 .line{stroke:#3182bd;}.epoch.category20c .category1 .area,.epoch.category20c .category1 .dot{fill:#3182bd;stroke:rgba(0, 0, 0, 0);}.epoch.category20c .arc.category1 path{fill:#3182bd;}.epoch.category20c .bar.category1{fill:#3182bd;}.epoch.category20c div.ref.category2{background-color:#6baed6;}.epoch.category20c .category2 .line{stroke:#6baed6;}.epoch.category20c .category2 .area,.epoch.category20c .category2 .dot{fill:#6baed6;stroke:rgba(0, 0, 0, 0);}.epoch.category20c .arc.category2 path{fill:#6baed6;}.epoch.category20c .bar.category2{fill:#6baed6;}.epoch.category20c div.ref.category3{background-color:#9ecae1;}.epoch.category20c .category3 .line{stroke:#9ecae1;}.epoch.category20c .category3 .area,.epoch.category20c .category3 .dot{fill:#9ecae1;stroke:rgba(0, 0, 0, 0);}.epoch.category20c .arc.category3 path{fill:#9ecae1;}.epoch.category20c .bar.category3{fill:#9ecae1;}.epoch.category20c div.ref.category4{background-color:#c6dbef;}.epoch.category20c .category4 .line{stroke:#c6dbef;}.epoch.category20c .category4 .area,.epoch.category20c .category4 .dot{fill:#c6dbef;stroke:rgba(0, 0, 0, 0);}.epoch.category20c .arc.category4 path{fill:#c6dbef;}.epoch.category20c .bar.category4{fill:#c6dbef;}.epoch.category20c div.ref.category5{background-color:#e6550d;}.epoch.category20c .category5 .line{stroke:#e6550d;}.epoch.category20c .category5 .area,.epoch.category20c .category5 .dot{fill:#e6550d;stroke:rgba(0, 0, 0, 0);}.epoch.category20c .arc.category5 path{fill:#e6550d;}.epoch.category20c .bar.category5{fill:#e6550d;}.epoch.category20c div.ref.category6{background-color:#fd8d3c;}.epoch.category20c .category6 .line{stroke:#fd8d3c;}.epoch.category20c .category6 .area,.epoch.category20c .category6 .dot{fill:#fd8d3c;stroke:rgba(0, 0, 0, 0);}.epoch.category20c .arc.category6 path{fill:#fd8d3c;}.epoch.category20c .bar.category6{fill:#fd8d3c;}.epoch.category20c div.ref.category7{background-color:#fdae6b;}.epoch.category20c .category7 .line{stroke:#fdae6b;}.epoch.category20c .category7 .area,.epoch.category20c .category7 .dot{fill:#fdae6b;stroke:rgba(0, 0, 0, 0);}.epoch.category20c .arc.category7 path{fill:#fdae6b;}.epoch.category20c .bar.category7{fill:#fdae6b;}.epoch.category20c div.ref.category8{background-color:#fdd0a2;}.epoch.category20c .category8 .line{stroke:#fdd0a2;}.epoch.category20c .category8 .area,.epoch.category20c .category8 .dot{fill:#fdd0a2;stroke:rgba(0, 0, 0, 0);}.epoch.category20c .arc.category8 path{fill:#fdd0a2;}.epoch.category20c .bar.category8{fill:#fdd0a2;}.epoch.category20c div.ref.category9{background-color:#31a354;}.epoch.category20c .category9 .line{stroke:#31a354;}.epoch.category20c .category9 .area,.epoch.category20c .category9 .dot{fill:#31a354;stroke:rgba(0, 0, 0, 0);}.epoch.category20c .arc.category9 path{fill:#31a354;}.epoch.category20c .bar.category9{fill:#31a354;}.epoch.category20c div.ref.category10{background-color:#74c476;}.epoch.category20c .category10 .line{stroke:#74c476;}.epoch.category20c .category10 .area,.epoch.category20c .category10 .dot{fill:#74c476;stroke:rgba(0, 0, 0, 0);}.epoch.category20c .arc.category10 path{fill:#74c476;}.epoch.category20c .bar.category10{fill:#74c476;}.epoch.category20c div.ref.category11{background-color:#a1d99b;}.epoch.category20c .category11 .line{stroke:#a1d99b;}.epoch.category20c .category11 .area,.epoch.category20c .category11 .dot{fill:#a1d99b;stroke:rgba(0, 0, 0, 0);}.epoch.category20c .arc.category11 path{fill:#a1d99b;}.epoch.category20c .bar.category11{fill:#a1d99b;}.epoch.category20c div.ref.category12{background-color:#c7e9c0;}.epoch.category20c .category12 .line{stroke:#c7e9c0;}.epoch.category20c .category12 .area,.epoch.category20c .category12 .dot{fill:#c7e9c0;stroke:rgba(0, 0, 0, 0);}.epoch.category20c .arc.category12 path{fill:#c7e9c0;}.epoch.category20c .bar.category12{fill:#c7e9c0;}.epoch.category20c div.ref.category13{background-color:#756bb1;}.epoch.category20c .category13 .line{stroke:#756bb1;}.epoch.category20c .category13 .area,.epoch.category20c .category13 .dot{fill:#756bb1;stroke:rgba(0, 0, 0, 0);}.epoch.category20c .arc.category13 path{fill:#756bb1;}.epoch.category20c .bar.category13{fill:#756bb1;}.epoch.category20c div.ref.category14{background-color:#9e9ac8;}.epoch.category20c .category14 .line{stroke:#9e9ac8;}.epoch.category20c .category14 .area,.epoch.category20c .category14 .dot{fill:#9e9ac8;stroke:rgba(0, 0, 0, 0);}.epoch.category20c .arc.category14 path{fill:#9e9ac8;}.epoch.category20c .bar.category14{fill:#9e9ac8;}.epoch.category20c div.ref.category15{background-color:#bcbddc;}.epoch.category20c .category15 .line{stroke:#bcbddc;}.epoch.category20c .category15 .area,.epoch.category20c .category15 .dot{fill:#bcbddc;stroke:rgba(0, 0, 0, 0);}.epoch.category20c .arc.category15 path{fill:#bcbddc;}.epoch.category20c .bar.category15{fill:#bcbddc;}.epoch.category20c div.ref.category16{background-color:#dadaeb;}.epoch.category20c .category16 .line{stroke:#dadaeb;}.epoch.category20c .category16 .area,.epoch.category20c .category16 .dot{fill:#dadaeb;stroke:rgba(0, 0, 0, 0);}.epoch.category20c .arc.category16 path{fill:#dadaeb;}.epoch.category20c .bar.category16{fill:#dadaeb;}.epoch.category20c div.ref.category17{background-color:#636363;}.epoch.category20c .category17 .line{stroke:#636363;}.epoch.category20c .category17 .area,.epoch.category20c .category17 .dot{fill:#636363;stroke:rgba(0, 0, 0, 0);}.epoch.category20c .arc.category17 path{fill:#636363;}.epoch.category20c .bar.category17{fill:#636363;}.epoch.category20c div.ref.category18{background-color:#969696;}.epoch.category20c .category18 .line{stroke:#969696;}.epoch.category20c .category18 .area,.epoch.category20c .category18 .dot{fill:#969696;stroke:rgba(0, 0, 0, 0);}.epoch.category20c .arc.category18 path{fill:#969696;}.epoch.category20c .bar.category18{fill:#969696;}.epoch.category20c div.ref.category19{background-color:#bdbdbd;}.epoch.category20c .category19 .line{stroke:#bdbdbd;}.epoch.category20c .category19 .area,.epoch.category20c .category19 .dot{fill:#bdbdbd;stroke:rgba(0, 0, 0, 0);}.epoch.category20c .arc.category19 path{fill:#bdbdbd;}.epoch.category20c .bar.category19{fill:#bdbdbd;}.epoch.category20c div.ref.category20{background-color:#d9d9d9;}.epoch.category20c .category20 .line{stroke:#d9d9d9;}.epoch.category20c .category20 .area,.epoch.category20c .category20 .dot{fill:#d9d9d9;stroke:rgba(0, 0, 0, 0);}.epoch.category20c .arc.category20 path{fill:#d9d9d9;}.epoch.category20c .bar.category20{fill:#d9d9d9;}.epoch .category1 .bucket,.epoch.heatmap5 .category1 .bucket{fill:#1f77b4;}.epoch .category2 .bucket,.epoch.heatmap5 .category2 .bucket{fill:#2ca02c;}.epoch .category3 .bucket,.epoch.heatmap5 .category3 .bucket{fill:#d62728;}.epoch .category4 .bucket,.epoch.heatmap5 .category4 .bucket{fill:#8c564b;}.epoch .category5 .bucket,.epoch.heatmap5 .category5 .bucket{fill:#7f7f7f;}.epoch-theme-dark .epoch .axis path,.epoch-theme-dark .epoch .axis line{stroke:#d0d0d0;}.epoch-theme-dark .epoch .axis .tick text{fill:#d0d0d0;}.epoch-theme-dark .arc.pie{stroke:#333;}.epoch-theme-dark .arc.pie text{fill:#333;}.epoch-theme-dark .epoch .gauge-labels .value{fill:#BBB;}.epoch-theme-dark .epoch .gauge .arc.outer{stroke:#999;}.epoch-theme-dark .epoch .gauge .arc.inner{stroke:#AAA;}.epoch-theme-dark .epoch .gauge .tick{stroke:#AAA;}.epoch-theme-dark .epoch .gauge .needle{fill:#F3DE88;}.epoch-theme-dark .epoch .gauge .needle-base{fill:#999;}.epoch-theme-dark .epoch div.ref.category1,.epoch-theme-dark .epoch.category10 div.ref.category1{background-color:#909CFF;}.epoch-theme-dark .epoch .category1 .line,.epoch-theme-dark .epoch.category10 .category1 .line{stroke:#909CFF;}.epoch-theme-dark .epoch .category1 .area,.epoch-theme-dark .epoch .category1 .dot,.epoch-theme-dark .epoch.category10 .category1 .area,.epoch-theme-dark .epoch.category10 .category1 .dot{fill:#909CFF;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch .arc.category1 path,.epoch-theme-dark .epoch.category10 .arc.category1 path{fill:#909CFF;}.epoch-theme-dark .epoch .bar.category1,.epoch-theme-dark .epoch.category10 .bar.category1{fill:#909CFF;}.epoch-theme-dark .epoch div.ref.category2,.epoch-theme-dark .epoch.category10 div.ref.category2{background-color:#FFAC89;}.epoch-theme-dark .epoch .category2 .line,.epoch-theme-dark .epoch.category10 .category2 .line{stroke:#FFAC89;}.epoch-theme-dark .epoch .category2 .area,.epoch-theme-dark .epoch .category2 .dot,.epoch-theme-dark .epoch.category10 .category2 .area,.epoch-theme-dark .epoch.category10 .category2 .dot{fill:#FFAC89;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch .arc.category2 path,.epoch-theme-dark .epoch.category10 .arc.category2 path{fill:#FFAC89;}.epoch-theme-dark .epoch .bar.category2,.epoch-theme-dark .epoch.category10 .bar.category2{fill:#FFAC89;}.epoch-theme-dark .epoch div.ref.category3,.epoch-theme-dark .epoch.category10 div.ref.category3{background-color:#E889E8;}.epoch-theme-dark .epoch .category3 .line,.epoch-theme-dark .epoch.category10 .category3 .line{stroke:#E889E8;}.epoch-theme-dark .epoch .category3 .area,.epoch-theme-dark .epoch .category3 .dot,.epoch-theme-dark .epoch.category10 .category3 .area,.epoch-theme-dark .epoch.category10 .category3 .dot{fill:#E889E8;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch .arc.category3 path,.epoch-theme-dark .epoch.category10 .arc.category3 path{fill:#E889E8;}.epoch-theme-dark .epoch .bar.category3,.epoch-theme-dark .epoch.category10 .bar.category3{fill:#E889E8;}.epoch-theme-dark .epoch div.ref.category4,.epoch-theme-dark .epoch.category10 div.ref.category4{background-color:#78E8D3;}.epoch-theme-dark .epoch .category4 .line,.epoch-theme-dark .epoch.category10 .category4 .line{stroke:#78E8D3;}.epoch-theme-dark .epoch .category4 .area,.epoch-theme-dark .epoch .category4 .dot,.epoch-theme-dark .epoch.category10 .category4 .area,.epoch-theme-dark .epoch.category10 .category4 .dot{fill:#78E8D3;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch .arc.category4 path,.epoch-theme-dark .epoch.category10 .arc.category4 path{fill:#78E8D3;}.epoch-theme-dark .epoch .bar.category4,.epoch-theme-dark .epoch.category10 .bar.category4{fill:#78E8D3;}.epoch-theme-dark .epoch div.ref.category5,.epoch-theme-dark .epoch.category10 div.ref.category5{background-color:#C2FF97;}.epoch-theme-dark .epoch .category5 .line,.epoch-theme-dark .epoch.category10 .category5 .line{stroke:#C2FF97;}.epoch-theme-dark .epoch .category5 .area,.epoch-theme-dark .epoch .category5 .dot,.epoch-theme-dark .epoch.category10 .category5 .area,.epoch-theme-dark .epoch.category10 .category5 .dot{fill:#C2FF97;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch .arc.category5 path,.epoch-theme-dark .epoch.category10 .arc.category5 path{fill:#C2FF97;}.epoch-theme-dark .epoch .bar.category5,.epoch-theme-dark .epoch.category10 .bar.category5{fill:#C2FF97;}.epoch-theme-dark .epoch div.ref.category6,.epoch-theme-dark .epoch.category10 div.ref.category6{background-color:#B7BCD1;}.epoch-theme-dark .epoch .category6 .line,.epoch-theme-dark .epoch.category10 .category6 .line{stroke:#B7BCD1;}.epoch-theme-dark .epoch .category6 .area,.epoch-theme-dark .epoch .category6 .dot,.epoch-theme-dark .epoch.category10 .category6 .area,.epoch-theme-dark .epoch.category10 .category6 .dot{fill:#B7BCD1;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch .arc.category6 path,.epoch-theme-dark .epoch.category10 .arc.category6 path{fill:#B7BCD1;}.epoch-theme-dark .epoch .bar.category6,.epoch-theme-dark .epoch.category10 .bar.category6{fill:#B7BCD1;}.epoch-theme-dark .epoch div.ref.category7,.epoch-theme-dark .epoch.category10 div.ref.category7{background-color:#FF857F;}.epoch-theme-dark .epoch .category7 .line,.epoch-theme-dark .epoch.category10 .category7 .line{stroke:#FF857F;}.epoch-theme-dark .epoch .category7 .area,.epoch-theme-dark .epoch .category7 .dot,.epoch-theme-dark .epoch.category10 .category7 .area,.epoch-theme-dark .epoch.category10 .category7 .dot{fill:#FF857F;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch .arc.category7 path,.epoch-theme-dark .epoch.category10 .arc.category7 path{fill:#FF857F;}.epoch-theme-dark .epoch .bar.category7,.epoch-theme-dark .epoch.category10 .bar.category7{fill:#FF857F;}.epoch-theme-dark .epoch div.ref.category8,.epoch-theme-dark .epoch.category10 div.ref.category8{background-color:#F3DE88;}.epoch-theme-dark .epoch .category8 .line,.epoch-theme-dark .epoch.category10 .category8 .line{stroke:#F3DE88;}.epoch-theme-dark .epoch .category8 .area,.epoch-theme-dark .epoch .category8 .dot,.epoch-theme-dark .epoch.category10 .category8 .area,.epoch-theme-dark .epoch.category10 .category8 .dot{fill:#F3DE88;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch .arc.category8 path,.epoch-theme-dark .epoch.category10 .arc.category8 path{fill:#F3DE88;}.epoch-theme-dark .epoch .bar.category8,.epoch-theme-dark .epoch.category10 .bar.category8{fill:#F3DE88;}.epoch-theme-dark .epoch div.ref.category9,.epoch-theme-dark .epoch.category10 div.ref.category9{background-color:#C9935E;}.epoch-theme-dark .epoch .category9 .line,.epoch-theme-dark .epoch.category10 .category9 .line{stroke:#C9935E;}.epoch-theme-dark .epoch .category9 .area,.epoch-theme-dark .epoch .category9 .dot,.epoch-theme-dark .epoch.category10 .category9 .area,.epoch-theme-dark .epoch.category10 .category9 .dot{fill:#C9935E;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch .arc.category9 path,.epoch-theme-dark .epoch.category10 .arc.category9 path{fill:#C9935E;}.epoch-theme-dark .epoch .bar.category9,.epoch-theme-dark .epoch.category10 .bar.category9{fill:#C9935E;}.epoch-theme-dark .epoch div.ref.category10,.epoch-theme-dark .epoch.category10 div.ref.category10{background-color:#A488FF;}.epoch-theme-dark .epoch .category10 .line,.epoch-theme-dark .epoch.category10 .category10 .line{stroke:#A488FF;}.epoch-theme-dark .epoch .category10 .area,.epoch-theme-dark .epoch .category10 .dot,.epoch-theme-dark .epoch.category10 .category10 .area,.epoch-theme-dark .epoch.category10 .category10 .dot{fill:#A488FF;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch .arc.category10 path,.epoch-theme-dark .epoch.category10 .arc.category10 path{fill:#A488FF;}.epoch-theme-dark .epoch .bar.category10,.epoch-theme-dark .epoch.category10 .bar.category10{fill:#A488FF;}.epoch-theme-dark .epoch.category20 div.ref.category1{background-color:#909CFF;}.epoch-theme-dark .epoch.category20 .category1 .line{stroke:#909CFF;}.epoch-theme-dark .epoch.category20 .category1 .area,.epoch-theme-dark .epoch.category20 .category1 .dot{fill:#909CFF;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20 .arc.category1 path{fill:#909CFF;}.epoch-theme-dark .epoch.category20 .bar.category1{fill:#909CFF;}.epoch-theme-dark .epoch.category20 div.ref.category2{background-color:#626AAD;}.epoch-theme-dark .epoch.category20 .category2 .line{stroke:#626AAD;}.epoch-theme-dark .epoch.category20 .category2 .area,.epoch-theme-dark .epoch.category20 .category2 .dot{fill:#626AAD;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20 .arc.category2 path{fill:#626AAD;}.epoch-theme-dark .epoch.category20 .bar.category2{fill:#626AAD;}.epoch-theme-dark .epoch.category20 div.ref.category3{background-color:#FFAC89;}.epoch-theme-dark .epoch.category20 .category3 .line{stroke:#FFAC89;}.epoch-theme-dark .epoch.category20 .category3 .area,.epoch-theme-dark .epoch.category20 .category3 .dot{fill:#FFAC89;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20 .arc.category3 path{fill:#FFAC89;}.epoch-theme-dark .epoch.category20 .bar.category3{fill:#FFAC89;}.epoch-theme-dark .epoch.category20 div.ref.category4{background-color:#BD7F66;}.epoch-theme-dark .epoch.category20 .category4 .line{stroke:#BD7F66;}.epoch-theme-dark .epoch.category20 .category4 .area,.epoch-theme-dark .epoch.category20 .category4 .dot{fill:#BD7F66;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20 .arc.category4 path{fill:#BD7F66;}.epoch-theme-dark .epoch.category20 .bar.category4{fill:#BD7F66;}.epoch-theme-dark .epoch.category20 div.ref.category5{background-color:#E889E8;}.epoch-theme-dark .epoch.category20 .category5 .line{stroke:#E889E8;}.epoch-theme-dark .epoch.category20 .category5 .area,.epoch-theme-dark .epoch.category20 .category5 .dot{fill:#E889E8;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20 .arc.category5 path{fill:#E889E8;}.epoch-theme-dark .epoch.category20 .bar.category5{fill:#E889E8;}.epoch-theme-dark .epoch.category20 div.ref.category6{background-color:#995A99;}.epoch-theme-dark .epoch.category20 .category6 .line{stroke:#995A99;}.epoch-theme-dark .epoch.category20 .category6 .area,.epoch-theme-dark .epoch.category20 .category6 .dot{fill:#995A99;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20 .arc.category6 path{fill:#995A99;}.epoch-theme-dark .epoch.category20 .bar.category6{fill:#995A99;}.epoch-theme-dark .epoch.category20 div.ref.category7{background-color:#78E8D3;}.epoch-theme-dark .epoch.category20 .category7 .line{stroke:#78E8D3;}.epoch-theme-dark .epoch.category20 .category7 .area,.epoch-theme-dark .epoch.category20 .category7 .dot{fill:#78E8D3;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20 .arc.category7 path{fill:#78E8D3;}.epoch-theme-dark .epoch.category20 .bar.category7{fill:#78E8D3;}.epoch-theme-dark .epoch.category20 div.ref.category8{background-color:#4F998C;}.epoch-theme-dark .epoch.category20 .category8 .line{stroke:#4F998C;}.epoch-theme-dark .epoch.category20 .category8 .area,.epoch-theme-dark .epoch.category20 .category8 .dot{fill:#4F998C;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20 .arc.category8 path{fill:#4F998C;}.epoch-theme-dark .epoch.category20 .bar.category8{fill:#4F998C;}.epoch-theme-dark .epoch.category20 div.ref.category9{background-color:#C2FF97;}.epoch-theme-dark .epoch.category20 .category9 .line{stroke:#C2FF97;}.epoch-theme-dark .epoch.category20 .category9 .area,.epoch-theme-dark .epoch.category20 .category9 .dot{fill:#C2FF97;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20 .arc.category9 path{fill:#C2FF97;}.epoch-theme-dark .epoch.category20 .bar.category9{fill:#C2FF97;}.epoch-theme-dark .epoch.category20 div.ref.category10{background-color:#789E5E;}.epoch-theme-dark .epoch.category20 .category10 .line{stroke:#789E5E;}.epoch-theme-dark .epoch.category20 .category10 .area,.epoch-theme-dark .epoch.category20 .category10 .dot{fill:#789E5E;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20 .arc.category10 path{fill:#789E5E;}.epoch-theme-dark .epoch.category20 .bar.category10{fill:#789E5E;}.epoch-theme-dark .epoch.category20 div.ref.category11{background-color:#B7BCD1;}.epoch-theme-dark .epoch.category20 .category11 .line{stroke:#B7BCD1;}.epoch-theme-dark .epoch.category20 .category11 .area,.epoch-theme-dark .epoch.category20 .category11 .dot{fill:#B7BCD1;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20 .arc.category11 path{fill:#B7BCD1;}.epoch-theme-dark .epoch.category20 .bar.category11{fill:#B7BCD1;}.epoch-theme-dark .epoch.category20 div.ref.category12{background-color:#7F8391;}.epoch-theme-dark .epoch.category20 .category12 .line{stroke:#7F8391;}.epoch-theme-dark .epoch.category20 .category12 .area,.epoch-theme-dark .epoch.category20 .category12 .dot{fill:#7F8391;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20 .arc.category12 path{fill:#7F8391;}.epoch-theme-dark .epoch.category20 .bar.category12{fill:#7F8391;}.epoch-theme-dark .epoch.category20 div.ref.category13{background-color:#CCB889;}.epoch-theme-dark .epoch.category20 .category13 .line{stroke:#CCB889;}.epoch-theme-dark .epoch.category20 .category13 .area,.epoch-theme-dark .epoch.category20 .category13 .dot{fill:#CCB889;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20 .arc.category13 path{fill:#CCB889;}.epoch-theme-dark .epoch.category20 .bar.category13{fill:#CCB889;}.epoch-theme-dark .epoch.category20 div.ref.category14{background-color:#A1906B;}.epoch-theme-dark .epoch.category20 .category14 .line{stroke:#A1906B;}.epoch-theme-dark .epoch.category20 .category14 .area,.epoch-theme-dark .epoch.category20 .category14 .dot{fill:#A1906B;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20 .arc.category14 path{fill:#A1906B;}.epoch-theme-dark .epoch.category20 .bar.category14{fill:#A1906B;}.epoch-theme-dark .epoch.category20 div.ref.category15{background-color:#F3DE88;}.epoch-theme-dark .epoch.category20 .category15 .line{stroke:#F3DE88;}.epoch-theme-dark .epoch.category20 .category15 .area,.epoch-theme-dark .epoch.category20 .category15 .dot{fill:#F3DE88;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20 .arc.category15 path{fill:#F3DE88;}.epoch-theme-dark .epoch.category20 .bar.category15{fill:#F3DE88;}.epoch-theme-dark .epoch.category20 div.ref.category16{background-color:#A89A5E;}.epoch-theme-dark .epoch.category20 .category16 .line{stroke:#A89A5E;}.epoch-theme-dark .epoch.category20 .category16 .area,.epoch-theme-dark .epoch.category20 .category16 .dot{fill:#A89A5E;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20 .arc.category16 path{fill:#A89A5E;}.epoch-theme-dark .epoch.category20 .bar.category16{fill:#A89A5E;}.epoch-theme-dark .epoch.category20 div.ref.category17{background-color:#FF857F;}.epoch-theme-dark .epoch.category20 .category17 .line{stroke:#FF857F;}.epoch-theme-dark .epoch.category20 .category17 .area,.epoch-theme-dark .epoch.category20 .category17 .dot{fill:#FF857F;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20 .arc.category17 path{fill:#FF857F;}.epoch-theme-dark .epoch.category20 .bar.category17{fill:#FF857F;}.epoch-theme-dark .epoch.category20 div.ref.category18{background-color:#BA615D;}.epoch-theme-dark .epoch.category20 .category18 .line{stroke:#BA615D;}.epoch-theme-dark .epoch.category20 .category18 .area,.epoch-theme-dark .epoch.category20 .category18 .dot{fill:#BA615D;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20 .arc.category18 path{fill:#BA615D;}.epoch-theme-dark .epoch.category20 .bar.category18{fill:#BA615D;}.epoch-theme-dark .epoch.category20 div.ref.category19{background-color:#A488FF;}.epoch-theme-dark .epoch.category20 .category19 .line{stroke:#A488FF;}.epoch-theme-dark .epoch.category20 .category19 .area,.epoch-theme-dark .epoch.category20 .category19 .dot{fill:#A488FF;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20 .arc.category19 path{fill:#A488FF;}.epoch-theme-dark .epoch.category20 .bar.category19{fill:#A488FF;}.epoch-theme-dark .epoch.category20 div.ref.category20{background-color:#7662B8;}.epoch-theme-dark .epoch.category20 .category20 .line{stroke:#7662B8;}.epoch-theme-dark .epoch.category20 .category20 .area,.epoch-theme-dark .epoch.category20 .category20 .dot{fill:#7662B8;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20 .arc.category20 path{fill:#7662B8;}.epoch-theme-dark .epoch.category20 .bar.category20{fill:#7662B8;}.epoch-theme-dark .epoch.category20b div.ref.category1{background-color:#909CFF;}.epoch-theme-dark .epoch.category20b .category1 .line{stroke:#909CFF;}.epoch-theme-dark .epoch.category20b .category1 .area,.epoch-theme-dark .epoch.category20b .category1 .dot{fill:#909CFF;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20b .arc.category1 path{fill:#909CFF;}.epoch-theme-dark .epoch.category20b .bar.category1{fill:#909CFF;}.epoch-theme-dark .epoch.category20b div.ref.category2{background-color:#7680D1;}.epoch-theme-dark .epoch.category20b .category2 .line{stroke:#7680D1;}.epoch-theme-dark .epoch.category20b .category2 .area,.epoch-theme-dark .epoch.category20b .category2 .dot{fill:#7680D1;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20b .arc.category2 path{fill:#7680D1;}.epoch-theme-dark .epoch.category20b .bar.category2{fill:#7680D1;}.epoch-theme-dark .epoch.category20b div.ref.category3{background-color:#656DB2;}.epoch-theme-dark .epoch.category20b .category3 .line{stroke:#656DB2;}.epoch-theme-dark .epoch.category20b .category3 .area,.epoch-theme-dark .epoch.category20b .category3 .dot{fill:#656DB2;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20b .arc.category3 path{fill:#656DB2;}.epoch-theme-dark .epoch.category20b .bar.category3{fill:#656DB2;}.epoch-theme-dark .epoch.category20b div.ref.category4{background-color:#525992;}.epoch-theme-dark .epoch.category20b .category4 .line{stroke:#525992;}.epoch-theme-dark .epoch.category20b .category4 .area,.epoch-theme-dark .epoch.category20b .category4 .dot{fill:#525992;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20b .arc.category4 path{fill:#525992;}.epoch-theme-dark .epoch.category20b .bar.category4{fill:#525992;}.epoch-theme-dark .epoch.category20b div.ref.category5{background-color:#FFAC89;}.epoch-theme-dark .epoch.category20b .category5 .line{stroke:#FFAC89;}.epoch-theme-dark .epoch.category20b .category5 .area,.epoch-theme-dark .epoch.category20b .category5 .dot{fill:#FFAC89;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20b .arc.category5 path{fill:#FFAC89;}.epoch-theme-dark .epoch.category20b .bar.category5{fill:#FFAC89;}.epoch-theme-dark .epoch.category20b div.ref.category6{background-color:#D18D71;}.epoch-theme-dark .epoch.category20b .category6 .line{stroke:#D18D71;}.epoch-theme-dark .epoch.category20b .category6 .area,.epoch-theme-dark .epoch.category20b .category6 .dot{fill:#D18D71;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20b .arc.category6 path{fill:#D18D71;}.epoch-theme-dark .epoch.category20b .bar.category6{fill:#D18D71;}.epoch-theme-dark .epoch.category20b div.ref.category7{background-color:#AB735C;}.epoch-theme-dark .epoch.category20b .category7 .line{stroke:#AB735C;}.epoch-theme-dark .epoch.category20b .category7 .area,.epoch-theme-dark .epoch.category20b .category7 .dot{fill:#AB735C;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20b .arc.category7 path{fill:#AB735C;}.epoch-theme-dark .epoch.category20b .bar.category7{fill:#AB735C;}.epoch-theme-dark .epoch.category20b div.ref.category8{background-color:#92624E;}.epoch-theme-dark .epoch.category20b .category8 .line{stroke:#92624E;}.epoch-theme-dark .epoch.category20b .category8 .area,.epoch-theme-dark .epoch.category20b .category8 .dot{fill:#92624E;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20b .arc.category8 path{fill:#92624E;}.epoch-theme-dark .epoch.category20b .bar.category8{fill:#92624E;}.epoch-theme-dark .epoch.category20b div.ref.category9{background-color:#E889E8;}.epoch-theme-dark .epoch.category20b .category9 .line{stroke:#E889E8;}.epoch-theme-dark .epoch.category20b .category9 .area,.epoch-theme-dark .epoch.category20b .category9 .dot{fill:#E889E8;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20b .arc.category9 path{fill:#E889E8;}.epoch-theme-dark .epoch.category20b .bar.category9{fill:#E889E8;}.epoch-theme-dark .epoch.category20b div.ref.category10{background-color:#BA6EBA;}.epoch-theme-dark .epoch.category20b .category10 .line{stroke:#BA6EBA;}.epoch-theme-dark .epoch.category20b .category10 .area,.epoch-theme-dark .epoch.category20b .category10 .dot{fill:#BA6EBA;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20b .arc.category10 path{fill:#BA6EBA;}.epoch-theme-dark .epoch.category20b .bar.category10{fill:#BA6EBA;}.epoch-theme-dark .epoch.category20b div.ref.category11{background-color:#9B5C9B;}.epoch-theme-dark .epoch.category20b .category11 .line{stroke:#9B5C9B;}.epoch-theme-dark .epoch.category20b .category11 .area,.epoch-theme-dark .epoch.category20b .category11 .dot{fill:#9B5C9B;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20b .arc.category11 path{fill:#9B5C9B;}.epoch-theme-dark .epoch.category20b .bar.category11{fill:#9B5C9B;}.epoch-theme-dark .epoch.category20b div.ref.category12{background-color:#7B487B;}.epoch-theme-dark .epoch.category20b .category12 .line{stroke:#7B487B;}.epoch-theme-dark .epoch.category20b .category12 .area,.epoch-theme-dark .epoch.category20b .category12 .dot{fill:#7B487B;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20b .arc.category12 path{fill:#7B487B;}.epoch-theme-dark .epoch.category20b .bar.category12{fill:#7B487B;}.epoch-theme-dark .epoch.category20b div.ref.category13{background-color:#78E8D3;}.epoch-theme-dark .epoch.category20b .category13 .line{stroke:#78E8D3;}.epoch-theme-dark .epoch.category20b .category13 .area,.epoch-theme-dark .epoch.category20b .category13 .dot{fill:#78E8D3;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20b .arc.category13 path{fill:#78E8D3;}.epoch-theme-dark .epoch.category20b .bar.category13{fill:#78E8D3;}.epoch-theme-dark .epoch.category20b div.ref.category14{background-color:#60BAAA;}.epoch-theme-dark .epoch.category20b .category14 .line{stroke:#60BAAA;}.epoch-theme-dark .epoch.category20b .category14 .area,.epoch-theme-dark .epoch.category20b .category14 .dot{fill:#60BAAA;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20b .arc.category14 path{fill:#60BAAA;}.epoch-theme-dark .epoch.category20b .bar.category14{fill:#60BAAA;}.epoch-theme-dark .epoch.category20b div.ref.category15{background-color:#509B8D;}.epoch-theme-dark .epoch.category20b .category15 .line{stroke:#509B8D;}.epoch-theme-dark .epoch.category20b .category15 .area,.epoch-theme-dark .epoch.category20b .category15 .dot{fill:#509B8D;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20b .arc.category15 path{fill:#509B8D;}.epoch-theme-dark .epoch.category20b .bar.category15{fill:#509B8D;}.epoch-theme-dark .epoch.category20b div.ref.category16{background-color:#3F7B70;}.epoch-theme-dark .epoch.category20b .category16 .line{stroke:#3F7B70;}.epoch-theme-dark .epoch.category20b .category16 .area,.epoch-theme-dark .epoch.category20b .category16 .dot{fill:#3F7B70;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20b .arc.category16 path{fill:#3F7B70;}.epoch-theme-dark .epoch.category20b .bar.category16{fill:#3F7B70;}.epoch-theme-dark .epoch.category20b div.ref.category17{background-color:#C2FF97;}.epoch-theme-dark .epoch.category20b .category17 .line{stroke:#C2FF97;}.epoch-theme-dark .epoch.category20b .category17 .area,.epoch-theme-dark .epoch.category20b .category17 .dot{fill:#C2FF97;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20b .arc.category17 path{fill:#C2FF97;}.epoch-theme-dark .epoch.category20b .bar.category17{fill:#C2FF97;}.epoch-theme-dark .epoch.category20b div.ref.category18{background-color:#9FD17C;}.epoch-theme-dark .epoch.category20b .category18 .line{stroke:#9FD17C;}.epoch-theme-dark .epoch.category20b .category18 .area,.epoch-theme-dark .epoch.category20b .category18 .dot{fill:#9FD17C;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20b .arc.category18 path{fill:#9FD17C;}.epoch-theme-dark .epoch.category20b .bar.category18{fill:#9FD17C;}.epoch-theme-dark .epoch.category20b div.ref.category19{background-color:#7DA361;}.epoch-theme-dark .epoch.category20b .category19 .line{stroke:#7DA361;}.epoch-theme-dark .epoch.category20b .category19 .area,.epoch-theme-dark .epoch.category20b .category19 .dot{fill:#7DA361;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20b .arc.category19 path{fill:#7DA361;}.epoch-theme-dark .epoch.category20b .bar.category19{fill:#7DA361;}.epoch-theme-dark .epoch.category20b div.ref.category20{background-color:#65854E;}.epoch-theme-dark .epoch.category20b .category20 .line{stroke:#65854E;}.epoch-theme-dark .epoch.category20b .category20 .area,.epoch-theme-dark .epoch.category20b .category20 .dot{fill:#65854E;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20b .arc.category20 path{fill:#65854E;}.epoch-theme-dark .epoch.category20b .bar.category20{fill:#65854E;}.epoch-theme-dark .epoch.category20c div.ref.category1{background-color:#B7BCD1;}.epoch-theme-dark .epoch.category20c .category1 .line{stroke:#B7BCD1;}.epoch-theme-dark .epoch.category20c .category1 .area,.epoch-theme-dark .epoch.category20c .category1 .dot{fill:#B7BCD1;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20c .arc.category1 path{fill:#B7BCD1;}.epoch-theme-dark .epoch.category20c .bar.category1{fill:#B7BCD1;}.epoch-theme-dark .epoch.category20c div.ref.category2{background-color:#979DAD;}.epoch-theme-dark .epoch.category20c .category2 .line{stroke:#979DAD;}.epoch-theme-dark .epoch.category20c .category2 .area,.epoch-theme-dark .epoch.category20c .category2 .dot{fill:#979DAD;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20c .arc.category2 path{fill:#979DAD;}.epoch-theme-dark .epoch.category20c .bar.category2{fill:#979DAD;}.epoch-theme-dark .epoch.category20c div.ref.category3{background-color:#6E717D;}.epoch-theme-dark .epoch.category20c .category3 .line{stroke:#6E717D;}.epoch-theme-dark .epoch.category20c .category3 .area,.epoch-theme-dark .epoch.category20c .category3 .dot{fill:#6E717D;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20c .arc.category3 path{fill:#6E717D;}.epoch-theme-dark .epoch.category20c .bar.category3{fill:#6E717D;}.epoch-theme-dark .epoch.category20c div.ref.category4{background-color:#595C66;}.epoch-theme-dark .epoch.category20c .category4 .line{stroke:#595C66;}.epoch-theme-dark .epoch.category20c .category4 .area,.epoch-theme-dark .epoch.category20c .category4 .dot{fill:#595C66;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20c .arc.category4 path{fill:#595C66;}.epoch-theme-dark .epoch.category20c .bar.category4{fill:#595C66;}.epoch-theme-dark .epoch.category20c div.ref.category5{background-color:#FF857F;}.epoch-theme-dark .epoch.category20c .category5 .line{stroke:#FF857F;}.epoch-theme-dark .epoch.category20c .category5 .area,.epoch-theme-dark .epoch.category20c .category5 .dot{fill:#FF857F;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20c .arc.category5 path{fill:#FF857F;}.epoch-theme-dark .epoch.category20c .bar.category5{fill:#FF857F;}.epoch-theme-dark .epoch.category20c div.ref.category6{background-color:#DE746E;}.epoch-theme-dark .epoch.category20c .category6 .line{stroke:#DE746E;}.epoch-theme-dark .epoch.category20c .category6 .area,.epoch-theme-dark .epoch.category20c .category6 .dot{fill:#DE746E;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20c .arc.category6 path{fill:#DE746E;}.epoch-theme-dark .epoch.category20c .bar.category6{fill:#DE746E;}.epoch-theme-dark .epoch.category20c div.ref.category7{background-color:#B55F5A;}.epoch-theme-dark .epoch.category20c .category7 .line{stroke:#B55F5A;}.epoch-theme-dark .epoch.category20c .category7 .area,.epoch-theme-dark .epoch.category20c .category7 .dot{fill:#B55F5A;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20c .arc.category7 path{fill:#B55F5A;}.epoch-theme-dark .epoch.category20c .bar.category7{fill:#B55F5A;}.epoch-theme-dark .epoch.category20c div.ref.category8{background-color:#964E4B;}.epoch-theme-dark .epoch.category20c .category8 .line{stroke:#964E4B;}.epoch-theme-dark .epoch.category20c .category8 .area,.epoch-theme-dark .epoch.category20c .category8 .dot{fill:#964E4B;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20c .arc.category8 path{fill:#964E4B;}.epoch-theme-dark .epoch.category20c .bar.category8{fill:#964E4B;}.epoch-theme-dark .epoch.category20c div.ref.category9{background-color:#F3DE88;}.epoch-theme-dark .epoch.category20c .category9 .line{stroke:#F3DE88;}.epoch-theme-dark .epoch.category20c .category9 .area,.epoch-theme-dark .epoch.category20c .category9 .dot{fill:#F3DE88;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20c .arc.category9 path{fill:#F3DE88;}.epoch-theme-dark .epoch.category20c .bar.category9{fill:#F3DE88;}.epoch-theme-dark .epoch.category20c div.ref.category10{background-color:#DBC87B;}.epoch-theme-dark .epoch.category20c .category10 .line{stroke:#DBC87B;}.epoch-theme-dark .epoch.category20c .category10 .area,.epoch-theme-dark .epoch.category20c .category10 .dot{fill:#DBC87B;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20c .arc.category10 path{fill:#DBC87B;}.epoch-theme-dark .epoch.category20c .bar.category10{fill:#DBC87B;}.epoch-theme-dark .epoch.category20c div.ref.category11{background-color:#BAAA68;}.epoch-theme-dark .epoch.category20c .category11 .line{stroke:#BAAA68;}.epoch-theme-dark .epoch.category20c .category11 .area,.epoch-theme-dark .epoch.category20c .category11 .dot{fill:#BAAA68;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20c .arc.category11 path{fill:#BAAA68;}.epoch-theme-dark .epoch.category20c .bar.category11{fill:#BAAA68;}.epoch-theme-dark .epoch.category20c div.ref.category12{background-color:#918551;}.epoch-theme-dark .epoch.category20c .category12 .line{stroke:#918551;}.epoch-theme-dark .epoch.category20c .category12 .area,.epoch-theme-dark .epoch.category20c .category12 .dot{fill:#918551;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20c .arc.category12 path{fill:#918551;}.epoch-theme-dark .epoch.category20c .bar.category12{fill:#918551;}.epoch-theme-dark .epoch.category20c div.ref.category13{background-color:#C9935E;}.epoch-theme-dark .epoch.category20c .category13 .line{stroke:#C9935E;}.epoch-theme-dark .epoch.category20c .category13 .area,.epoch-theme-dark .epoch.category20c .category13 .dot{fill:#C9935E;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20c .arc.category13 path{fill:#C9935E;}.epoch-theme-dark .epoch.category20c .bar.category13{fill:#C9935E;}.epoch-theme-dark .epoch.category20c div.ref.category14{background-color:#B58455;}.epoch-theme-dark .epoch.category20c .category14 .line{stroke:#B58455;}.epoch-theme-dark .epoch.category20c .category14 .area,.epoch-theme-dark .epoch.category20c .category14 .dot{fill:#B58455;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20c .arc.category14 path{fill:#B58455;}.epoch-theme-dark .epoch.category20c .bar.category14{fill:#B58455;}.epoch-theme-dark .epoch.category20c div.ref.category15{background-color:#997048;}.epoch-theme-dark .epoch.category20c .category15 .line{stroke:#997048;}.epoch-theme-dark .epoch.category20c .category15 .area,.epoch-theme-dark .epoch.category20c .category15 .dot{fill:#997048;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20c .arc.category15 path{fill:#997048;}.epoch-theme-dark .epoch.category20c .bar.category15{fill:#997048;}.epoch-theme-dark .epoch.category20c div.ref.category16{background-color:#735436;}.epoch-theme-dark .epoch.category20c .category16 .line{stroke:#735436;}.epoch-theme-dark .epoch.category20c .category16 .area,.epoch-theme-dark .epoch.category20c .category16 .dot{fill:#735436;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20c .arc.category16 path{fill:#735436;}.epoch-theme-dark .epoch.category20c .bar.category16{fill:#735436;}.epoch-theme-dark .epoch.category20c div.ref.category17{background-color:#A488FF;}.epoch-theme-dark .epoch.category20c .category17 .line{stroke:#A488FF;}.epoch-theme-dark .epoch.category20c .category17 .area,.epoch-theme-dark .epoch.category20c .category17 .dot{fill:#A488FF;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20c .arc.category17 path{fill:#A488FF;}.epoch-theme-dark .epoch.category20c .bar.category17{fill:#A488FF;}.epoch-theme-dark .epoch.category20c div.ref.category18{background-color:#8670D1;}.epoch-theme-dark .epoch.category20c .category18 .line{stroke:#8670D1;}.epoch-theme-dark .epoch.category20c .category18 .area,.epoch-theme-dark .epoch.category20c .category18 .dot{fill:#8670D1;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20c .arc.category18 path{fill:#8670D1;}.epoch-theme-dark .epoch.category20c .bar.category18{fill:#8670D1;}.epoch-theme-dark .epoch.category20c div.ref.category19{background-color:#705CAD;}.epoch-theme-dark .epoch.category20c .category19 .line{stroke:#705CAD;}.epoch-theme-dark .epoch.category20c .category19 .area,.epoch-theme-dark .epoch.category20c .category19 .dot{fill:#705CAD;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20c .arc.category19 path{fill:#705CAD;}.epoch-theme-dark .epoch.category20c .bar.category19{fill:#705CAD;}.epoch-theme-dark .epoch.category20c div.ref.category20{background-color:#52447F;}.epoch-theme-dark .epoch.category20c .category20 .line{stroke:#52447F;}.epoch-theme-dark .epoch.category20c .category20 .area,.epoch-theme-dark .epoch.category20c .category20 .dot{fill:#52447F;stroke:rgba(0, 0, 0, 0);}.epoch-theme-dark .epoch.category20c .arc.category20 path{fill:#52447F;}.epoch-theme-dark .epoch.category20c .bar.category20{fill:#52447F;}added:examples/realtime-advanced/resources/static/epoch.min.js+114 added
1+(function(){var e;null==window.Epoch&&(window.Epoch={});null==(e=window.Epoch).Chart&&(e.Chart={});null==(e=window.Epoch).Time&&(e.Time={});null==(e=window.Epoch).Util&&(e.Util={});null==(e=window.Epoch).Formats&&(e.Formats={});Epoch.warn=function(g){return(console.warn||console.log)("Epoch Warning: "+g)};Epoch.exception=function(g){throw"Epoch Error: "+g;}}).call(this);2+(function(){Epoch.TestContext=function(){function e(){var c,a,d;this._log=[];a=0;for(d=g.length;a<d;a++)c=g[a],this._makeFauxMethod(c)}var g;g="arc arcTo beginPath bezierCurveTo clearRect clip closePath drawImage fill fillRect fillText moveTo quadraticCurveTo rect restore rotate save scale scrollPathIntoView setLineDash setTransform stroke strokeRect strokeText transform translate".split(" ");e.prototype._makeFauxMethod=function(c){return this[c]=function(){var a;return this._log.push(""+c+"("+function(){var d,3+b,h;h=[];d=0;for(b=arguments.length;d<b;d++)a=arguments[d],h.push(a.toString());return h}.apply(this,arguments).join(",")+")")}};e.prototype.getImageData=function(){var c;this._log.push("getImageData("+function(){var a,d,b;b=[];a=0;for(d=arguments.length;a<d;a++)c=arguments[a],b.push(c.toString());return b}.apply(this,arguments).join(",")+")");return{width:0,height:0,resolution:1,data:[]}};return e}()}).call(this);4+(function(){var e,g;e=function(c){return function(a){return Object.prototype.toString.call(a)==="[object "+c+"]"}};Epoch.isArray=null!=(g=Array.isArray)?g:e("Array");Epoch.isObject=e("Object");Epoch.isString=e("String");Epoch.isFunction=e("Function");Epoch.isNumber=e("Number");Epoch.isElement=function(c){return"undefined"!==typeof HTMLElement&&null!==HTMLElement?c instanceof HTMLElement:null!=c&&Epoch.isObject(c)&&1===c.nodeType&&Epoch.isString(c.nodeName)};Epoch.Util.copy=function(c){var a,d,b;if(null==5+c)return null;a={};for(d in c)b=c[d],a[d]=b;return a};Epoch.Util.defaults=function(c,a){var d,b,h,k,f;f=Epoch.Util.copy(c);for(h in a)k=c[h],b=a[h],d=Epoch.isObject(k)&&Epoch.isObject(b),null!=k&&null!=b?d&&!Epoch.isArray(k)?f[h]=Epoch.Util.defaults(k,b):f[h]=k:f[h]=null!=k?k:b;return f};Epoch.Util.formatSI=function(c,a,d){var b,h,k,f;null==a&&(a=1);null==d&&(d=!1);if(1E3>c){if((c|0)!==c||d)c=c.toFixed(a);return c}f="KMGTPEZY".split("");for(h in f)if(k=f[h],b=Math.pow(10,3*((h|0)+1)),c>=b&&c<Math.pow(10,6+3*((h|0)+2))){c/=b;if(0!==c%1||d)c=c.toFixed(a);return""+c+" "+k}};Epoch.Util.formatBytes=function(c,a,d){var b,h,k,f;null==a&&(a=1);null==d&&(d=!1);if(1024>c){if(0!==c%1||d)c=c.toFixed(a);return""+c+" B"}f="KB MB GB TB PB EB ZB YB".split(" ");for(h in f)if(k=f[h],b=Math.pow(1024,(h|0)+1),c>=b&&c<Math.pow(1024,(h|0)+2)){c/=b;if(0!==c%1||d)c=c.toFixed(a);return""+c+" "+k}};Epoch.Util.dasherize=function(c){return Epoch.Util.trim(c).replace("\n","").replace(/\s+/g,"-").toLowerCase()};Epoch.Util.domain=7+function(c,a){var d,b,h,k,f,q,u,m;null==a&&(a="x");h={};d=[];k=0;for(q=c.length;k<q;k++)for(b=c[k],m=b.values,f=0,u=m.length;f<u;f++)b=m[f],null==h[b[a]]&&(d.push(b[a]),h[b[a]]=!0);return d};Epoch.Util.trim=function(c){return Epoch.isString(c)?c.replace(/^\s+/g,"").replace(/\s+$/g,""):null};Epoch.Util.getComputedStyle=function(c,a){if(Epoch.isFunction(window.getComputedStyle))return window.getComputedStyle(c,a);if(null!=c.currentStyle)return c.currentStyle};Epoch.Util.toRGBA=function(c,a){var d,b,8+h;if(d=c.match(/^rgba\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*[0-9\.]+\)/))h=d[1],b=d[2],d=d[3],b="rgba("+h+","+b+","+d+","+a+")";else if(d=d3.rgb(c))b="rgba("+d.r+","+d.g+","+d.b+","+a+")";return b};Epoch.Util.getContext=function(c,a){null==a&&(a="2d");return null!=c.getContext?c.getContext(a):new Epoch.TestContext}}).call(this);9+(function(){d3.selection.prototype.width=function(e){return null!=e&&Epoch.isString(e)?this.style("width",e):null!=e&&Epoch.isNumber(e)?this.style("width",""+e+"px"):+Epoch.Util.getComputedStyle(this.node(),null).width.replace("px","")};d3.selection.prototype.height=function(e){return null!=e&&Epoch.isString(e)?this.style("height",e):null!=e&&Epoch.isNumber(e)?this.style("height",""+e+"px"):+Epoch.Util.getComputedStyle(this.node(),null).height.replace("px","")}}).call(this);10+(function(){var e;Epoch.Formats.regular=function(g){return g};Epoch.Formats.si=function(g){return Epoch.Util.formatSI(g)};Epoch.Formats.percent=function(g){return(100*g).toFixed(1)+"%"};Epoch.Formats.seconds=function(g){return e(new Date(1E3*g))};e=d3.time.format("%I:%M:%S %p");Epoch.Formats.bytes=function(g){return Epoch.Util.formatBytes(g)}}).call(this);11+(function(){var e={}.hasOwnProperty,g=function(c,a){function d(){this.constructor=c}for(var b in a)e.call(a,b)&&(c[b]=a[b]);d.prototype=a.prototype;c.prototype=new d;c.__super__=a.prototype;return c};Epoch.Events=function(){function c(){this._events={}}c.prototype.on=function(a,d){var b;if(null!=d)return null==(b=this._events)[a]&&(b[a]=[]),this._events[a].push(d)};c.prototype.onAll=function(a){var d,b,h;if(Epoch.isObject(a)){h=[];for(b in a)d=a[b],h.push(this.on(b,d));return h}};c.prototype.off=12+function(a,d){var b,h;if(Epoch.isArray(this._events[a])){if(null==d)return delete this._events[a];for(h=[];0<=(b=this._events[a].indexOf(d));)h.push(this._events[a].splice(b,1));return h}};c.prototype.offAll=function(a){var d,b,h,k;if(Epoch.isArray(a)){k=[];d=0;for(h=a.length;d<h;d++)b=a[d],k.push(this.off(b));return k}if(Epoch.isObject(a)){h=[];for(b in a)d=a[b],h.push(this.off(b,d));return h}};c.prototype.trigger=function(a){var d,b,h,k,f,q,c,m;if(null!=this._events[a]){d=function(){var a,f,q;q=13+[];k=a=1;for(f=arguments.length;1<=f?a<f:a>f;k=1<=f?++a:--a)q.push(arguments[k]);return q}.apply(this,arguments);c=this._events[a];m=[];f=0;for(q=c.length;f<q;f++)b=c[f],h=null,Epoch.isString(b)?h=this[b]:Epoch.isFunction(b)&&(h=b),null==h&&Epoch.exception("Callback for event '"+a+"' is not a function or reference to a method."),m.push(h.apply(this,d));return m}};return c}();Epoch.Chart.Base=function(c){function a(h){this.options=null!=h?h:{};a.__super__.constructor.call(this);this.setData(this.options.data||14+[]);null!=this.options.el&&(this.el=d3.select(this.options.el));this.width=this.options.width;this.height=this.options.height;null!=this.el?(null==this.width&&(this.width=this.el.width()),null==this.height&&(this.height=this.el.height())):(null==this.width&&(this.width=d.width),null==this.height&&(this.height=d.height));this.onAll(b)}var d,b;g(a,c);d={width:320,height:240};b={"option:width":"dimensionsChanged","option:height":"dimensionsChanged"};a.prototype._getAllOptions=function(){return Epoch.Util.defaults({},15+this.options)};a.prototype._getOption=function(a){var k,f;a=a.split(".");for(k=this.options;a.length&&null!=k;)f=a.shift(),k=k[f];return k};a.prototype._setOption=function(a,k){var f,q,b;f=a.split(".");for(q=this.options;f.length;){b=f.shift();if(0===f.length){q[b]=k;this.trigger("option:"+a);break}null==q[b]&&(q[b]={});q=q[b]}};a.prototype._setManyOptions=function(a,k){var f,q,b;null==k&&(k="");b=[];for(f in a)q=a[f],Epoch.isObject(q)?b.push(this._setManyOptions(q,""+(k+f)+".")):b.push(this._setOption(k+16+f,q));return b};a.prototype.option=function(){if(0===arguments.length)return this._getAllOptions();if(1===arguments.length&&Epoch.isString(arguments[0]))return this._getOption(arguments[0]);if(2===arguments.length&&Epoch.isString(arguments[0]))return this._setOption(arguments[0],arguments[1]);if(1===arguments.length&&Epoch.isObject(arguments[0]))return this._setManyOptions(arguments[0])};a.prototype.setData=function(a){var k,f,b,d,c;k=1;d=0;for(c=a.length;d<c;d++)b=a[d],f=["layer"],f.push("category"+17+k),b.category=k,null!=b.label&&f.push(Epoch.Util.dasherize(b.label)),b.className=f.join(" "),k++;return this.data=a};a.prototype.update=function(a,k){null==k&&(k=!0);this.setData(a);if(k)return this.draw()};a.prototype.draw=function(){return this.trigger("draw")};a.prototype.extent=function(a){return[d3.min(this.data,function(k){return d3.min(k.values,a)}),d3.max(this.data,function(k){return d3.max(k.values,a)})]};a.prototype.dimensionsChanged=function(){this.width=this.option("width")||this.width;18+this.height=this.option("height")||this.height;this.el.width(this.width);return this.el.height(this.height)};return a}(Epoch.Events);Epoch.Chart.SVG=function(c){function a(d){this.options=null!=d?d:{};a.__super__.constructor.call(this,this.options);this.svg=null!=this.el?this.el.append("svg"):d3.select(document.createElement("svg"));this.svg.attr({xmlns:"http://www.w3.org/2000/svg",width:this.width,height:this.height})}g(a,c);a.prototype.dimensionsChanged=function(){a.__super__.dimensionsChanged.call(this);19+return this.svg.attr("width",this.width).attr("height",this.height)};return a}(Epoch.Chart.Base);Epoch.Chart.Canvas=function(c){function a(d){this.options=null!=d?d:{};a.__super__.constructor.call(this,this.options);this.pixelRatio=null!=this.options.pixelRatio?this.options.pixelRatio:null!=window.devicePixelRatio?window.devicePixelRatio:1;this.canvas=d3.select(document.createElement("CANVAS"));this.canvas.style({width:""+this.width+"px",height:""+this.height+"px"});this.canvas.attr({width:this.getWidth(),20+height:this.getHeight()});null!=this.el&&this.el.node().appendChild(this.canvas.node());this.ctx=Epoch.Util.getContext(this.canvas.node())}g(a,c);a.prototype.getWidth=function(){return this.width*this.pixelRatio};a.prototype.getHeight=function(){return this.height*this.pixelRatio};a.prototype.clear=function(){return this.ctx.clearRect(0,0,this.getWidth(),this.getHeight())};a.prototype.getStyles=function(a){return Epoch.QueryCSS.getStyles(a,this.el)};a.prototype.dimensionsChanged=function(){a.__super__.dimensionsChanged.call(this);21+this.canvas.style({width:""+this.width+"px",height:""+this.height+"px"});return this.canvas.attr({width:this.getWidth(),height:this.getHeight()})};return a}(Epoch.Chart.Base)}).call(this);22+(function(){var e;e=function(){function g(){}var c,a,d,b,h;a=0;b=function(){return"epoch-container-"+a++};c=/^([^#. ]+)?(#[^. ]+)?(\.[^# ]+)?$/;d=!1;h=function(a){var f,b;f=a.match(c);if(null==f)return Epoch.error("Query CSS cannot match given selector: "+a);b=f[1];a=f[2];f=f[3];b=(null!=b?b:"div").toUpperCase();b=document.createElement(b);null!=a&&(b.id=a.substr(1));null!=f&&(b.className=f.substr(1).replace(/\./g," "));return b};g.log=function(a){return d=a};g.cache={};g.styleList=["fill","stroke",23+"stroke-width"];g.container=null;g.purge=function(){return g.cache={}};g.getContainer=function(){var a;if(null!=g.container)return g.container;a=document.createElement("DIV");a.id="_canvas_css_reference";document.body.appendChild(a);return g.container=d3.select(a)};g.hash=function(a,f){var d;d=f.attr("data-epoch-container-id");null==d&&(d=b(),f.attr("data-epoch-container-id",d));return""+d+"__"+a};g.getStyles=function(a,f){var b,c,m,l,n,e,r;c=g.hash(a,f);b=g.cache[c];if(null!=b)return b;m=[];for(b=24+f.node().parentNode;null!=b&&"body"!==b.nodeName.toLowerCase();)m.unshift(b),b=b.parentNode;m.push(f.node());b=[];e=0;for(r=m.length;e<r;e++)l=m[e],n=l.nodeName.toLowerCase(),null!=l.id&&0<l.id.length&&(n+="#"+l.id),null!=l.className&&0<l.className.length&&(n+="."+Epoch.Util.trim(l.className).replace(/\s+/g,".")),b.push(n);b.push("svg");e=Epoch.Util.trim(a).split(/\s+/);l=0;for(n=e.length;l<n;l++)m=e[l],b.push(m);d&&console.log(b);for(l=n=h(b.shift());b.length;)m=h(b.shift()),l.appendChild(m),l=m;25+d&&console.log(n);g.getContainer().node().appendChild(n);m=d3.select("#_canvas_css_reference "+a);l={};r=g.styleList;n=0;for(e=r.length;n<e;n++)b=r[n],l[b]=m.style(b);g.cache[c]=l;g.getContainer().html("");return l};return g}();Epoch.QueryCSS=e}).call(this);26+(function(){var e={}.hasOwnProperty,g=function(c,a){function d(){this.constructor=c}for(var b in a)e.call(a,b)&&(c[b]=a[b]);d.prototype=a.prototype;c.prototype=new d;c.__super__=a.prototype;return c};Epoch.Chart.Plot=function(c){function a(k){var f,c,u;this.options=null!=k?k:{};Epoch.Util.copy(this.options.margins);a.__super__.constructor.call(this,this.options=Epoch.Util.defaults(this.options,b));this.margins={};u=["top","right","bottom","left"];f=0;for(c=u.length;f<c;f++)k=u[f],this.margins[k]=27+null!=this.options.margins&&null!=this.options.margins[k]?this.options.margins[k]:this.hasAxis(k)?d[k]:6;this.g=this.svg.append("g").attr("transform","translate("+this.margins.left+", "+this.margins.top+")");this.onAll(h)}var d,b,h;g(a,c);b={domain:null,range:null,axes:["left","bottom"],ticks:{top:14,bottom:14,left:5,right:5},tickFormats:{top:Epoch.Formats.regular,bottom:Epoch.Formats.regular,left:Epoch.Formats.si,right:Epoch.Formats.si}};d={top:25,right:50,bottom:25,left:50};h={"option:margins.top":"marginsChanged",28+"option:margins.right":"marginsChanged","option:margins.bottom":"marginsChanged","option:margins.left":"marginsChanged","option:axes":"axesChanged","option:ticks.top":"ticksChanged","option:ticks.right":"ticksChanged","option:ticks.bottom":"ticksChanged","option:ticks.left":"ticksChanged","option:tickFormats.top":"tickFormatsChanged","option:tickFormats.right":"tickFormatsChanged","option:tickFormats.bottom":"tickFormatsChanged","option:tickFormats.left":"tickFormatsChanged","option:domain":"domainChanged",29+"option:range":"rangeChanged"};a.prototype.setTickFormat=function(a,f){return this.options.tickFormats[a]=f};a.prototype.hasAxis=function(a){return-1<this.options.axes.indexOf(a)};a.prototype.innerWidth=function(){return this.width-(this.margins.left+this.margins.right)};a.prototype.innerHeight=function(){return this.height-(this.margins.top+this.margins.bottom)};a.prototype.x=function(){var a,f;a=null!=(f=this.options.domain)?f:this.extent(function(a){return a.x});return d3.scale.linear().domain(a).range([0,30+this.innerWidth()])};a.prototype.y=function(){var a,f;a=null!=(f=this.options.range)?f:this.extent(function(a){return a.y});return d3.scale.linear().domain(a).range([this.innerHeight(),0])};a.prototype.bottomAxis=function(){return d3.svg.axis().scale(this.x()).orient("bottom").ticks(this.options.ticks.bottom).tickFormat(this.options.tickFormats.bottom)};a.prototype.topAxis=function(){return d3.svg.axis().scale(this.x()).orient("top").ticks(this.options.ticks.top).tickFormat(this.options.tickFormats.top)};31+a.prototype.leftAxis=function(){return d3.svg.axis().scale(this.y()).orient("left").ticks(this.options.ticks.left).tickFormat(this.options.tickFormats.left)};a.prototype.rightAxis=function(){return d3.svg.axis().scale(this.y()).orient("right").ticks(this.options.ticks.right).tickFormat(this.options.tickFormats.right)};a.prototype.draw=function(){this._axesDrawn?this._redrawAxes():this._drawAxes();return a.__super__.draw.call(this)};a.prototype._redrawAxes=function(){this.hasAxis("bottom")&&this.g.selectAll(".x.axis.bottom").transition().duration(500).ease("linear").call(this.bottomAxis());32+this.hasAxis("top")&&this.g.selectAll(".x.axis.top").transition().duration(500).ease("linear").call(this.topAxis());this.hasAxis("left")&&this.g.selectAll(".y.axis.left").transition().duration(500).ease("linear").call(this.leftAxis());if(this.hasAxis("right"))return this.g.selectAll(".y.axis.right").transition().duration(500).ease("linear").call(this.rightAxis())};a.prototype._drawAxes=function(){this.hasAxis("bottom")&&this.g.append("g").attr("class","x axis bottom").attr("transform","translate(0, "+33+this.innerHeight()+")").call(this.bottomAxis());this.hasAxis("top")&&this.g.append("g").attr("class","x axis top").call(this.topAxis());this.hasAxis("left")&&this.g.append("g").attr("class","y axis left").call(this.leftAxis());this.hasAxis("right")&&this.g.append("g").attr("class","y axis right").attr("transform","translate("+this.innerWidth()+", 0)").call(this.rightAxis());return this._axesDrawn=!0};a.prototype.dimensionsChanged=function(){a.__super__.dimensionsChanged.call(this);this.g.selectAll(".axis").remove();34+this._axesDrawn=!1;return this.draw()};a.prototype.marginsChanged=function(){var a,f,b;if(null!=this.options.margins){b=this.options.margins;for(a in b)f=b[a],this.margins[a]=null==f?6:f;this.g.transition().duration(750).attr("transform","translate("+this.margins.left+", "+this.margins.top+")");return this.draw()}};a.prototype.axesChanged=function(){var a,f,b,c;c=["top","right","bottom","left"];f=0;for(b=c.length;f<b;f++)if(a=c[f],null==this.options.margins||null==this.options.margins[a])this.hasAxis(a)?35+this.margins[a]=d[a]:this.margins[a]=6;this.g.transition().duration(750).attr("transform","translate("+this.margins.left+", "+this.margins.top+")");this.g.selectAll(".axis").remove();this._axesDrawn=!1;return this.draw()};a.prototype.ticksChanged=function(){return this.draw()};a.prototype.tickFormatsChanged=function(){return this.draw()};a.prototype.domainChanged=function(){return this.draw()};a.prototype.rangeChanged=function(){return this.draw()};return a}(Epoch.Chart.SVG)}).call(this);36+(function(){var e={}.hasOwnProperty,g=function(c,a){function d(){this.constructor=c}for(var b in a)e.call(a,b)&&(c[b]=a[b]);d.prototype=a.prototype;c.prototype=new d;c.__super__=a.prototype;return c};Epoch.Chart.Area=function(c){function a(){return a.__super__.constructor.apply(this,arguments)}g(a,c);a.prototype.y=function(){var a,b,c,k,f,q,u,m;a=[];q=this.data;k=0;for(f=q.length;k<f;k++)for(b in c=q[k],u=c.values,u)c=u[b],null!=a[b]&&(a[b]+=c.y),null==a[b]&&(a[b]=c.y);return d3.scale.linear().domain(null!=37+(m=this.options.range)?m:[0,d3.max(a)]).range([this.height-this.margins.top-this.margins.bottom,0])};a.prototype.draw=function(){var d,b,c,k;b=[this.x(),this.y()];c=b[0];k=b[1];d=d3.svg.area().x(function(a){return c(a.x)}).y0(function(a){return k(a.y0)}).y1(function(a){return k(a.y0+a.y)});d3.layout.stack().values(function(a){return a.values})(this.data);this.g.selectAll(".layer").remove();b=this.g.selectAll(".layer").data(this.data,function(a){return a.category});b.select(".area").attr("d",function(a){return d(a.values)});38+b.enter().append("g").attr("class",function(a){return a.className});b.append("path").attr("class","area").attr("d",function(a){return d(a.values)});return a.__super__.draw.call(this)};return a}(Epoch.Chart.Plot)}).call(this);39+(function(){var e={}.hasOwnProperty,g=function(c,a){function d(){this.constructor=c}for(var b in a)e.call(a,b)&&(c[b]=a[b]);d.prototype=a.prototype;c.prototype=new d;c.__super__=a.prototype;return c};Epoch.Chart.Bar=function(c){function a(k){this.options=null!=k?k:{};this.options="horizontal"===this.options.orientation?Epoch.Util.defaults(this.options,b):Epoch.Util.defaults(this.options,d);a.__super__.constructor.call(this,this.options);this.onAll(h)}var d,b,h;g(a,c);d={style:"grouped",orientation:"vertical",40+padding:{bar:0.08,group:0.1},outerPadding:{bar:0.08,group:0.1}};b=Epoch.Util.defaults({tickFormats:{top:Epoch.Formats.si,bottom:Epoch.Formats.si,left:Epoch.Formats.regular,right:Epoch.Formats.regular}},d);h={"option:orientation":"orientationChanged","option:padding":"paddingChanged","option:outerPadding":"paddingChanged","option:padding:bar":"paddingChanged","option:padding:group":"paddingChanged","option:outerPadding:bar":"paddingChanged","option:outerPadding:group":"paddingChanged"};a.prototype.x=41+function(){var a;if("vertical"===this.options.orientation)return d3.scale.ordinal().domain(Epoch.Util.domain(this.data)).rangeRoundBands([0,this.innerWidth()],this.options.padding.group,this.options.outerPadding.group);a=this.extent(function(a){return a.y});a[0]=Math.min(0,a[0]);return d3.scale.linear().domain(a).range([0,this.width-this.margins.left-this.margins.right])};a.prototype.x1=function(a){var f;return d3.scale.ordinal().domain(function(){var a,k,b,d;b=this.data;d=[];a=0;for(k=b.length;a<42+k;a++)f=b[a],d.push(f.category);return d}.call(this)).rangeRoundBands([0,a.rangeBand()],this.options.padding.bar,this.options.outerPadding.bar)};a.prototype.y=function(){var a;return"vertical"===this.options.orientation?(a=this.extent(function(a){return a.y}),a[0]=Math.min(0,a[0]),d3.scale.linear().domain(a).range([this.height-this.margins.top-this.margins.bottom,0])):d3.scale.ordinal().domain(Epoch.Util.domain(this.data)).rangeRoundBands([0,this.innerHeight()],this.options.padding.group,this.options.outerPadding.group)};43+a.prototype.y1=function(a){var f;return d3.scale.ordinal().domain(function(){var a,k,b,d;b=this.data;d=[];a=0;for(k=b.length;a<k;a++)f=b[a],d.push(f.category);return d}.call(this)).rangeRoundBands([0,a.rangeBand()],this.options.padding.bar,this.options.outerPadding.bar)};a.prototype._remapData=function(){var a,f,b,d,c,h,n,e,g,s,t,v;c={};t=this.data;h=0;for(e=t.length;h<e;h++)for(d=t[h],a="bar "+d.className.replace(/\s*layer\s*/,""),v=d.values,n=0,g=v.length;n<g;n++)f=v[n],null==c[s=f.x]&&(c[s]=[]),44+c[f.x].push({label:d.category,y:f.y,className:a});f=[];for(b in c)a=c[b],f.push({group:b,values:a});return f};a.prototype.draw=function(){"horizontal"===this.options.orientation?this._drawHorizontal():this._drawVertical();return a.__super__.draw.call(this)};a.prototype._drawVertical=function(){var a,b,d,c,h,l;a=[this.x(),this.y()];c=a[0];l=a[1];h=this.x1(c);b=this.height-this.margins.top-this.margins.bottom;a=this._remapData();a=this.g.selectAll(".layer").data(a,function(a){return a.group});a.transition().duration(750).attr("transform",45+function(a){return"translate("+c(a.group)+", 0)"});a.enter().append("g").attr("class","layer").attr("transform",function(a){return"translate("+c(a.group)+", 0)"});d=a.selectAll("rect").data(function(a){return a.values});d.transition().duration(600).attr("x",function(a){return h(a.label)}).attr("y",function(a){return l(a.y)}).attr("width",h.rangeBand()).attr("height",function(a){return b-l(a.y)});d.enter().append("rect").attr("class",function(a){return a.className}).attr("x",function(a){return h(a.label)}).attr("y",46+function(a){return l(a.y)}).attr("width",h.rangeBand()).attr("height",function(a){return b-l(a.y)});d.exit().transition().duration(150).style("opacity","0").remove();return a.exit().transition().duration(750).style("opacity","0").remove()};a.prototype._drawHorizontal=function(){var a,b,d,c,h;a=[this.x(),this.y()];d=a[0];c=a[1];h=this.y1(c);a=this._remapData();a=this.g.selectAll(".layer").data(a,function(a){return a.group});a.transition().duration(750).attr("transform",function(a){return"translate(0, "+47+c(a.group)+")"});a.enter().append("g").attr("class","layer").attr("transform",function(a){return"translate(0, "+c(a.group)+")"});b=a.selectAll("rect").data(function(a){return a.values});b.transition().duration(600).attr("x",function(a){return 0}).attr("y",function(a){return h(a.label)}).attr("height",h.rangeBand()).attr("width",function(a){return d(a.y)});b.enter().append("rect").attr("class",function(a){return a.className}).attr("x",function(a){return 0}).attr("y",function(a){return h(a.label)}).attr("height",48+h.rangeBand()).attr("width",function(a){return d(a.y)});b.exit().transition().duration(150).style("opacity","0").remove();return a.exit().transition().duration(750).style("opacity","0").remove()};a.prototype.orientationChanged=function(){var a,b,d,c;c=this.options.tickFormats.top;a=this.options.tickFormats.bottom;b=this.options.tickFormats.left;d=this.options.tickFormats.right;this.options.tickFormats.left=c;this.options.tickFormats.right=a;this.options.tickFormats.top=b;this.options.tickFormats.bottom=49+d;return this.draw()};a.prototype.paddingChanged=function(){return this.draw()};return a}(Epoch.Chart.Plot)}).call(this);50+(function(){var e={}.hasOwnProperty,g=function(c,a){function d(){this.constructor=c}for(var b in a)e.call(a,b)&&(c[b]=a[b]);d.prototype=a.prototype;c.prototype=new d;c.__super__=a.prototype;return c};Epoch.Chart.Line=function(c){function a(){return a.__super__.constructor.apply(this,arguments)}g(a,c);a.prototype.line=function(){var a,b,c;c=[this.x(),this.y()];a=c[0];b=c[1];return d3.svg.line().x(function(b){return function(b){return a(b.x)}}(this)).y(function(a){return function(a){return b(a.y)}}(this))};a.prototype.draw=51+function(){var c,b;b=[this.x(),this.y(),this.line()][2];c=this.g.selectAll(".layer").data(this.data,function(a){return a.category});c.select(".line").transition().duration(500).attr("d",function(a){return b(a.values)});c.enter().append("g").attr("class",function(a){return a.className}).append("path").attr("class","line").attr("d",function(a){return b(a.values)});c.exit().transition().duration(750).style("opacity","0").remove();return a.__super__.draw.call(this)};return a}(Epoch.Chart.Plot)}).call(this);52+(function(){var e={}.hasOwnProperty,g=function(c,a){function d(){this.constructor=c}for(var b in a)e.call(a,b)&&(c[b]=a[b]);d.prototype=a.prototype;c.prototype=new d;c.__super__=a.prototype;return c};Epoch.Chart.Pie=function(c){function a(b){this.options=null!=b?b:{};a.__super__.constructor.call(this,this.options=Epoch.Util.defaults(this.options,d));this.pie=d3.layout.pie().sort(null).value(function(a){return a.value});this.arc=d3.svg.arc().outerRadius(function(a){return function(){return Math.max(a.width,53+a.height)/2-a.options.margin}}(this)).innerRadius(function(a){return function(){return a.options.inner}}(this));this.g=this.svg.append("g").attr("transform","translate("+this.width/2+", "+this.height/2+")");this.on("option:margin","marginChanged");this.on("option:inner","innerChanged")}var d;g(a,c);d={margin:10,inner:0};a.prototype.draw=function(){var b;this.g.selectAll(".arc").remove();b=this.g.selectAll(".arc").data(this.pie(this.data),function(a){return a.data.category});b.enter().append("g").attr("class",54+function(a){return"arc pie "+a.data.className});b.select("path").attr("d",this.arc);b.select("text").attr("transform",function(a){return function(b){return"translate("+a.arc.centroid(b)+")"}}(this)).text(function(a){return a.data.label||a.data.category});b.append("path").attr("d",this.arc).each(function(a){return this._current=a});b.append("text").attr("transform",function(a){return function(b){return"translate("+a.arc.centroid(b)+")"}}(this)).attr("dy",".35em").style("text-anchor","middle").text(function(a){return a.data.label||55+a.data.category});return a.__super__.draw.call(this)};a.prototype.marginChanged=function(){return this.draw()};a.prototype.innerChanged=function(){return this.draw()};return a}(Epoch.Chart.SVG)}).call(this);56+(function(){var e={}.hasOwnProperty,g=function(c,a){function d(){this.constructor=c}for(var b in a)e.call(a,b)&&(c[b]=a[b]);d.prototype=a.prototype;c.prototype=new d;c.__super__=a.prototype;return c};Epoch.Chart.Scatter=function(c){function a(b){this.options=null!=b?b:{};a.__super__.constructor.call(this,this.options=Epoch.Util.defaults(this.options,d));this.on("option:radius","radiusChanged")}var d;g(a,c);d={radius:3.5,axes:["top","bottom","left","right"]};a.prototype.draw=function(){var b,c,k,f,57+d;b=[this.x(),this.y()];f=b[0];d=b[1];k=this.options.radius;c=this.g.selectAll(".layer").data(this.data,function(a){return a.category});c.enter().append("g").attr("class",function(a){return a.className});b=c.selectAll(".dot").data(function(a){return a.values});b.transition().duration(500).attr("r",function(a){var b;return null!=(b=a.r)?b:k}).attr("cx",function(a){return f(a.x)}).attr("cy",function(a){return d(a.y)});b.enter().append("circle").attr("class","dot").attr("r",function(a){var b;return null!=58+(b=a.r)?b:k}).attr("cx",function(a){return f(a.x)}).attr("cy",function(a){return d(a.y)});b.exit().transition().duration(750).style("opacity",0).remove();c.exit().transition().duration(750).style("opacity",0).remove();return a.__super__.draw.call(this)};a.prototype.radiusChanged=function(){return this.draw()};return a}(Epoch.Chart.Plot)}).call(this);59+(function(){var e={}.hasOwnProperty,g=function(c,a){function d(){this.constructor=c}for(var b in a)e.call(a,b)&&(c[b]=a[b]);d.prototype=a.prototype;c.prototype=new d;c.__super__=a.prototype;return c};Epoch.Time.Plot=function(c){function a(k){var f,c,u;this.options=k;Epoch.Util.copy(this.options.margins);a.__super__.constructor.call(this,this.options=Epoch.Util.defaults(this.options,b));this._queue=[];this.margins={};u=["top","right","bottom","left"];f=0;for(c=u.length;f<c;f++)k=u[f],this.margins[k]=60+null!=this.options.margins&&null!=this.options.margins[k]?this.options.margins[k]:this.hasAxis(k)?d[k]:6;this.svg=this.el.insert("svg",":first-child").attr("width",this.width).attr("height",this.height).style("z-index","1000");"absolute"!==this.el.style("position")&&"relative"!==this.el.style("position")&&this.el.style("position","relative");this.canvas.style({position:"absolute","z-index":"999"});this._sizeCanvas();this.animation={interval:null,active:!1,delta:function(a){return function(){return-(a.w()/61+a.options.fps)}}(this),tickDelta:function(a){return function(){return-(a.w()/a.pixelRatio/a.options.fps)}}(this),frame:0,duration:this.options.fps};this._buildAxes();this.animationCallback=function(a){return function(){return a._animate()}}(this);this.onAll(h)}var d,b,h;g(a,c);b={fps:24,historySize:120,windowSize:40,queueSize:10,axes:["bottom"],ticks:{time:15,left:5,right:5},tickFormats:{top:Epoch.Formats.seconds,bottom:Epoch.Formats.seconds,left:Epoch.Formats.si,right:Epoch.Formats.si}};d={top:25,62+right:50,bottom:25,left:50};h={"option:margins":"marginsChanged","option:margins.top":"marginsChanged","option:margins.right":"marginsChanged","option:margins.bottom":"marginsChanged","option:margins.left":"marginsChanged","option:axes":"axesChanged","option:ticks":"ticksChanged","option:ticks.top":"ticksChanged","option:ticks.right":"ticksChanged","option:ticks.bottom":"ticksChanged","option:ticks.left":"ticksChanged","option:tickFormats":"tickFormatsChanged","option:tickFormats.top":"tickFormatsChanged",63+"option:tickFormats.right":"tickFormatsChanged","option:tickFormats.bottom":"tickFormatsChanged","option:tickFormats.left":"tickFormatsChanged"};a.prototype._sizeCanvas=function(){this.canvas.attr({width:this.innerWidth(),height:this.innerHeight()});return this.canvas.style({width:""+this.innerWidth()/this.pixelRatio+"px",height:""+this.innerHeight()/this.pixelRatio+"px",top:""+this.margins.top+"px",left:""+this.margins.left+"px"})};a.prototype._buildAxes=function(){this.svg.selectAll(".axis").remove();64+this._prepareTimeAxes();return this._prepareRangeAxes()};a.prototype.setData=function(a){var b,c,d,h,e;this.data=[];e=[];for(d in a)h=a[d],c=Epoch.Util.copy(h),b=Math.max(0,h.values.length-this.options.historySize),c.values=h.values.slice(b),b=["layer"],b.push("category"+((d|0)+1)),null!=h.label&&b.push(Epoch.Util.dasherize(h.label)),c.className=b.join(" "),e.push(this.data.push(c));return e};a.prototype._offsetX=function(){return 0};a.prototype._prepareTimeAxes=function(){var a;this.hasAxis("bottom")&&65+(a=this.bottomAxis=this.svg.append("g").attr("class","x axis bottom canvas").attr("transform","translate("+(this.margins.left-1)+", "+(this.innerHeight()/this.pixelRatio+this.margins.top)+")"),a.append("path").attr("class","domain").attr("d","M0,0H"+(this.innerWidth()/this.pixelRatio+1)));this.hasAxis("top")&&(a=this.topAxis=this.svg.append("g").attr("class","x axis top canvas").attr("transform","translate("+(this.margins.left-1)+", "+this.margins.top+")"),a.append("path").attr("class","domain").attr("d",66+"M0,0H"+(this.innerWidth()/this.pixelRatio+1)));return this._resetInitialTimeTicks()};a.prototype._resetInitialTimeTicks=function(){var a,b,c,d,h;d=this.options.ticks.time;this._ticks=[];this._tickTimer=d;null!=this.bottomAxis&&this.bottomAxis.selectAll(".tick").remove();null!=this.topAxis&&this.topAxis.selectAll(".tick").remove();h=this.data;a=0;for(b=h.length;a<b;a++)if(c=h[a],null!=c.values&&0<c.values.length){b=[this.options.windowSize-1,c.values.length-1];a=b[0];for(b=b[1];0<=a&&0<=b;)this._pushTick(a,67+c.values[b].time,!1,!0),a-=d,b-=d;break}return[]};a.prototype._prepareRangeAxes=function(){this.hasAxis("left")&&this.svg.append("g").attr("class","y axis left").attr("transform","translate("+(this.margins.left-1)+", "+this.margins.top+")").call(this.leftAxis());if(this.hasAxis("right"))return this.svg.append("g").attr("class","y axis right").attr("transform","translate("+(this.width-this.margins.right)+", "+this.margins.top+")").call(this.rightAxis())};a.prototype.leftAxis=function(){var a,b;b=this.options.ticks.left;68+a=d3.svg.axis().scale(this.ySvg()).orient("left").tickFormat(this.options.tickFormats.left);return 2===b?a.tickValues(this.extent(function(a){return a.y})):a.ticks(b)};a.prototype.rightAxis=function(){var a,b;this.extent(function(a){return a.y});b=this.options.ticks.right;a=d3.svg.axis().scale(this.ySvg()).orient("right").tickFormat(this.options.tickFormats.left);return 2===b?a.tickValues(this.extent(function(a){return a.y})):a.ticks(b)};a.prototype.hasAxis=function(a){return-1<this.options.axes.indexOf(a)};69+a.prototype.innerWidth=function(){return(this.width-(this.margins.left+this.margins.right))*this.pixelRatio};a.prototype.innerHeight=function(){return(this.height-(this.margins.top+this.margins.bottom))*this.pixelRatio};a.prototype._prepareEntry=function(a){return a};a.prototype._prepareLayers=function(a){return a};a.prototype._startTransition=function(){if(!0!==this.animation.active&&0!==this._queue.length)return this.trigger("transition:start"),this._shift(),this.animation.active=!0,this.animation.interval=70+setInterval(this.animationCallback,1E3/this.options.fps)};a.prototype._stopTransition=function(){var a,b,c,d;if(this.inTransition()){d=this.data;b=0;for(c=d.length;b<c;b++)a=d[b],a.values.length>this.options.windowSize+1&&a.values.shift();b=[this._ticks[0],this._ticks[this._ticks.length-1]];a=b[0];b=b[1];null!=b&&b.enter&&(b.enter=!1,b.opacity=1);null!=a&&a.exit&&this._shiftTick();this.animation.frame=0;this.trigger("transition:end");if(0<this._queue.length)return this._shift();this.animation.active=71+!1;return clearInterval(this.animation.interval)}};a.prototype.inTransition=function(){return this.animation.active};a.prototype.push=function(a){a=this._prepareLayers(a);this._queue.length>this.options.queueSize&&this._queue.splice(this.options.queueSize,this._queue.length-this.options.queueSize);if(this._queue.length===this.options.queueSize)return!1;this._queue.push(a.map(function(a){return function(b){return a._prepareEntry(b)}}(this)));this.trigger("push");if(!this.inTransition())return this._startTransition()};72+a.prototype._shift=function(){var a,b,c,d;this.trigger("before:shift");a=this._queue.shift();d=this.data;for(b in d)c=d[b],c.values.push(a[b]);this._updateTicks(a[0].time);this._transitionRangeAxes();return this.trigger("after:shift")};a.prototype._transitionRangeAxes=function(){this.hasAxis("left")&&this.svg.selectAll(".y.axis.left").transition().duration(500).ease("linear").call(this.leftAxis());if(this.hasAxis("right"))return this.svg.selectAll(".y.axis.right").transition().duration(500).ease("linear").call(this.rightAxis())};73+a.prototype._animate=function(){if(this.inTransition())return++this.animation.frame===this.animation.duration&&this._stopTransition(),this.draw(this.animation.frame*this.animation.delta()),this._updateTimeAxes()};a.prototype.y=function(){return d3.scale.linear().domain(this.extent(function(a){return a.y})).range([this.innerHeight(),0])};a.prototype.ySvg=function(){return d3.scale.linear().domain(this.extent(function(a){return a.y})).range([this.innerHeight()/this.pixelRatio,0])};a.prototype.w=function(){return this.innerWidth()/74+this.options.windowSize};a.prototype._updateTicks=function(a){if(this.hasAxis("top")||this.hasAxis("bottom"))if(++this._tickTimer%this.options.ticks.time||this._pushTick(this.options.windowSize,a,!0),!(0<=this._ticks[0].x-this.w()/this.pixelRatio))return this._ticks[0].exit=!0};a.prototype._pushTick=function(a,b,c,d){null==c&&(c=!1);null==d&&(d=!1);if(this.hasAxis("top")||this.hasAxis("bottom"))return b={time:b,x:a*(this.w()/this.pixelRatio)+this._offsetX(),opacity:c?0:1,enter:c?!0:!1,exit:!1},this.hasAxis("bottom")&&75+(a=this.bottomAxis.append("g").attr("class","tick major").attr("transform","translate("+(b.x+1)+",0)").style("opacity",b.opacity),a.append("line").attr("y2",6),a.append("text").attr("text-anchor","middle").attr("dy",19).text(this.options.tickFormats.bottom(b.time)),b.bottomEl=a),this.hasAxis("top")&&(a=this.topAxis.append("g").attr("class","tick major").attr("transform","translate("+(b.x+1)+",0)").style("opacity",b.opacity),a.append("line").attr("y2",-6),a.append("text").attr("text-anchor","middle").attr("dy",76+-10).text(this.options.tickFormats.top(b.time)),b.topEl=a),d?this._ticks.unshift(b):this._ticks.push(b),b};a.prototype._shiftTick=function(){var a;if(0<this._ticks.length&&(a=this._ticks.shift(),null!=a.topEl&&a.topEl.remove(),null!=a.bottomEl))return a.bottomEl.remove()};a.prototype._updateTimeAxes=function(){var a,b,c,d,h,e,g;if(this.hasAxis("top")||this.hasAxis("bottom")){a=[this.animation.tickDelta(),1/this.options.fps];b=a[0];a=a[1];e=this._ticks;g=[];d=0;for(h=e.length;d<h;d++)c=e[d],c.x+=b,77+this.hasAxis("bottom")&&c.bottomEl.attr("transform","translate("+(c.x+1)+",0)"),this.hasAxis("top")&&c.topEl.attr("transform","translate("+(c.x+1)+",0)"),c.enter?c.opacity+=a:c.exit&&(c.opacity-=a),c.enter||c.exit?(this.hasAxis("bottom")&&c.bottomEl.style("opacity",c.opacity),this.hasAxis("top")?g.push(c.topEl.style("opacity",c.opacity)):g.push(void 0)):g.push(void 0);return g}};a.prototype.draw=function(b){return a.__super__.draw.call(this)};a.prototype.dimensionsChanged=function(){a.__super__.dimensionsChanged.call(this);78+this.svg.attr("width",this.width).attr("height",this.height);this._sizeCanvas();this._buildAxes();return this.draw(this.animation.frame*this.animation.delta())};a.prototype.axesChanged=function(){var a,b,c,h;h=["top","right","bottom","left"];b=0;for(c=h.length;b<c;b++)if(a=h[b],null==this.options.margins||null==this.options.margins[a])this.hasAxis(a)?this.margins[a]=d[a]:this.margins[a]=6;this._sizeCanvas();this._buildAxes();return this.draw(this.animation.frame*this.animation.delta())};a.prototype.ticksChanged=79+function(){this._resetInitialTimeTicks();this._transitionRangeAxes();return this.draw(this.animation.frame*this.animation.delta())};a.prototype.tickFormatsChanged=function(){this._resetInitialTimeTicks();this._transitionRangeAxes();return this.draw(this.animation.frame*this.animation.delta())};a.prototype.marginsChanged=function(){var a,b,c;if(null!=this.options.margins){c=this.options.margins;for(a in c)b=c[a],this.margins[a]=null==b?6:b;this._sizeCanvas();return this.draw(this.animation.frame*this.animation.delta())}};80+return a}(Epoch.Chart.Canvas);Epoch.Time.Stack=function(c){function a(){return a.__super__.constructor.apply(this,arguments)}g(a,c);a.prototype._prepareLayers=function(a){var b,c,k,f;k=c=0;for(f=a.length;k<f;k++)b=a[k],b.y0=c,c+=b.y;return a};a.prototype.setData=function(c){var b,h,k,f,e;a.__super__.setData.call(this,c);e=[];b=c=0;for(f=this.data[0].values.length;0<=f?c<f:c>f;b=0<=f?++c:--c)k=0,e.push(function(){var a,c,d,f;d=this.data;f=[];a=0;for(c=d.length;a<c;a++)h=d[a],h.values[b].y0=k,f.push(k+=81+h.values[b].y);return f}.call(this));return e};a.prototype.extent=function(){var a,b,c,k,f,e,g,m;a=f=c=0;for(g=this.data[0].values.length;0<=g?f<g:f>g;a=0<=g?++f:--f){b=e=k=0;for(m=this.data.length;0<=m?e<m:e>m;b=0<=m?++e:--e)k+=this.data[b].values[a].y;k>c&&(c=k)}return[0,c]};return a}(Epoch.Time.Plot)}).call(this);82+(function(){var e={}.hasOwnProperty,g=function(c,a){function d(){this.constructor=c}for(var b in a)e.call(a,b)&&(c[b]=a[b]);d.prototype=a.prototype;c.prototype=new d;c.__super__=a.prototype;return c};Epoch.Time.Area=function(c){function a(){return a.__super__.constructor.apply(this,arguments)}g(a,c);a.prototype.setStyles=function(a){a=null!=a.className?this.getStyles("g."+a.className.replace(/\s/g,".")+" path.area"):this.getStyles("g path.area");this.ctx.fillStyle=a.fill;null!=a.stroke&&(this.ctx.strokeStyle=83+a.stroke);if(null!=a["stroke-width"])return this.ctx.lineWidth=a["stroke-width"].replace("px","")};a.prototype._drawAreas=function(a){var b,c,k,f,e,g,m,l,n,p;null==a&&(a=0);g=[this.y(),this.w()];m=g[0];g=g[1];p=[];for(c=l=n=this.data.length-1;0>=n?0>=l:0<=l;c=0>=n?++l:--l){f=this.data[c];this.setStyles(f);this.ctx.beginPath();e=[this.options.windowSize,f.values.length,this.inTransition()];c=e[0];k=e[1];for(e=e[2];-2<=--c&&0<=--k;)b=f.values[k],b=[(c+1)*g+a,m(b.y+b.y0)],e&&(b[0]+=g),c===this.options.windowSize-84+1?this.ctx.moveTo.apply(this.ctx,b):this.ctx.lineTo.apply(this.ctx,b);c=e?(c+3)*g+a:(c+2)*g+a;this.ctx.lineTo(c,this.innerHeight());this.ctx.lineTo(this.width*this.pixelRatio+g+a,this.innerHeight());this.ctx.closePath();p.push(this.ctx.fill())}return p};a.prototype._drawStrokes=function(a){var b,c,k,f,e,g,m,l,n,p;null==a&&(a=0);c=[this.y(),this.w()];m=c[0];g=c[1];p=[];for(c=l=n=this.data.length-1;0>=n?0>=l:0<=l;c=0>=n?++l:--l){f=this.data[c];this.setStyles(f);this.ctx.beginPath();e=[this.options.windowSize,85+f.values.length,this.inTransition()];c=e[0];k=e[1];for(e=e[2];-2<=--c&&0<=--k;)b=f.values[k],b=[(c+1)*g+a,m(b.y+b.y0)],e&&(b[0]+=g),c===this.options.windowSize-1?this.ctx.moveTo.apply(this.ctx,b):this.ctx.lineTo.apply(this.ctx,b);p.push(this.ctx.stroke())}return p};a.prototype.draw=function(c){null==c&&(c=0);this.clear();this._drawAreas(c);this._drawStrokes(c);return a.__super__.draw.call(this)};return a}(Epoch.Time.Stack)}).call(this);86+(function(){var e={}.hasOwnProperty,g=function(c,a){function d(){this.constructor=c}for(var b in a)e.call(a,b)&&(c[b]=a[b]);d.prototype=a.prototype;c.prototype=new d;c.__super__=a.prototype;return c};Epoch.Time.Bar=function(c){function a(){return a.__super__.constructor.apply(this,arguments)}g(a,c);a.prototype._offsetX=function(){return 0.5*this.w()/this.pixelRatio};a.prototype.setStyles=function(a){a=this.getStyles("rect.bar."+a.replace(/\s/g,"."));this.ctx.fillStyle=a.fill;this.ctx.strokeStyle=87+null==a.stroke||"none"===a.stroke?"transparent":a.stroke;if(null!=a["stroke-width"])return this.ctx.lineWidth=a["stroke-width"].replace("px","")};a.prototype.draw=function(c){var b,h,k,f,e,g,m,l,n,p,r,s,t;null==c&&(c=0);this.clear();f=[this.y(),this.w()];p=f[0];n=f[1];t=this.data;r=0;for(s=t.length;r<s;r++)if(m=t[r],0<m.values.length)for(this.setStyles(m.className),e=[this.options.windowSize,m.values.length,this.inTransition()],f=e[0],g=e[1],e=(l=e[2])?-1:0;--f>=e&&0<=--g;)b=m.values[g],k=[f*n+c,88+b.y,b.y0],b=k[0],h=k[1],k=k[2],l&&(b+=n),b=[b+1,p(h+k),n-2,this.innerHeight()-p(h)+0.5*this.pixelRatio],this.ctx.fillRect.apply(this.ctx,b),this.ctx.strokeRect.apply(this.ctx,b);return a.__super__.draw.call(this)};return a}(Epoch.Time.Stack)}).call(this);89+(function(){var e={}.hasOwnProperty,g=function(c,a){function d(){this.constructor=c}for(var b in a)e.call(a,b)&&(c[b]=a[b]);d.prototype=a.prototype;c.prototype=new d;c.__super__=a.prototype;return c};Epoch.Time.Gauge=function(c){function a(c){this.options=null!=c?c:{};a.__super__.constructor.call(this,this.options=Epoch.Util.defaults(this.options,d));this.value=this.options.value||0;"absolute"!==this.el.style("position")&&"relative"!==this.el.style("position")&&this.el.style("position","relative");90+this.svg=this.el.insert("svg",":first-child").attr("width",this.width).attr("height",this.height).attr("class","gauge-labels");this.svg.style({position:"absolute","z-index":"1"});this.svg.append("g").attr("transform","translate("+this.textX()+", "+this.textY()+")").append("text").attr("class","value").text(this.options.format(this.value));this.animation={interval:null,active:!1,delta:0,target:0};this._animate=function(a){return function(){Math.abs(a.animation.target-a.value)<Math.abs(a.animation.delta)?91+(a.value=a.animation.target,clearInterval(a.animation.interval),a.animation.active=!1):a.value+=a.animation.delta;a.svg.select("text.value").text(a.options.format(a.value));return a.draw()}}(this);this.onAll(b)}var d,b;g(a,c);d={domain:[0,1],ticks:10,tickSize:5,tickOffset:5,fps:34,format:Epoch.Formats.percent};b={"option:domain":"domainChanged","option:ticks":"ticksChanged","option:tickSize":"tickSizeChanged","option:tickOffset":"tickOffsetChanged","option:format":"formatChanged"};a.prototype.update=92+function(a){this.animation.target=a;this.animation.delta=(a-this.value)/this.options.fps;if(!this.animation.active)return this.animation.interval=setInterval(this._animate,1E3/this.options.fps),this.animation.active=!0};a.prototype.push=function(a){return this.update(a)};a.prototype.radius=function(){return this.getHeight()/1.58};a.prototype.centerX=function(){return this.getWidth()/2};a.prototype.centerY=function(){return 0.68*this.getHeight()};a.prototype.textX=function(){return this.width/2};a.prototype.textY=93+function(){return 0.48*this.height};a.prototype.getAngle=function(a){var b,c;c=this.options.domain;b=c[0];return(a-b)/(c[1]-b)*(Math.PI+2*Math.PI/8)-Math.PI/2-Math.PI/8};a.prototype.setStyles=function(a){a=this.getStyles(a);this.ctx.fillStyle=a.fill;this.ctx.strokeStyle=a.stroke;if(null!=a["stroke-width"])return this.ctx.lineWidth=a["stroke-width"].replace("px","")};a.prototype.draw=function(){var b,c,d,e,g,m,l,n,p,r,s,t;g=[this.centerX(),this.centerY(),this.radius()];d=g[0];e=g[1];g=g[2];l=[this.options.tickOffset,94+this.options.tickSize];n=l[0];p=l[1];this.clear();l=d3.scale.linear().domain([0,this.options.ticks]).range([-1.125*Math.PI,Math.PI/8]);this.setStyles(".epoch .gauge .tick");this.ctx.beginPath();b=s=0;for(t=this.options.ticks;0<=t?s<=t:s>=t;b=0<=t?++s:--s)b=l(b),b=[Math.cos(b),Math.sin(b)],c=b[0],m=b[1],b=c*(g-n)+d,r=m*(g-n)+e,c=c*(g-n-p)+d,m=m*(g-n-p)+e,this.ctx.moveTo(b,r),this.ctx.lineTo(c,m);this.ctx.stroke();this.setStyles(".epoch .gauge .arc.outer");this.ctx.beginPath();this.ctx.arc(d,e,g,-1.125*95+Math.PI,0.125*Math.PI,!1);this.ctx.stroke();this.setStyles(".epoch .gauge .arc.inner");this.ctx.beginPath();this.ctx.arc(d,e,g-10,-1.125*Math.PI,0.125*Math.PI,!1);this.ctx.stroke();this.drawNeedle();return a.__super__.draw.call(this)};a.prototype.drawNeedle=function(){var a,b,c;c=[this.centerX(),this.centerY(),this.radius()];a=c[0];b=c[1];c=c[2];this.setStyles(".epoch .gauge .needle");this.ctx.beginPath();this.ctx.save();this.ctx.translate(a,b);this.ctx.rotate(this.getAngle(this.value));this.ctx.moveTo(4*96+this.pixelRatio,0);this.ctx.lineTo(-4*this.pixelRatio,0);this.ctx.lineTo(-1*this.pixelRatio,19-c);this.ctx.lineTo(1,19-c);this.ctx.fill();this.setStyles(".epoch .gauge .needle-base");this.ctx.beginPath();this.ctx.arc(0,0,this.getWidth()/25,0,2*Math.PI);this.ctx.fill();return this.ctx.restore()};a.prototype.domainChanged=function(){return this.draw()};a.prototype.ticksChanged=function(){return this.draw()};a.prototype.tickSizeChanged=function(){return this.draw()};a.prototype.tickOffsetChanged=function(){return this.draw()};97+a.prototype.formatChanged=function(){return this.svg.select("text.value").text(this.options.format(this.value))};return a}(Epoch.Chart.Canvas)}).call(this);98+(function(){var e={}.hasOwnProperty,g=function(c,a){function d(){this.constructor=c}for(var b in a)e.call(a,b)&&(c[b]=a[b]);d.prototype=a.prototype;c.prototype=new d;c.__super__=a.prototype;return c};Epoch.Time.Heatmap=function(c){function a(c){this.options=c;a.__super__.constructor.call(this,this.options=Epoch.Util.defaults(this.options,b));this._setOpacityFunction();this._setupPaintCanvas();this.onAll(e)}var d,b,e;g(a,c);b={buckets:10,bucketRange:[0,100],opacity:"linear",bucketPadding:2,paintZeroValues:!1,99+cutOutliers:!1};d={root:function(a,b){return Math.pow(a/b,0.5)},linear:function(a,b){return a/b},quadratic:function(a,b){return Math.pow(a/b,2)},cubic:function(a,b){return Math.pow(a/b,3)},quartic:function(a,b){return Math.pow(a/b,4)},quintic:function(a,b){return Math.pow(a/b,5)}};e={"option:buckets":"bucketsChanged","option:bucketRange":"bucketRangeChanged","option:opacity":"opacityChanged","option:bucketPadding":"bucketPaddingChanged","option:paintZeroValues":"paintZeroValuesChanged","option:cutOutliers":"cutOutliersChanged"};100+a.prototype._setOpacityFunction=function(){if(Epoch.isString(this.options.opacity)){if(this._opacityFn=d[this.options.opacity],null==this._opacityFn)return Epoch.exception("Unknown coloring function provided '"+this.options.opacity+"'")}else return Epoch.isFunction(this.options.opacity)?this._opacityFn=this.options.opacity:Epoch.exception("Unknown type for provided coloring function.")};a.prototype.setData=function(b){var c,d,e,g;a.__super__.setData.call(this,b);e=this.data;g=[];c=0;for(d=e.length;c<101+d;c++)b=e[c],g.push(b.values=b.values.map(function(a){return function(b){return a._prepareEntry(b)}}(this)));return g};a.prototype._getBuckets=function(a){var b,c,d,e,g;e=a.time;g=[];b=0;for(d=this.options.buckets;0<=d?b<d:b>d;0<=d?++b:--b)g.push(0);e={time:e,max:0,buckets:g};b=(this.options.bucketRange[1]-this.options.bucketRange[0])/this.options.buckets;g=a.histogram;for(c in g)a=g[c],d=parseInt((c-this.options.bucketRange[0])/b),this.options.cutOutliers&&(0>d||d>=this.options.buckets)||(0>d?d=102+0:d>=this.options.buckets&&(d=this.options.buckets-1),e.buckets[d]+=parseInt(a));c=a=0;for(b=e.buckets.length;0<=b?a<b:a>b;c=0<=b?++a:--a)e.max=Math.max(e.max,e.buckets[c]);return e};a.prototype.y=function(){return d3.scale.linear().domain(this.options.bucketRange).range([this.innerHeight(),0])};a.prototype.ySvg=function(){return d3.scale.linear().domain(this.options.bucketRange).range([this.innerHeight()/this.pixelRatio,0])};a.prototype.h=function(){return this.innerHeight()/this.options.buckets};103+a.prototype._offsetX=function(){return 0.5*this.w()/this.pixelRatio};a.prototype._setupPaintCanvas=function(){this.paintWidth=(this.options.windowSize+1)*this.w();this.paintHeight=this.height*this.pixelRatio;this.paint=document.createElement("CANVAS");this.paint.width=this.paintWidth;this.paint.height=this.paintHeight;this.p=Epoch.Util.getContext(this.paint);this.redraw();this.on("after:shift","_paintEntry");this.on("transition:end","_shiftPaintCanvas");return this.on("transition:end",function(a){return function(){return a.draw(a.animation.frame*104+a.animation.delta())}}(this))};a.prototype.redraw=function(){var a,b;b=this.data[0].values.length;a=this.options.windowSize;for(this.inTransition()&&a++;0<=--b&&0<=--a;)this._paintEntry(b,a);return this.draw(this.animation.frame*this.animation.delta())};a.prototype._computeColor=function(a,b,c){return Epoch.Util.toRGBA(c,this._opacityFn(a,b))};a.prototype._paintEntry=function(a,b){var c,d,e,g,h,p,r,s,t,v,y,w,A,z;null==a&&(a=null);null==b&&(b=null);g=[this.w(),this.h()];y=g[0];p=g[1];null==a&&(a=this.data[0].values.length-105+1);null==b&&(b=this.options.windowSize);g=[];var x;x=[];h=0;for(v=this.options.buckets;0<=v?h<v:h>v;0<=v?++h:--h)x.push(0);v=0;t=this.data;d=0;for(r=t.length;d<r;d++){s=t[d];h=this._getBuckets(s.values[a]);w=h.buckets;for(c in w)e=w[c],x[c]+=e;v+=h.max;e=this.getStyles("."+s.className.split(" ").join(".")+" rect.bucket");h.color=e.fill;g.push(h)}s=b*y;this.p.clearRect(s,0,y,this.paintHeight);r=this.options.buckets;z=[];for(c in x){e=x[c];d=this._avgLab(g,c);w=t=0;for(A=g.length;w<A;w++)h=g[w],t+=106+h.buckets[c]/e*v;if(0<e||this.options.paintZeroValues)this.p.fillStyle=this._computeColor(e,t,d),this.p.fillRect(s,(r-1)*p,y-this.options.bucketPadding,p-this.options.bucketPadding);z.push(r--)}return z};a.prototype._shiftPaintCanvas=function(){var a;a=this.p.getImageData(this.w(),0,this.paintWidth-this.w(),this.paintHeight);return this.p.putImageData(a,0,0)};a.prototype._avgLab=function(a,b){var c,d,e,g,h,p,r,s;r=[0,0,0,0];h=r[0];c=r[1];d=r[2];r=r[3];p=0;for(s=a.length;p<s;p++)e=a[p],null!=e.buckets[b]&&107+(r+=e.buckets[b]);for(g in a)e=a[g],p=null!=e.buckets[b]?e.buckets[b]|0:0,p/=r,e=d3.lab(e.color),h+=p*e.l,c+=p*e.a,d+=p*e.b;return d3.lab(h,c,d).toString()};a.prototype.draw=function(b){null==b&&(b=0);this.clear();this.ctx.drawImage(this.paint,b,0);return a.__super__.draw.call(this)};a.prototype.bucketsChanged=function(){return this.redraw()};a.prototype.bucketRangeChanged=function(){this._transitionRangeAxes();return this.redraw()};a.prototype.opacityChanged=function(){this._setOpacityFunction();108+return this.redraw()};a.prototype.bucketPaddingChanged=function(){return this.redraw()};a.prototype.paintZeroValuesChanged=function(){return this.redraw()};a.prototype.cutOutliersChanged=function(){return this.redraw()};return a}(Epoch.Time.Plot)}).call(this);109+(function(){var e={}.hasOwnProperty,g=function(c,a){function d(){this.constructor=c}for(var b in a)e.call(a,b)&&(c[b]=a[b]);d.prototype=a.prototype;c.prototype=new d;c.__super__=a.prototype;return c};Epoch.Time.Line=function(c){function a(){return a.__super__.constructor.apply(this,arguments)}g(a,c);a.prototype.setStyles=function(a){a=this.getStyles("g."+a.replace(/\s/g,".")+" path.line");this.ctx.fillStyle=a.fill;this.ctx.strokeStyle=a.stroke;return this.ctx.lineWidth=this.pixelRatio*a["stroke-width"].replace("px",110+"")};a.prototype.y=function(){return d3.scale.linear().domain(this.extent(function(a){return a.y})).range([this.innerHeight()-this.pixelRatio/2,this.pixelRatio])};a.prototype.draw=function(c){var b,e,g,f,q,u,m,l,n,p;null==c&&(c=0);this.clear();e=[this.y(),this.w()];m=e[0];u=e[1];p=this.data;l=0;for(n=p.length;l<n;l++)if(f=p[l],0<f.values.length){this.setStyles(f.className);this.ctx.beginPath();q=[this.options.windowSize,f.values.length,this.inTransition()];e=q[0];g=q[1];for(q=q[2];-2<=--e&&0<=--g;)b=111+f.values[g],b=[(e+1)*u+c,m(b.y)],q&&(b[0]+=u),e===this.options.windowSize-1?this.ctx.moveTo.apply(this.ctx,b):this.ctx.lineTo.apply(this.ctx,b);this.ctx.stroke()}return a.__super__.draw.call(this)};return a}(Epoch.Time.Plot)}).call(this);(function(){Epoch._typeMap={area:Epoch.Chart.Area,bar:Epoch.Chart.Bar,line:Epoch.Chart.Line,pie:Epoch.Chart.Pie,scatter:Epoch.Chart.Scatter,"time.area":Epoch.Time.Area,"time.bar":Epoch.Time.Bar,"time.line":Epoch.Time.Line,"time.gauge":Epoch.Time.Gauge,"time.heatmap":Epoch.Time.Heatmap}}).call(this);112+(function(){null!=window.MooTools&&function(){return Element.implement("epoch",function(e){var g,c;c=$$(this);null==(g=c.retrieve("epoch-chart")[0])&&(e.el=this,g=Epoch._typeMap[e.type],null==g&&Epoch.exception("Unknown chart type '"+e.type+"'"),c.store("epoch-chart",g=new g(e)),g.draw());return g})}()}).call(this);113+(function(){var e;e=function(e){return e.fn.epoch=function(c){var a;c.el=this.get(0);null==(a=this.data("epoch-chart"))&&(a=Epoch._typeMap[c.type],null==a&&Epoch.exception("Unknown chart type '"+c.type+"'"),this.data("epoch-chart",a=new a(c)),a.draw());return a}};null!=window.jQuery&&e(jQuery)}).call(this);114+(function(){var e;e=function(e){var c,a,d;a={};c=0;d=function(){return"epoch-chart-"+ ++c};return e.extend(e.fn,{epoch:function(b){var c,e;if(null!=(c=this.data("epoch-chart")))return a[c];b.el=this.get(0);e=Epoch._typeMap[b.type];null==e&&Epoch.exception("Unknown chart type '"+b.type+"'");this.data("epoch-chart",c=d());b=new e(b);a[c]=b;b.draw();return b}})};null!=window.Zepto&&e(Zepto)}).call(this);added:examples/realtime-advanced/resources/static/prismjs.min.css+137 added
1+/* http://prismjs.com/download.html?themes=prism&languages=clike+javascript+go */2+/**3+ * prism.js default theme for JavaScript, CSS and HTML4+ * Based on dabblet (http://dabblet.com)5+ * @author Lea Verou6+ */7+8+code[class*="language-"],9+pre[class*="language-"] {10+ color: black;11+ text-shadow: 0 1px white;12+ font-family: Consolas, Monaco, 'Andale Mono', monospace;13+ direction: ltr;14+ text-align: left;15+ white-space: pre;16+ word-spacing: normal;17+ word-break: normal;18+ line-height: 1.5;19+20+ -moz-tab-size: 4;21+ -o-tab-size: 4;22+ tab-size: 4;23+24+ -webkit-hyphens: none;25+ -moz-hyphens: none;26+ -ms-hyphens: none;27+ hyphens: none;28+}29+30+pre[class*="language-"]::-moz-selection, pre[class*="language-"] ::-moz-selection,31+code[class*="language-"]::-moz-selection, code[class*="language-"] ::-moz-selection {32+ text-shadow: none;33+ background: #b3d4fc;34+}35+36+pre[class*="language-"]::selection, pre[class*="language-"] ::selection,37+code[class*="language-"]::selection, code[class*="language-"] ::selection {38+ text-shadow: none;39+ background: #b3d4fc;40+}41+42+@media print {43+ code[class*="language-"],44+ pre[class*="language-"] {45+ text-shadow: none;46+ }47+}48+49+/* Code blocks */50+pre[class*="language-"] {51+ padding: 1em;52+ margin: .5em 0;53+ overflow: auto;54+}55+56+:not(pre) > code[class*="language-"],57+pre[class*="language-"] {58+ background: #f5f2f0;59+}60+61+/* Inline code */62+:not(pre) > code[class*="language-"] {63+ padding: .1em;64+ border-radius: .3em;65+}66+67+.token.comment,68+.token.prolog,69+.token.doctype,70+.token.cdata {71+ color: slategray;72+}73+74+.token.punctuation {75+ color: #999;76+}77+78+.namespace {79+ opacity: .7;80+}81+82+.token.property,83+.token.tag,84+.token.boolean,85+.token.number,86+.token.constant,87+.token.symbol,88+.token.deleted {89+ color: #905;90+}91+92+.token.selector,93+.token.attr-name,94+.token.string,95+.token.char,96+.token.builtin,97+.token.inserted {98+ color: #690;99+}100+101+.token.operator,102+.token.entity,103+.token.url,104+.language-css .token.string,105+.style .token.string {106+ color: #a67f59;107+ background: hsla(0, 0%, 100%, .5);108+}109+110+.token.atrule,111+.token.attr-value,112+.token.keyword {113+ color: #07a;114+}115+116+.token.function {117+ color: #DD4A68;118+}119+120+.token.regex,121+.token.important,122+.token.variable {123+ color: #e90;124+}125+126+.token.important,127+.token.bold {128+ font-weight: bold;129+}130+.token.italic {131+ font-style: italic;132+}133+134+.token.entity {135+ cursor: help;136+}137+added:examples/realtime-advanced/resources/static/prismjs.min.js+5 added
1+/* http://prismjs.com/download.html?themes=prism&languages=clike+javascript+go */2+self="undefined"!=typeof window?window:"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?self:{};var Prism=function(){var e=/\blang(?:uage)?-(?!\*)(\w+)\b/i,t=self.Prism={util:{encode:function(e){return e instanceof n?new n(e.type,t.util.encode(e.content),e.alias):"Array"===t.util.type(e)?e.map(t.util.encode):e.replace(/&/g,"&").replace(/</g,"<").replace(/\u00a0/g," ")},type:function(e){return Object.prototype.toString.call(e).match(/\[object (\w+)\]/)[1]},clone:function(e){var n=t.util.type(e);switch(n){case"Object":var a={};for(var r in e)e.hasOwnProperty(r)&&(a[r]=t.util.clone(e[r]));return a;case"Array":return e.map(function(e){return t.util.clone(e)})}return e}},languages:{extend:function(e,n){var a=t.util.clone(t.languages[e]);for(var r in n)a[r]=n[r];return a},insertBefore:function(e,n,a,r){r=r||t.languages;var i=r[e];if(2==arguments.length){a=arguments[1];for(var l in a)a.hasOwnProperty(l)&&(i[l]=a[l]);return i}var s={};for(var o in i)if(i.hasOwnProperty(o)){if(o==n)for(var l in a)a.hasOwnProperty(l)&&(s[l]=a[l]);s[o]=i[o]}return t.languages.DFS(t.languages,function(t,n){n===r[e]&&t!=e&&(this[t]=s)}),r[e]=s},DFS:function(e,n,a){for(var r in e)e.hasOwnProperty(r)&&(n.call(e,r,e[r],a||r),"Object"===t.util.type(e[r])?t.languages.DFS(e[r],n):"Array"===t.util.type(e[r])&&t.languages.DFS(e[r],n,r))}},highlightAll:function(e,n){for(var a,r=document.querySelectorAll('code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code'),i=0;a=r[i++];)t.highlightElement(a,e===!0,n)},highlightElement:function(a,r,i){for(var l,s,o=a;o&&!e.test(o.className);)o=o.parentNode;if(o&&(l=(o.className.match(e)||[,""])[1],s=t.languages[l]),s){a.className=a.className.replace(e,"").replace(/\s+/g," ")+" language-"+l,o=a.parentNode,/pre/i.test(o.nodeName)&&(o.className=o.className.replace(e,"").replace(/\s+/g," ")+" language-"+l);var u=a.textContent;if(u){u=u.replace(/^(?:\r?\n|\r)/,"");var g={element:a,language:l,grammar:s,code:u};if(t.hooks.run("before-highlight",g),r&&self.Worker){var c=new Worker(t.filename);c.onmessage=function(e){g.highlightedCode=n.stringify(JSON.parse(e.data),l),t.hooks.run("before-insert",g),g.element.innerHTML=g.highlightedCode,i&&i.call(g.element),t.hooks.run("after-highlight",g)},c.postMessage(JSON.stringify({language:g.language,code:g.code}))}else g.highlightedCode=t.highlight(g.code,g.grammar,g.language),t.hooks.run("before-insert",g),g.element.innerHTML=g.highlightedCode,i&&i.call(a),t.hooks.run("after-highlight",g)}}},highlight:function(e,a,r){var i=t.tokenize(e,a);return n.stringify(t.util.encode(i),r)},tokenize:function(e,n){var a=t.Token,r=[e],i=n.rest;if(i){for(var l in i)n[l]=i[l];delete n.rest}e:for(var l in n)if(n.hasOwnProperty(l)&&n[l]){var s=n[l];s="Array"===t.util.type(s)?s:[s];for(var o=0;o<s.length;++o){var u=s[o],g=u.inside,c=!!u.lookbehind,f=0,h=u.alias;u=u.pattern||u;for(var p=0;p<r.length;p++){var d=r[p];if(r.length>e.length)break e;if(!(d instanceof a)){u.lastIndex=0;var m=u.exec(d);if(m){c&&(f=m[1].length);var y=m.index-1+f,m=m[0].slice(f),v=m.length,k=y+v,b=d.slice(0,y+1),w=d.slice(k+1),N=[p,1];b&&N.push(b);var O=new a(l,g?t.tokenize(m,g):m,h);N.push(O),w&&N.push(w),Array.prototype.splice.apply(r,N)}}}}}return r},hooks:{all:{},add:function(e,n){var a=t.hooks.all;a[e]=a[e]||[],a[e].push(n)},run:function(e,n){var a=t.hooks.all[e];if(a&&a.length)for(var r,i=0;r=a[i++];)r(n)}}},n=t.Token=function(e,t,n){this.type=e,this.content=t,this.alias=n};if(n.stringify=function(e,a,r){if("string"==typeof e)return e;if("Array"===t.util.type(e))return e.map(function(t){return n.stringify(t,a,e)}).join("");var i={type:e.type,content:n.stringify(e.content,a,r),tag:"span",classes:["token",e.type],attributes:{},language:a,parent:r};if("comment"==i.type&&(i.attributes.spellcheck="true"),e.alias){var l="Array"===t.util.type(e.alias)?e.alias:[e.alias];Array.prototype.push.apply(i.classes,l)}t.hooks.run("wrap",i);var s="";for(var o in i.attributes)s+=o+'="'+(i.attributes[o]||"")+'"';return"<"+i.tag+' class="'+i.classes.join(" ")+'" '+s+">"+i.content+"</"+i.tag+">"},!self.document)return self.addEventListener?(self.addEventListener("message",function(e){var n=JSON.parse(e.data),a=n.language,r=n.code;self.postMessage(JSON.stringify(t.util.encode(t.tokenize(r,t.languages[a])))),self.close()},!1),self.Prism):self.Prism;var a=document.getElementsByTagName("script");return a=a[a.length-1],a&&(t.filename=a.src,document.addEventListener&&!a.hasAttribute("data-manual")&&document.addEventListener("DOMContentLoaded",t.highlightAll)),self.Prism}();"undefined"!=typeof module&&module.exports&&(module.exports=Prism);;3+Prism.languages.clike={comment:[{pattern:/(^|[^\\])\/\*[\w\W]*?\*\//,lookbehind:!0},{pattern:/(^|[^\\:])\/\/.*/,lookbehind:!0}],string:/("|')(\\\n|\\?.)*?\1/,"class-name":{pattern:/((?:(?:class|interface|extends|implements|trait|instanceof|new)\s+)|(?:catch\s+\())[a-z0-9_\.\\]+/i,lookbehind:!0,inside:{punctuation:/(\.|\\)/}},keyword:/\b(if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/,"boolean":/\b(true|false)\b/,"function":{pattern:/[a-z0-9_]+\(/i,inside:{punctuation:/\(/}},number:/\b-?(0x[\dA-Fa-f]+|\d*\.?\d+([Ee]-?\d+)?)\b/,operator:/[-+]{1,2}|!|<=?|>=?|={1,3}|&{1,2}|\|?\||\?|\*|\/|~|\^|%/,ignore:/&(lt|gt|amp);/i,punctuation:/[{}[\];(),.:]/};;4+Prism.languages.javascript=Prism.languages.extend("clike",{keyword:/\b(break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|false|finally|for|function|get|if|implements|import|in|instanceof|interface|let|new|null|package|private|protected|public|return|set|static|super|switch|this|throw|true|try|typeof|var|void|while|with|yield)\b/,number:/\b-?(0x[\dA-Fa-f]+|\d*\.?\d+([Ee][+-]?\d+)?|NaN|-?Infinity)\b/,"function":/(?!\d)[a-z0-9_$]+(?=\()/i}),Prism.languages.insertBefore("javascript","keyword",{regex:{pattern:/(^|[^/])\/(?!\/)(\[.+?]|\\.|[^/\r\n])+\/[gim]{0,3}(?=\s*($|[\r\n,.;})]))/,lookbehind:!0}}),Prism.languages.markup&&Prism.languages.insertBefore("markup","tag",{script:{pattern:/<script[\w\W]*?>[\w\W]*?<\/script>/i,inside:{tag:{pattern:/<script[\w\W]*?>|<\/script>/i,inside:Prism.languages.markup.tag.inside},rest:Prism.languages.javascript},alias:"language-javascript"}});;5+Prism.languages.go=Prism.languages.extend("clike",{keyword:/\b(break|case|chan|const|continue|default|defer|else|fallthrough|for|func|go(to)?|if|import|interface|map|package|range|return|select|struct|switch|type|var)\b/,builtin:/\b(bool|byte|complex(64|128)|error|float(32|64)|rune|string|u?int(8|16|32|64|)|uintptr|append|cap|close|complex|copy|delete|imag|len|make|new|panic|print(ln)?|real|recover)\b/,"boolean":/\b(_|iota|nil|true|false)\b/,operator:/([(){}\[\]]|[*\/%^!]=?|\+[=+]?|-[>=-]?|\|[=|]?|>[=>]?|<(<|[=-])?|==?|&(&|=|^=?)?|\.(\.\.)?|[,;]|:=?)/,number:/\b(-?(0x[a-f\d]+|(\d+\.?\d*|\.\d+)(e[-+]?\d+)?)i?)\b/i,string:/("|'|`)(\\?.|\r|\n)*?\1/}),delete Prism.languages.go["class-name"];;added:examples/realtime-advanced/resources/static/realtime.js+144 added
1+2+3+function StartRealtime(roomid, timestamp) {4+ StartEpoch(timestamp);5+ StartSSE(roomid);6+ StartForm();7+}8+9+function StartForm() {10+ $('#chat-message').focus();11+ $('#chat-form').ajaxForm(function() {12+ $('#chat-message').val('');13+ $('#chat-message').focus();14+ });15+}16+17+function StartEpoch(timestamp) {18+ var windowSize = 60;19+ var height = 200;20+ var defaultData = histogram(windowSize, timestamp);21+22+ window.heapChart = $('#heapChart').epoch({23+ type: 'time.area',24+ axes: ['bottom', 'left'],25+ height: height,26+ historySize: 10,27+ data: [28+ {values: defaultData},29+ {values: defaultData}30+ ]31+ });32+33+ window.mallocsChart = $('#mallocsChart').epoch({34+ type: 'time.area',35+ axes: ['bottom', 'left'],36+ height: height,37+ historySize: 10,38+ data: [39+ {values: defaultData},40+ {values: defaultData}41+ ]42+ });43+44+ window.messagesChart = $('#messagesChart').epoch({45+ type: 'time.line',46+ axes: ['bottom', 'left'],47+ height: 240,48+ historySize: 10,49+ data: [50+ {values: defaultData},51+ {values: defaultData},52+ {values: defaultData}53+ ]54+ });55+}56+57+function StartSSE(roomid) {58+ if (!window.EventSource) {59+ alert("EventSource is not enabled in this browser");60+ return;61+ }62+ var source = new EventSource('/stream/'+roomid);63+ source.addEventListener('message', newChatMessage, false);64+ source.addEventListener('stats', stats, false);65+}66+67+function stats(e) {68+ var data = parseJSONStats(e.data);69+ heapChart.push(data.heap);70+ mallocsChart.push(data.mallocs);71+ messagesChart.push(data.messages);72+}73+74+function parseJSONStats(e) {75+ var data = jQuery.parseJSON(e);76+ var timestamp = data.timestamp;77+78+ var heap = [79+ {time: timestamp, y: data.HeapInuse},80+ {time: timestamp, y: data.StackInuse}81+ ];82+83+ var mallocs = [84+ {time: timestamp, y: data.Mallocs},85+ {time: timestamp, y: data.Frees}86+ ];87+ var messages = [88+ {time: timestamp, y: data.Connected},89+ {time: timestamp, y: data.Inbound},90+ {time: timestamp, y: data.Outbound}91+ ];92+93+ return {94+ heap: heap,95+ mallocs: mallocs,96+ messages: messages97+ }98+}99+100+function newChatMessage(e) {101+ var data = jQuery.parseJSON(e.data);102+ var nick = data.nick;103+ var message = data.message;104+ var style = rowStyle(nick);105+ var html = "<tr class=\""+style+"\"><td>"+nick+"</td><td>"+message+"</td></tr>";106+ $('#chat').append(html);107+108+ $("#chat-scroll").scrollTop($("#chat-scroll")[0].scrollHeight);109+}110+111+function histogram(windowSize, timestamp) {112+ var entries = new Array(windowSize);113+ for(var i = 0; i < windowSize; i++) {114+ entries[i] = {time: (timestamp-windowSize+i-1), y:0};115+ }116+ return entries;117+}118+119+var entityMap = {120+ "&": "&",121+ "<": "<",122+ ">": ">",123+ '"': '"',124+ "'": ''',125+ "/": '/'126+};127+128+function rowStyle(nick) {129+ var classes = ['active', 'success', 'info', 'warning', 'danger'];130+ var index = hashCode(nick)%5;131+ return classes[index];132+}133+134+function hashCode(s){135+ return Math.abs(s.split("").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0)); 136+}137+138+function escapeHtml(string) {139+ return String(string).replace(/[&<>"'\/]/g, function (s) {140+ return entityMap[s];141+ });142+}143+144+window.StartRealtime = StartRealtimeadded:examples/realtime-advanced/resources/room_login.templ.html+208 added
1+<!DOCTYPE html>2+<html lang="en">3+ <head>4+ <meta charset="utf-8">5+ <meta http-equiv="X-UA-Compatible" content="IE=edge">6+ <meta name="viewport" content="width=device-width, initial-scale=1">7+ <title>Server-Sent Events. Room "{{.roomid}}"</title>8+ <!-- jQuery -->9+ <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>10+ <script src="http://malsup.github.com/jquery.form.js"></script> 11+ <!-- EPOCH -->12+ <script src="http://d3js.org/d3.v3.min.js"></script>13+ <script src="/static/epoch.min.js"></script>14+ <link rel="stylesheet" href="/static/epoch.min.css">15+ <script src="/static/realtime.js"></script>16+ <!-- Latest compiled and minified CSS -->17+ <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">18+ <!-- Optional theme -->19+ <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">20+ <!-- Latest compiled and minified JavaScript -->21+ <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>22+ <!-- Primjs -->23+ <link href="/static/prismjs.min.css" rel="stylesheet" />24+25+ <script type="text/javascript">26+ $(document).ready(function() { 27+ StartRealtime({{.roomid}}, {{.timestamp}});28+ });29+ </script>30+ <style>31+ body { padding-top: 50px; }32+ </style>33+ </head>34+ <body>35+ <nav class="navbar navbar-fixed-top navbar-inverse">36+ <div class="container">37+ <div class="navbar-header">38+ <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">39+ <span class="sr-only">Toggle navigation</span>40+ <span class="icon-bar"></span>41+ <span class="icon-bar"></span>42+ <span class="icon-bar"></span>43+ </button>44+ <a class="navbar-brand" href="#">Server-Sent Events</a>45+ </div>46+ <div id="navbar" class="collapse navbar-collapse">47+ <ul class="nav navbar-nav">48+ <li class="active"><a href="#">Demo</a></li>49+ <li><a href="http://www.w3.org/TR/2009/WD-eventsource-20091029/">W3 Standard</a></li>50+ <li><a href="http://caniuse.com/#feat=eventsource">Browser Support</a></li>51+ <li><a href="http://gin-gonic.github.io/gin/">Gin Framework</a></li>52+ <li><a href="https://github.com/gin-gonic/gin/tree/develop/examples/realtime-advanced">Github</a></li>53+ </ul>54+ </div><!-- /.nav-collapse -->55+ </div><!-- /.container -->56+ </nav><!-- /.navbar -->57+ <!-- Main jumbotron for a primary marketing message or call to action -->58+ <div class="jumbotron">59+ <div class="container">60+ <h1>Server-Sent Events in Go</h1>61+ <p>Server-sent events (SSE) is a technology where a browser receives automatic updates from a server via HTTP connection. It is not websockets. <a href="http://www.html5rocks.com/en/tutorials/eventsource/basics/">Learn more.</a></p>62+ <p>The chat and the charts data is provided in realtime using the SSE implemention of <a href="https://github.com/gin-gonic/gin/blob/15b0c49da556d58a3d934b86e3aa552ff224026d/examples/realtime-chat/main.go#L23-L32">Gin Framework</a>.</p>63+ <div class="row">64+ <div class="col-md-8">65+ <div id="chat-scroll" style="overflow-y:scroll; overflow-x:scroll; height:290px">66+ <table id="table-style" class="table" data-show-header="false">67+ <thead>68+ <tr>69+ <th data-field="nick" class="col-md-2">Nick</th>70+ <th data-field="message" class="col-md-8">Message</th>71+ </tr>72+ </thead>73+ <tbody id="chat"></tbody>74+ </table>75+ </div>76+ {{if .nick}}77+ <form autocomplete="off" class="form-inline" id="chat-form" action="/room-post/{{.roomid}}?nick={{.nick}}" method="post">78+ <div class="form-group">79+ <label class="sr-only" for="chat-message">Message</label>80+ <div class="input-group">81+ <div class="input-group-addon">{{.nick}}</div>82+ <input type="text" name="message" id="chat-message" class="form-control" placeholder="a message" value="" />83+ </div>84+ </div>85+ <input type="submit" class="btn btn-primary" value="Send" />86+ </form>87+ {{else}}88+ <form action="" method="get" class="form-inline">89+ <legend>Join the SSE real-time chat</legend>90+ <div class="form-group">91+ <input value='' name="nick" id="nick" placeholder="Your Name" type="text" class="form-control" />92+ </div>93+ <div class="form-group text-center">94+ <input type="submit" class="btn btn-success btn-login-submit" value="Join" />95+ </div>96+ </form>97+ {{end}}98+ </div>99+ <div class="col-md-4">100+ <div id="messagesChart" class="epoch category10"></div>101+ <p>102+ <span style="font-size:20px; color:#1f77b4">◼︎</span> Users<br>103+ <span style="font-size:20px; color:#ff7f0e">◼︎</span> Inbound messages / sec<br>104+ <span style="font-size:20px; color:#2ca02c">◼︎</span> Outbound messages / sec<br>105+ </p>106+ </div>107+ </div>108+ </div>109+ </div>110+ <div class="container">111+ <div class="row">112+ <h2>Realtime server Go stats</h2>113+ <div class="col-md-6">114+ <h3>Memory usage</h3>115+ <p>116+ <div id="heapChart" class="epoch category20c"></div>117+ </p>118+ <p>119+ <span style="font-size:20px; color:#1f77b4">◼︎</span> Heap bytes<br>120+ <span style="font-size:20px; color:#aec7e8">◼︎</span> Stack bytes<br>121+ </p>122+ </div>123+ <div class="col-md-6">124+ <h3>Allocations per second</h3>125+ <p>126+ <div id="mallocsChart" class="epoch category20b"></div>127+ </p>128+ <p>129+ <span style="font-size:20px; color:#393b79">◼︎</span> Mallocs / sec<br>130+ <span style="font-size:20px; color:#5254a3">◼︎</span> Frees / sec<br>131+ </p>132+ </div>133+ </div>134+ <div class="row">135+ <h2>MIT Open Sourced</h2>136+ <ul>137+ <li><a href="https://github.com/gin-gonic/gin/tree/develop/examples/realtime-advanced">This demo website (JS and Go)</a></li>138+ <li><a href="https://github.com/manucorporat/sse">The SSE implementation in Go</a></li>139+ <li><a href="https://github.com/gin-gonic/gin">The Web Framework (Gin)</a></li>140+ </ul>141+ <div class="col-md-6">142+ <script src="/static/prismjs.min.js"></script>143+ <h3>Server-side (Go)</h3>144+ <pre><code class="language-go">func streamRoom(c *gin.Context) {145+ roomid := c.ParamValue("roomid")146+ listener := openListener(roomid)147+ statsTicker := time.NewTicker(1 * time.Second)148+ defer closeListener(roomid, listener)149+ defer statsTicker.Stop()150+151+ c.Stream(func(w io.Writer) bool {152+ select {153+ case msg := <-listener:154+ c.SSEvent("message", msg)155+ case <-statsTicker.C:156+ c.SSEvent("stats", Stats())157+ }158+ return true159+ })160+}</code></pre>161+ </div>162+ <div class="col-md-6">163+ <h3>Client-side (JS)</h3>164+ <pre><code class="language-javascript">function StartSSE(roomid) {165+ var source = new EventSource('/stream/'+roomid);166+ source.addEventListener('message', newChatMessage, false);167+ source.addEventListener('stats', stats, false);168+}</code></pre>169+ </div>170+ </div>171+ <div class="row">172+ <div class="col-md-12">173+ <h3>SSE package</h3>174+ <pre><code class="language-go">import "github.com/manucorporat/sse"175+176+func httpHandler(w http.ResponseWriter, req *http.Request) {177+ // data can be a primitive like a string, an integer or a float178+ sse.Encode(w, sse.Event{179+ Event: "message",180+ Data: "some data\nmore data",181+ })182+183+ // also a complex type, like a map, a struct or a slice184+ sse.Encode(w, sse.Event{185+ Id: "124",186+ Event: "message",187+ Data: map[string]interface{}{188+ "user": "manu",189+ "date": time.Now().Unix(),190+ "content": "hi!",191+ },192+ })193+}</code></pre>194+<pre>event: message195+data: some data\\nmore data196+197+id: 124198+event: message199+data: {"content":"hi!","date":1431540810,"user":"manu"}</pre>200+ </div>201+ </div>202+ <hr>203+ <footer>204+ <p>Created with <span class="glyphicon glyphicon-heart"></span> by <a href="https://github.com/manucorporat">Manu Martinez-Almeida</a></p>205+ </footer>206+ </div>207+ </body>208+</html>added:examples/realtime-advanced/main.go+39 added
1+package main2+3+import (4+ "fmt"5+ "runtime"6+7+ "github.com/gin-gonic/gin"8+)9+10+func main() {11+ ConfigRuntime()12+ StartWorkers()13+ StartGin()14+}15+16+func ConfigRuntime() {17+ nuCPU := runtime.NumCPU()18+ runtime.GOMAXPROCS(nuCPU)19+ fmt.Printf("Running with %d CPUs\n", nuCPU)20+}21+22+func StartWorkers() {23+ go statsWorker()24+}25+26+func StartGin() {27+ gin.SetMode(gin.ReleaseMode)28+29+ router := gin.New()30+ router.Use(rateLimit, gin.Recovery())31+ router.LoadHTMLGlob("resources/*.templ.html")32+ router.Static("/static", "resources/static")33+ router.GET("/", index)34+ router.GET("/room/:roomid", roomGET)35+ router.POST("/room-post/:roomid", roomPOST)36+ router.GET("/stream/:roomid", streamRoom)37+38+ router.Run(":80")39+}added:examples/realtime-advanced/rooms.go+25 added
1+package main2+3+import "github.com/dustin/go-broadcast"4+5+var roomChannels = make(map[string]broadcast.Broadcaster)6+7+func openListener(roomid string) chan interface{} {8+ listener := make(chan interface{})9+ room(roomid).Register(listener)10+ return listener11+}12+13+func closeListener(roomid string, listener chan interface{}) {14+ room(roomid).Unregister(listener)15+ close(listener)16+}17+18+func room(roomid string) broadcast.Broadcaster {19+ b, ok := roomChannels[roomid]20+ if !ok {21+ b = broadcast.NewBroadcaster(10)22+ roomChannels[roomid] = b23+ }24+ return b25+}added:examples/realtime-advanced/routes.go+96 added
1+package main2+3+import (4+ "fmt"5+ "html"6+ "io"7+ "strings"8+ "time"9+10+ "github.com/gin-gonic/gin"11+)12+13+func rateLimit(c *gin.Context) {14+15+ ip := c.ClientIP()16+ value := int(ips.Add(ip, 1))17+ if value%50 == 0 {18+ fmt.Printf("ip: %s, count: %d\n", ip, value)19+ }20+ if value >= 200 {21+ if value%200 == 0 {22+ fmt.Println("ip blocked")23+ }24+ c.Abort()25+ c.String(503, "you were automatically banned :)")26+ }27+}28+29+func index(c *gin.Context) {30+ c.Redirect(301, "/room/hn")31+}32+33+func roomGET(c *gin.Context) {34+ roomid := c.ParamValue("roomid")35+ nick := c.FormValue("nick")36+ if len(nick) < 2 {37+ nick = ""38+ }39+ if len(nick) > 13 {40+ nick = nick[0:12] + "..."41+ }42+ c.HTML(200, "room_login.templ.html", gin.H{43+ "roomid": roomid,44+ "nick": nick,45+ "timestamp": time.Now().Unix(),46+ })47+48+}49+50+func roomPOST(c *gin.Context) {51+ roomid := c.ParamValue("roomid")52+ nick := c.FormValue("nick")53+ message := c.PostFormValue("message")54+ message = strings.TrimSpace(message)55+56+ validMessage := len(message) > 1 && len(message) < 20057+ validNick := len(nick) > 1 && len(nick) < 1458+ if !validMessage || !validNick {59+ c.JSON(400, gin.H{60+ "status": "failed",61+ "error": "the message or nickname is too long",62+ })63+ return64+ }65+66+ post := gin.H{67+ "nick": html.EscapeString(nick),68+ "message": html.EscapeString(message),69+ }70+ messages.Add("inbound", 1)71+ room(roomid).Submit(post)72+ c.JSON(200, post)73+}74+75+func streamRoom(c *gin.Context) {76+ roomid := c.ParamValue("roomid")77+ listener := openListener(roomid)78+ ticker := time.NewTicker(1 * time.Second)79+ users.Add("connected", 1)80+ defer func() {81+ closeListener(roomid, listener)82+ ticker.Stop()83+ users.Add("disconnected", 1)84+ }()85+86+ c.Stream(func(w io.Writer) bool {87+ select {88+ case msg := <-listener:89+ messages.Add("outbound", 1)90+ c.SSEvent("message", msg)91+ case <-ticker.C:92+ c.SSEvent("stats", Stats())93+ }94+ return true95+ })96+}added:examples/realtime-advanced/stats.go+56 added
1+package main2+3+import (4+ "runtime"5+ "sync"6+ "time"7+8+ "github.com/manucorporat/stats"9+)10+11+var ips = stats.New()12+var messages = stats.New()13+var users = stats.New()14+var mutexStats sync.RWMutex15+var savedStats map[string]uint6416+17+func statsWorker() {18+ c := time.Tick(1 * time.Second)19+ var lastMallocs uint64 = 020+ var lastFrees uint64 = 021+ for range c {22+ var stats runtime.MemStats23+ runtime.ReadMemStats(&stats)24+25+ mutexStats.Lock()26+ savedStats = map[string]uint64{27+ "timestamp": uint64(time.Now().Unix()),28+ "HeapInuse": stats.HeapInuse,29+ "StackInuse": stats.StackInuse,30+ "Mallocs": (stats.Mallocs - lastMallocs),31+ "Frees": (stats.Frees - lastFrees),32+ "Inbound": uint64(messages.Get("inbound")),33+ "Outbound": uint64(messages.Get("outbound")),34+ "Connected": connectedUsers(),35+ }36+ lastMallocs = stats.Mallocs37+ lastFrees = stats.Frees38+ messages.Reset()39+ mutexStats.Unlock()40+ }41+}42+43+func connectedUsers() uint64 {44+ connected := users.Get("connected") - users.Get("disconnected")45+ if connected < 0 {46+ return 047+ }48+ return uint64(connected)49+}50+51+func Stats() map[string]uint64 {52+ mutexStats.RLock()53+ defer mutexStats.RUnlock()54+55+ return savedStats56+}added:examples/realtime-chat/main.go+58 added
1+package main2+3+import (4+ "fmt"5+ "io"6+ "math/rand"7+8+ "github.com/gin-gonic/gin"9+)10+11+func main() {12+ router := gin.Default()13+ router.SetHTMLTemplate(html)14+15+ router.GET("/room/:roomid", roomGET)16+ router.POST("/room/:roomid", roomPOST)17+ router.DELETE("/room/:roomid", roomDELETE)18+ router.GET("/stream/:roomid", stream)19+20+ router.Run(":8080")21+}22+23+func stream(c *gin.Context) {24+ roomid := c.ParamValue("roomid")25+ listener := openListener(roomid)26+ defer closeListener(roomid, listener)27+28+ c.Stream(func(w io.Writer) bool {29+ c.SSEvent("message", <-listener)30+ return true31+ })32+}33+34+func roomGET(c *gin.Context) {35+ roomid := c.ParamValue("roomid")36+ userid := fmt.Sprint(rand.Int31())37+ c.HTML(200, "chat_room", gin.H{38+ "roomid": roomid,39+ "userid": userid,40+ })41+}42+43+func roomPOST(c *gin.Context) {44+ roomid := c.ParamValue("roomid")45+ userid := c.PostFormValue("user")46+ message := c.PostFormValue("message")47+ room(roomid).Submit(userid + ": " + message)48+49+ c.JSON(200, gin.H{50+ "status": "success",51+ "message": message,52+ })53+}54+55+func roomDELETE(c *gin.Context) {56+ roomid := c.ParamValue("roomid")57+ deleteBroadcast(roomid)58+}added:examples/realtime-chat/rooms.go+33 added
1+package main2+3+import "github.com/dustin/go-broadcast"4+5+var roomChannels = make(map[string]broadcast.Broadcaster)6+7+func openListener(roomid string) chan interface{} {8+ listener := make(chan interface{})9+ room(roomid).Register(listener)10+ return listener11+}12+13+func closeListener(roomid string, listener chan interface{}) {14+ room(roomid).Unregister(listener)15+ close(listener)16+}17+18+func deleteBroadcast(roomid string) {19+ b, ok := roomChannels[roomid]20+ if ok {21+ b.Close()22+ delete(roomChannels, roomid)23+ }24+}25+26+func room(roomid string) broadcast.Broadcaster {27+ b, ok := roomChannels[roomid]28+ if !ok {29+ b = broadcast.NewBroadcaster(10)30+ roomChannels[roomid] = b31+ }32+ return b33+}added:examples/realtime-chat/template.go+44 added
1+package main2+3+import "html/template"4+5+var html = template.Must(template.New("chat_room").Parse(`6+<html> 7+<head> 8+ <title>{{.roomid}}</title>9+ <link rel="stylesheet" type="text/css" href="http://meyerweb.com/eric/tools/css/reset/reset.css"/>10+ <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script> 11+ <script src="http://malsup.github.com/jquery.form.js"></script> 12+ <script> 13+ $('#message_form').focus();14+ $(document).ready(function() { 15+ // bind 'myForm' and provide a simple callback function 16+ $('#myForm').ajaxForm(function() {17+ $('#message_form').val('');18+ $('#message_form').focus();19+ });20+21+ if (!!window.EventSource) {22+ var source = new EventSource('/stream/{{.roomid}}');23+ source.addEventListener('message', function(e) {24+ $('#messages').append(e.data + "</br>");25+ $('html, body').animate({scrollTop:$(document).height()}, 'slow');26+27+ }, false);28+ } else {29+ alert("NOT SUPPORTED");30+ }31+ });32+ </script> 33+ </head>34+ <body>35+ <h1>Welcome to {{.roomid}} room</h1>36+ <div id="messages"></div>37+ <form id="myForm" action="/room/{{.roomid}}" method="post"> 38+ User: <input id="user_form" name="user" value="{{.userid}}"></input> 39+ Message: <input id="message_form" name="message"></input> 40+ <input type="submit" value="Submit" /> 41+ </form>42+</body>43+</html>44+`))deleted:examples/example_basic.go-56 removed
1-package main2-3-import (4- "github.com/gin-gonic/gin"5-)6-7-var DB = make(map[string]string)8-9-func main() {10- r := gin.Default()11-12- // Ping test13- r.GET("/ping", func(c *gin.Context) {14- c.String(200, "pong")15- })16-17- // Get user value18- r.GET("/user/:name", func(c *gin.Context) {19- user := c.Params.ByName("name")20- value, ok := DB[user]21- if ok {22- c.JSON(200, gin.H{"user": user, "value": value})23- } else {24- c.JSON(200, gin.H{"user": user, "status": "no value"})25- }26- })27-28- // Authorized group (uses gin.BasicAuth() middleware)29- // Same than:30- // authorized := r.Group("/")31- // authorized.Use(gin.BasicAuth(gin.Credentials{32- // "foo": "bar",33- // "manu": "123",34- //}))35- authorized := r.Group("/", gin.BasicAuth(gin.Accounts{36- "foo": "bar", // user:foo password:bar37- "manu": "123", // user:manu password:12338- }))39-40- authorized.POST("admin", func(c *gin.Context) {41- user := c.MustGet(gin.AuthUserKey).(string)42-43- // Parse JSON44- var json struct {45- Value string `json:"value" binding:"required"`46- }47-48- if c.Bind(&json) {49- DB[user] = json.Value50- c.JSON(200, gin.H{"status": "ok"})51- }52- })53-54- // Listen and Server in 0.0.0.0:808055- r.Run(":8080")56-}modified:Godeps/Godeps.json+20 added-3 removed
1 {2 "ImportPath": "github.com/gin-gonic/gin",3- "GoVersion": "go1.3",3+ "GoVersion": "go1.4.2",4 "Deps": [5 {6- "ImportPath": "github.com/julienschmidt/httprouter",7- "Rev": "b428fda53bb0a764fea9c76c9413512eda291dec"6+ "ImportPath": "github.com/manucorporat/sse",7+ "Rev": "c574f6c50c8594f93d28b03a1bbd87b4a3899093"8+ },9+ {10+ "ImportPath": "github.com/mattn/go-colorable",11+ "Rev": "043ae16291351db8465272edf465c9f388161627"12+ },13+ {14+ "ImportPath": "github.com/stretchr/testify/assert",15+ "Rev": "de7fcff264cd05cc0c90c509ea789a436a0dd206"16+ },17+ {18+ "ImportPath": "golang.org/x/net/context",19+ "Rev": "84ba27dd5b2d8135e9da1395277f2c9333a2ffda"20+ },21+ {22+ "ImportPath": "gopkg.in/joeybloggs/go-validate-yourself.v4",23+ "Comment": "v4.0",24+ "Rev": "a3cb430fa1e43b15e72d7bec5b20d0bdff4c2bb8"25 }26 ]27 }added:render/data.go+16 added
1+package render2+3+import "net/http"4+5+type Data struct {6+ ContentType string7+ Data []byte8+}9+10+func (r Data) Write(w http.ResponseWriter) error {11+ if len(r.ContentType) > 0 {12+ w.Header().Set("Content-Type", r.ContentType)13+ }14+ w.Write(r.Data)15+ return nil16+}added:render/html.go+59 added
1+package render2+3+import (4+ "html/template"5+ "net/http"6+)7+8+type (9+ HTMLRender interface {10+ Instance(string, interface{}) Render11+ }12+13+ HTMLProduction struct {14+ Template *template.Template15+ }16+17+ HTMLDebug struct {18+ Files []string19+ Glob string20+ }21+22+ HTML struct {23+ Template *template.Template24+ Name string25+ Data interface{}26+ }27+)28+29+const htmlContentType = "text/html; charset=utf-8"30+31+func (r HTMLProduction) Instance(name string, data interface{}) Render {32+ return HTML{33+ Template: r.Template,34+ Name: name,35+ Data: data,36+ }37+}38+39+func (r HTMLDebug) Instance(name string, data interface{}) Render {40+ return HTML{41+ Template: r.loadTemplate(),42+ Name: name,43+ Data: data,44+ }45+}46+func (r HTMLDebug) loadTemplate() *template.Template {47+ if len(r.Files) > 0 {48+ return template.Must(template.ParseFiles(r.Files...))49+ }50+ if len(r.Glob) > 0 {51+ return template.Must(template.ParseGlob(r.Glob))52+ }53+ panic("the HTML debug render was created without files or glob pattern")54+}55+56+func (r HTML) Write(w http.ResponseWriter) error {57+ w.Header().Set("Content-Type", htmlContentType)58+ return r.Template.ExecuteTemplate(w, r.Name, r.Data)59+}added:render/json.go+33 added
1+package render2+3+import (4+ "encoding/json"5+ "net/http"6+)7+8+type (9+ JSON struct {10+ Data interface{}11+ }12+13+ IndentedJSON struct {14+ Data interface{}15+ }16+)17+18+const jsonContentType = "application/json; charset=utf-8"19+20+func (r JSON) Write(w http.ResponseWriter) error {21+ w.Header().Set("Content-Type", jsonContentType)22+ return json.NewEncoder(w).Encode(r.Data)23+}24+25+func (r IndentedJSON) Write(w http.ResponseWriter) error {26+ w.Header().Set("Content-Type", jsonContentType)27+ jsonBytes, err := json.MarshalIndent(r.Data, "", " ")28+ if err != nil {29+ return err30+ }31+ w.Write(jsonBytes)32+ return nil33+}added:render/redirect.go+20 added
1+package render2+3+import (4+ "fmt"5+ "net/http"6+)7+8+type Redirect struct {9+ Code int10+ Request *http.Request11+ Location string12+}13+14+func (r Redirect) Write(w http.ResponseWriter) error {15+ if r.Code < 300 || r.Code > 308 {16+ panic(fmt.Sprintf("Cannot redirect with status code %d", r.Code))17+ }18+ http.Redirect(w, r.Request, r.Location, r.Code)19+ return nil20+}added:render/render_test.go+130 added
1+// Copyright 2014 Manu Martinez-Almeida. All rights reserved.2+// Use of this source code is governed by a MIT style3+// license that can be found in the LICENSE file.4+5+package render6+7+import (8+ "encoding/xml"9+ "html/template"10+ "net/http/httptest"11+ "testing"12+13+ "github.com/stretchr/testify/assert"14+)15+16+// TODO unit tests17+// test errors18+19+func TestRenderJSON(t *testing.T) {20+ w := httptest.NewRecorder()21+ data := map[string]interface{}{22+ "foo": "bar",23+ }24+25+ err := (JSON{data}).Write(w)26+27+ assert.NoError(t, err)28+ assert.Equal(t, w.Body.String(), "{\"foo\":\"bar\"}\n")29+ assert.Equal(t, w.Header().Get("Content-Type"), "application/json; charset=utf-8")30+}31+32+func TestRenderIndentedJSON(t *testing.T) {33+ w := httptest.NewRecorder()34+ data := map[string]interface{}{35+ "foo": "bar",36+ "bar": "foo",37+ }38+39+ err := (IndentedJSON{data}).Write(w)40+41+ assert.NoError(t, err)42+ assert.Equal(t, w.Body.String(), "{\n \"bar\": \"foo\",\n \"foo\": \"bar\"\n}")43+ assert.Equal(t, w.Header().Get("Content-Type"), "application/json; charset=utf-8")44+}45+46+type xmlmap map[string]interface{}47+48+// Allows type H to be used with xml.Marshal49+func (h xmlmap) MarshalXML(e *xml.Encoder, start xml.StartElement) error {50+ start.Name = xml.Name{51+ Space: "",52+ Local: "map",53+ }54+ if err := e.EncodeToken(start); err != nil {55+ return err56+ }57+ for key, value := range h {58+ elem := xml.StartElement{59+ Name: xml.Name{Space: "", Local: key},60+ Attr: []xml.Attr{},61+ }62+ if err := e.EncodeElement(value, elem); err != nil {63+ return err64+ }65+ }66+ if err := e.EncodeToken(xml.EndElement{Name: start.Name}); err != nil {67+ return err68+ }69+ return nil70+}71+72+func TestRenderXML(t *testing.T) {73+ w := httptest.NewRecorder()74+ data := xmlmap{75+ "foo": "bar",76+ }77+78+ err := (XML{data}).Write(w)79+80+ assert.NoError(t, err)81+ assert.Equal(t, w.Body.String(), "<map><foo>bar</foo></map>")82+ assert.Equal(t, w.Header().Get("Content-Type"), "application/xml; charset=utf-8")83+}84+85+func TestRenderRedirect(t *testing.T) {86+ // TODO87+}88+89+func TestRenderData(t *testing.T) {90+ w := httptest.NewRecorder()91+ data := []byte("#!PNG some raw data")92+93+ err := (Data{94+ ContentType: "image/png",95+ Data: data,96+ }).Write(w)97+98+ assert.NoError(t, err)99+ assert.Equal(t, w.Body.String(), "#!PNG some raw data")100+ assert.Equal(t, w.Header().Get("Content-Type"), "image/png")101+}102+103+func TestRenderString(t *testing.T) {104+ w := httptest.NewRecorder()105+106+ err := (String{107+ Format: "hola %s %d",108+ Data: []interface{}{"manu", 2},109+ }).Write(w)110+111+ assert.NoError(t, err)112+ assert.Equal(t, w.Body.String(), "hola manu 2")113+ assert.Equal(t, w.Header().Get("Content-Type"), "text/plain; charset=utf-8")114+}115+116+func TestRenderHTMLTemplate(t *testing.T) {117+ w := httptest.NewRecorder()118+ templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))119+120+ htmlRender := HTMLProduction{Template: templ}121+ instance := htmlRender.Instance("t", map[string]interface{}{122+ "name": "alexandernyquist",123+ })124+125+ err := instance.Write(w)126+127+ assert.NoError(t, err)128+ assert.Equal(t, w.Body.String(), "Hello alexandernyquist")129+ assert.Equal(t, w.Header().Get("Content-Type"), "text/html; charset=utf-8")130+}modified:render/render.go+13 added-130 removed
2 unmodified lines3 // license that can be found in the LICENSE file.4 5 package render6 7-import (8- "encoding/json"9- "encoding/xml"10- "fmt"11- "html/template"12- "net/http"13-)7+import "net/http"8 15-type (16- Render interface {17- Render(http.ResponseWriter, int, ...interface{}) error18- }9+type Render interface {10+ Write(http.ResponseWriter) error11+}12 20- // JSON binding21- jsonRender struct{}22-23- // XML binding24- xmlRender struct{}25-26- // Plain text27- plainRender struct{}28-29- // HTML Plain text30- htmlPlainRender struct{}31-32- // Redirects33- redirectRender struct{}34-35- // Redirects36- htmlDebugRender struct {37- files []string38- globs []string39- }40-41- // form binding42- HTMLRender struct {43- Template *template.Template44- }45-)46-13 var (48- JSON = jsonRender{}49- XML = xmlRender{}50- Plain = plainRender{}51- HTMLPlain = htmlPlainRender{}52- Redirect = redirectRender{}53- HTMLDebug = &htmlDebugRender{}14+ _ Render = JSON{}15+ _ Render = IndentedJSON{}16+ _ Render = XML{}17+ _ Render = String{}18+ _ Render = Redirect{}19+ _ Render = Data{}20+ _ Render = HTML{}21+ _ HTMLRender = HTMLDebug{}22+ _ HTMLRender = HTMLProduction{}23 )55-56-func writeHeader(w http.ResponseWriter, code int, contentType string) {57- w.Header().Set("Content-Type", contentType+"; charset=utf-8")58- w.WriteHeader(code)59-}60-61-func (_ jsonRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {62- writeHeader(w, code, "application/json")63- encoder := json.NewEncoder(w)64- return encoder.Encode(data[0])65-}66-67-func (_ redirectRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {68- w.Header().Set("Location", data[0].(string))69- w.WriteHeader(code)70- return nil71-}72-73-func (_ xmlRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {74- writeHeader(w, code, "application/xml")75- encoder := xml.NewEncoder(w)76- return encoder.Encode(data[0])77-}78-79-func (_ plainRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {80- writeHeader(w, code, "text/plain")81- format := data[0].(string)82- args := data[1].([]interface{})83- var err error84- if len(args) > 0 {85- _, err = w.Write([]byte(fmt.Sprintf(format, args...)))86- } else {87- _, err = w.Write([]byte(format))88- }89- return err90-}91-92-func (_ htmlPlainRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {93- writeHeader(w, code, "text/html")94- format := data[0].(string)95- args := data[1].([]interface{})96- var err error97- if len(args) > 0 {98- _, err = w.Write([]byte(fmt.Sprintf(format, args...)))99- } else {100- _, err = w.Write([]byte(format))101- }102- return err103-}104-105-func (r *htmlDebugRender) AddGlob(pattern string) {106- r.globs = append(r.globs, pattern)107-}108-109-func (r *htmlDebugRender) AddFiles(files ...string) {110- r.files = append(r.files, files...)111-}112-113-func (r *htmlDebugRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {114- writeHeader(w, code, "text/html")115- file := data[0].(string)116- obj := data[1]117-118- t := template.New("")119-120- if len(r.files) > 0 {121- if _, err := t.ParseFiles(r.files...); err != nil {122- return err123- }124- }125-126- for _, glob := range r.globs {127- if _, err := t.ParseGlob(glob); err != nil {128- return err129- }130- }131-132- return t.ExecuteTemplate(w, file, obj)133-}134-135-func (html HTMLRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {136- writeHeader(w, code, "text/html")137- file := data[0].(string)138- obj := data[1]139- return html.Template.ExecuteTemplate(w, file, obj)140-}added:render/text.go+26 added
1+package render2+3+import (4+ "fmt"5+ "net/http"6+)7+8+type String struct {9+ Format string10+ Data []interface{}11+}12+13+const plainContentType = "text/plain; charset=utf-8"14+15+func (r String) Write(w http.ResponseWriter) error {16+ header := w.Header()17+ if _, exist := header["Content-Type"]; !exist {18+ header.Set("Content-Type", plainContentType)19+ }20+ if len(r.Data) > 0 {21+ fmt.Fprintf(w, r.Format, r.Data...)22+ } else {23+ w.Write([]byte(r.Format))24+ }25+ return nil26+}added:render/xml.go+17 added
1+package render2+3+import (4+ "encoding/xml"5+ "net/http"6+)7+8+type XML struct {9+ Data interface{}10+}11+12+const xmlContentType = "application/xml; charset=utf-8"13+14+func (r XML) Write(w http.ResponseWriter) error {15+ w.Header().Set("Content-Type", xmlContentType)16+ return xml.NewEncoder(w).Encode(r.Data)17+}modified:.gitignore+2 added
1 Godeps/*2 !Godeps/Godeps.json3+coverage.out4+count.outmodified:.travis.yml+15 added-1 removed
1 language: go2 sudo: false3 go:4- - 1.34 - 1.45+ - 1.4.26 - tip7+8+script:9+ - go get golang.org/x/tools/cmd/cover10+ - go get github.com/mattn/goveralls11+ - go test -v -covermode=count -coverprofile=coverage.out12+ - goveralls -coverprofile=coverage.out -service=travis-ci -repotoken yFj7FrCeddvBzUaaCyG33jCLfWXeb93eA13+14+notifications:15+ webhooks:16+ urls:17+ - https://webhooks.gitter.im/e/acc2c57482e94b44f55718+ on_success: change # options: [always|never|change] default: always19+ on_failure: always # options: [always|never|change] default: always20+ on_start: false # default: falsemodified:auth_test.go+109 added-48 removed
7 unmodified lines8 "encoding/base64"9 "net/http"10 "net/http/httptest"11 "testing"12+13+ "github.com/stretchr/testify/assert"14 )15 14-func TestBasicAuthSucceed(t *testing.T) {15- req, _ := http.NewRequest("GET", "/login", nil)16- w := httptest.NewRecorder()16+func TestBasicAuth(t *testing.T) {17+ pairs := processAccounts(Accounts{18+ "admin": "password",19+ "foo": "bar",20+ "bar": "foo",21+ })22 18- r := New()19- accounts := Accounts{"admin": "password"}20- r.Use(BasicAuth(accounts))23+ assert.Len(t, pairs, 3)24+ assert.Contains(t, pairs, authPair{25+ User: "bar",26+ Value: "Basic YmFyOmZvbw==",27+ })28+ assert.Contains(t, pairs, authPair{29+ User: "foo",30+ Value: "Basic Zm9vOmJhcg==",31+ })32+ assert.Contains(t, pairs, authPair{33+ User: "admin",34+ Value: "Basic YWRtaW46cGFzc3dvcmQ=",35+ })36+}37 22- r.GET("/login", func(c *Context) {23- c.String(200, "autorized")38+func TestBasicAuthFails(t *testing.T) {39+ assert.Panics(t, func() { processAccounts(nil) })40+ assert.Panics(t, func() {41+ processAccounts(Accounts{42+ "": "password",43+ "foo": "bar",44+ })45 })46+}47 26- req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("admin:password")))27- r.ServeHTTP(w, req)48+func TestBasicAuthSearchCredential(t *testing.T) {49+ pairs := processAccounts(Accounts{50+ "admin": "password",51+ "foo": "bar",52+ "bar": "foo",53+ })54 29- if w.Code != 200 {30- t.Errorf("Response code should be Ok, was: %s", w.Code)31- }32- bodyAsString := w.Body.String()55+ user, found := pairs.searchCredential(authorizationHeader("admin", "password"))56+ assert.Equal(t, user, "admin")57+ assert.True(t, found)58 34- if bodyAsString != "autorized" {35- t.Errorf("Response body should be `autorized`, was %s", bodyAsString)36- }59+ user, found = pairs.searchCredential(authorizationHeader("foo", "bar"))60+ assert.Equal(t, user, "foo")61+ assert.True(t, found)62+63+ user, found = pairs.searchCredential(authorizationHeader("bar", "foo"))64+ assert.Equal(t, user, "bar")65+ assert.True(t, found)66+67+ user, found = pairs.searchCredential(authorizationHeader("admins", "password"))68+ assert.Empty(t, user)69+ assert.False(t, found)70+71+ user, found = pairs.searchCredential(authorizationHeader("foo", "bar "))72+ assert.Empty(t, user)73+ assert.False(t, found)74+75+ user, found = pairs.searchCredential("")76+ assert.Empty(t, user)77+ assert.False(t, found)78 }79 39-func TestBasicAuth401(t *testing.T) {40- req, _ := http.NewRequest("GET", "/login", nil)80+func TestBasicAuthAuthorizationHeader(t *testing.T) {81+ assert.Equal(t, authorizationHeader("admin", "password"), "Basic YWRtaW46cGFzc3dvcmQ=")82+}83+84+func TestBasicAuthSecureCompare(t *testing.T) {85+ assert.True(t, secureCompare("1234567890", "1234567890"))86+ assert.False(t, secureCompare("123456789", "1234567890"))87+ assert.False(t, secureCompare("12345678900", "1234567890"))88+ assert.False(t, secureCompare("1234567891", "1234567890"))89+}90+91+func TestBasicAuthSucceed(t *testing.T) {92+ accounts := Accounts{"admin": "password"}93+ router := New()94+ router.Use(BasicAuth(accounts))95+ router.GET("/login", func(c *Context) {96+ c.String(200, c.MustGet(AuthUserKey).(string))97+ })98+99 w := httptest.NewRecorder()100+ req, _ := http.NewRequest("GET", "/login", nil)101+ req.Header.Set("Authorization", authorizationHeader("admin", "password"))102+ router.ServeHTTP(w, req)103 43- r := New()44- accounts := Accounts{"foo": "bar"}45- r.Use(BasicAuth(accounts))104+ assert.Equal(t, w.Code, 200)105+ assert.Equal(t, w.Body.String(), "admin")106+}107 47- r.GET("/login", func(c *Context) {48- c.String(200, "autorized")108+func TestBasicAuth401(t *testing.T) {109+ called := false110+ accounts := Accounts{"foo": "bar"}111+ router := New()112+ router.Use(BasicAuth(accounts))113+ router.GET("/login", func(c *Context) {114+ called = true115+ c.String(200, c.MustGet(AuthUserKey).(string))116 })117 118+ w := httptest.NewRecorder()119+ req, _ := http.NewRequest("GET", "/login", nil)120 req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("admin:password")))52- r.ServeHTTP(w, req)121+ router.ServeHTTP(w, req)122 54- if w.Code != 401 {55- t.Errorf("Response code should be Not autorized, was: %s", w.Code)56- }57-58- if w.HeaderMap.Get("WWW-Authenticate") != "Basic realm=\"Authorization Required\"" {59- t.Errorf("WWW-Authenticate header is incorrect: %s", w.HeaderMap.Get("Content-Type"))60- }123+ assert.False(t, called)124+ assert.Equal(t, w.Code, 401)125+ assert.Equal(t, w.HeaderMap.Get("WWW-Authenticate"), "Basic realm=\"Authorization Required\"")126 }127 128 func TestBasicAuth401WithCustomRealm(t *testing.T) {64- req, _ := http.NewRequest("GET", "/login", nil)65- w := httptest.NewRecorder()66-67- r := New()129+ called := false130 accounts := Accounts{"foo": "bar"}69- r.Use(BasicAuthForRealm(accounts, "My Custom Realm"))70-71- r.GET("/login", func(c *Context) {72- c.String(200, "autorized")131+ router := New()132+ router.Use(BasicAuthForRealm(accounts, "My Custom \"Realm\""))133+ router.GET("/login", func(c *Context) {134+ called = true135+ c.String(200, c.MustGet(AuthUserKey).(string))136 })137 138+ w := httptest.NewRecorder()139+ req, _ := http.NewRequest("GET", "/login", nil)140 req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("admin:password")))76- r.ServeHTTP(w, req)141+ router.ServeHTTP(w, req)142 78- if w.Code != 401 {79- t.Errorf("Response code should be Not autorized, was: %s", w.Code)80- }81-82- if w.HeaderMap.Get("WWW-Authenticate") != "Basic realm=\"My Custom Realm\"" {83- t.Errorf("WWW-Authenticate header is incorrect: %s", w.HeaderMap.Get("Content-Type"))84- }143+ assert.False(t, called)144+ assert.Equal(t, w.Code, 401)145+ assert.Equal(t, w.HeaderMap.Get("WWW-Authenticate"), "Basic realm=\"My Custom \\\"Realm\\\"\"")146 }modified:auth.go+31 added-38 removed
5 unmodified lines6 7 import (8 "crypto/subtle"9 "encoding/base64"10- "errors"11- "fmt"12- "sort"10+ "strconv"11 )12 13 const (14 AuthUserKey = "user"7 unmodified lines22 }23 authPairs []authPair24 )25 28-func (a authPairs) Len() int { return len(a) }29-func (a authPairs) Swap(i, j int) { a[i], a[j] = a[j], a[i] }30-func (a authPairs) Less(i, j int) bool { return a[i].Value < a[j].Value }26+func (a authPairs) searchCredential(authValue string) (string, bool) {27+ if len(authValue) == 0 {28+ return "", false29+ }30+ for _, pair := range a {31+ if pair.Value == authValue {32+ return pair.User, true33+ }34+ }35+ return "", false36+}37 38 // Implements a basic Basic HTTP Authorization. It takes as arguments a map[string]string where39 // the key is the user name and the value is the password, as well as the name of the Realm40 // (see http://tools.ietf.org/html/rfc2617#section-1.2)41 func BasicAuthForRealm(accounts Accounts, realm string) HandlerFunc {36- pairs, err := processAccounts(accounts)37- if err != nil {38- panic(err)42+ if realm == "" {43+ realm = "Authorization Required"44 }45+ realm = "Basic realm=" + strconv.Quote(realm)46+ pairs := processAccounts(accounts)47 return func(c *Context) {48 // Search user in the slice of allowed credentials42- user, ok := searchCredential(pairs, c.Request.Header.Get("Authorization"))43- if !ok {44- // Credentials doesn't match, we return 401 Unauthorized and abort request.45- if realm == "" {46- realm = "Authorization Required"47- }48- c.Writer.Header().Set("WWW-Authenticate", fmt.Sprintf("Basic realm=\"%s\"", realm))49- c.Fail(401, errors.New("Unauthorized"))49+ user, found := pairs.searchCredential(c.Request.Header.Get("Authorization"))50+ if !found {51+ // Credentials doesn't match, we return 401 and abort handlers chain.52+ c.Header("WWW-Authenticate", realm)53+ c.AbortWithStatus(401)54 } else {51- // user is allowed, set UserId to key "user" in this context, the userId can be read later using52- // c.Get(gin.AuthUserKey)55+ // The user credentials was found, set user's id to key AuthUserKey in this context, the userId can be read later using56+ // c.MustGet(gin.AuthUserKey)57 c.Set(AuthUserKey, user)58 }59 }60 }3 unmodified lines64 func BasicAuth(accounts Accounts) HandlerFunc {65 return BasicAuthForRealm(accounts, "")66 }67 64-func processAccounts(accounts Accounts) (authPairs, error) {68+func processAccounts(accounts Accounts) authPairs {69 if len(accounts) == 0 {66- return nil, errors.New("Empty list of authorized credentials")70+ panic("Empty list of authorized credentials")71 }72 pairs := make(authPairs, 0, len(accounts))73 for user, password := range accounts {74 if len(user) == 0 {71- return nil, errors.New("User can not be empty")75+ panic("User can not be empty")76 }73- base := user + ":" + password74- value := "Basic " + base64.StdEncoding.EncodeToString([]byte(base))77+ value := authorizationHeader(user, password)78 pairs = append(pairs, authPair{79 Value: value,80 User: user,81 })82 }80- // We have to sort the credentials in order to use bsearch later.81- sort.Sort(pairs)82- return pairs, nil83+ return pairs84 }85 85-func searchCredential(pairs authPairs, auth string) (string, bool) {86- if len(auth) == 0 {87- return "", false88- }89- // Search user in the slice of allowed credentials90- r := sort.Search(len(pairs), func(i int) bool { return pairs[i].Value >= auth })91- if r < len(pairs) && secureCompare(pairs[r].Value, auth) {92- return pairs[r].User, true93- } else {94- return "", false95- }86+func authorizationHeader(user, password string) string {87+ base := user + ":" + password88+ return "Basic " + base64.StdEncoding.EncodeToString([]byte(base))89 }90 91 func secureCompare(given, actual string) bool {92 if subtle.ConstantTimeEq(int32(len(given)), int32(len(actual))) == 1 {6 unmodified linesmodified:AUTHORS.md+1 added-2 removed
2 unmodified lines3 4 5 ##gin 0.x series authors6 7-**Original Developer:** Manu Martinez-Almeida (@manucorporat) 8-**Long-term Maintainer:** Javier Provecho (@javierprovecho)7+**Maintainer:** Manu Martinez-Almeida (@manucorporat), Javier Provecho (@javierprovecho)8 9 People and companies, who have contributed, in alphabetical order.10 11 **@858806258 (杰哥)**218 unmodified linesmodified:CHANGELOG.md+48 added-4 removed
1 #Changelog2 3+###Gin 1.0rc1 (May 22, 2015)4+5+- [PERFORMANCE] Zero allocation router6+- [PERFORMANCE] Faster JSON, XML and text rendering7+- [PERFORMANCE] Custom hand optimized HttpRouter for Gin8+- [PERFORMANCE] Misc code optimizations. Inlining, tail call optimizations9+- [NEW] Built-in support for golang.org/x/net/context10+- [NEW] Any(path, handler). Create a route that matches any path11+- [NEW] Refactored rendering pipeline (faster and static typeded)12+- [NEW] Refactored errors API13+- [NEW] IndentedJSON() prints pretty JSON14+- [NEW] Added gin.DefaultWriter15+- [NEW] UNIX socket support16+- [NEW] RouterGroup.BasePath is exposed17+- [NEW] JSON validation using go-validate-yourself (very powerful options)18+- [NEW] Completed suite of unit tests19+- [NEW] HTTP streaming with c.Stream()20+- [NEW] StaticFile() creates a router for serving just one file.21+- [NEW] StaticFS() has an option to disable directory listing.22+- [NEW] StaticFS() for serving static files through virtual filesystems23+- [NEW] Server-Sent Events native support24+- [NEW] WrapF() and WrapH() helpers for wrapping http.HandlerFunc and http.Handler25+- [NEW] Added LoggerWithWriter() middleware26+- [NEW] Added RecoveryWithWriter() middleware27+- [NEW] Added DefaultPostFormValue()28+- [NEW] Added DefaultFormValue()29+- [NEW] Added DefaultParamValue()30+- [FIX] BasicAuth() when using custom realm31+- [FIX] Bug when serving static files in nested routing group32+- [FIX] Redirect using built-in http.Redirect()33+- [FIX] Logger when printing the requested path34+- [FIX] Documentation typos35+- [FIX] Context.Engine renamed to Context.engine36+- [FIX] Better debugging messages37+- [FIX] ErrorLogger38+- [FIX] Debug HTTP render39+- [FIX] Refactored binding and render modules 40+- [FIX] Refactored Context initialization41+- [FIX] Refactored BasicAuth()42+- [FIX] NoMethod/NoRoute handlers43+- [FIX] Hijacking http44+- [FIX] Better support for Google App Engine (using log instead of fmt)45+46+47 ###Gin 0.6 (Mar 9, 2015)48 5-- [ADD] Support multipart/form-data6-- [ADD] NoMethod handler7-- [ADD] Validate sub structures8-- [ADD] Support for HTTP Realm Auth49+- [NEW] Support multipart/form-data50+- [NEW] NoMethod handler51+- [NEW] Validate sub structures52+- [NEW] Support for HTTP Realm Auth53 - [FIX] Unsigned integers in binding54 - [FIX] Improve color logger55 56 59 unmodified linesmodified:context_test.go+361 added-396 removed
9 unmodified lines10 "html/template"11 "net/http"12 "net/http/httptest"13 "testing"14+ "time"15+16+ "github.com/gin-gonic/gin/binding"17+ "github.com/manucorporat/sse"18+ "github.com/stretchr/testify/assert"19 )20 16-// TestContextParamsGet tests that a parameter can be parsed from the URL.17-func TestContextParamsByName(t *testing.T) {18- req, _ := http.NewRequest("GET", "/test/alexandernyquist", nil)19- w := httptest.NewRecorder()20- name := ""21+// Unit tests TODO22+// func (c *Context) File(filepath string) {23+// func (c *Context) Negotiate(code int, config Negotiate) {24+// BAD case: func (c *Context) Render(code int, render render.Render, obj ...interface{}) {25+// test that information is not leaked when reusing Contexts (using the Pool)26 22- r := New()23- r.GET("/test/:name", func(c *Context) {24- name = c.Params.ByName("name")25- })27+func createTestContext() (c *Context, w *httptest.ResponseRecorder, r *Engine) {28+ w = httptest.NewRecorder()29+ r = New()30+ c = r.allocateContext()31+ c.reset()32+ c.writermem.reset(w)33+ return34+}35 27- r.ServeHTTP(w, req)36+func TestContextReset(t *testing.T) {37+ router := New()38+ c := router.allocateContext()39+ assert.Equal(t, c.engine, router)40 29- if name != "alexandernyquist" {30- t.Errorf("Url parameter was not correctly parsed. Should be alexandernyquist, was %s.", name)31- }41+ c.index = 242+ c.Writer = &responseWriter{ResponseWriter: httptest.NewRecorder()}43+ c.Params = Params{Param{}}44+ c.Error(errors.New("test"))45+ c.Set("foo", "bar")46+ c.reset()47+48+ assert.False(t, c.IsAborted())49+ assert.Nil(t, c.Keys)50+ assert.Nil(t, c.Accepted)51+ assert.Len(t, c.Errors, 0)52+ assert.Empty(t, c.Errors.Errors())53+ assert.Empty(t, c.Errors.ByType(ErrorTypeAny))54+ assert.Len(t, c.Params, 0)55+ assert.Equal(t, c.index, -1)56+ assert.Equal(t, c.Writer.(*responseWriter), &c.writermem)57 }58 59 // TestContextSetGet tests that a parameter is set correctly on the60 // current context and can be retrieved using Get.61 func TestContextSetGet(t *testing.T) {37- req, _ := http.NewRequest("GET", "/test", nil)38- w := httptest.NewRecorder()62+ c, _, _ := createTestContext()63+ c.Set("foo", "bar")64 40- r := New()41- r.GET("/test", func(c *Context) {42- // Key should be lazily created43- if c.Keys != nil {44- t.Error("Keys should be nil")45- }65+ value, err := c.Get("foo")66+ assert.Equal(t, value, "bar")67+ assert.True(t, err)68 47- // Set48- c.Set("foo", "bar")69+ value, err = c.Get("foo2")70+ assert.Nil(t, value)71+ assert.False(t, err)72 50- v, err := c.Get("foo")51- if err != nil {52- t.Errorf("Error on exist key")53- }54- if v != "bar" {55- t.Errorf("Value should be bar, was %s", v)56- }57- })73+ assert.Equal(t, c.MustGet("foo"), "bar")74+ assert.Panics(t, func() { c.MustGet("no_exist") })75+}76 59- r.ServeHTTP(w, req)77+func TestContextSetGetValues(t *testing.T) {78+ c, _, _ := createTestContext()79+ c.Set("string", "this is a string")80+ c.Set("int32", int32(-42))81+ c.Set("int64", int64(42424242424242))82+ c.Set("uint64", uint64(42))83+ c.Set("float32", float32(4.2))84+ c.Set("float64", 4.2)85+ var a interface{} = 186+ c.Set("intInterface", a)87+88+ assert.Exactly(t, c.MustGet("string").(string), "this is a string")89+ assert.Exactly(t, c.MustGet("int32").(int32), int32(-42))90+ assert.Exactly(t, c.MustGet("int64").(int64), int64(42424242424242))91+ assert.Exactly(t, c.MustGet("uint64").(uint64), uint64(42))92+ assert.Exactly(t, c.MustGet("float32").(float32), float32(4.2))93+ assert.Exactly(t, c.MustGet("float64").(float64), 4.2)94+ assert.Exactly(t, c.MustGet("intInterface").(int), 1)95+96 }97 62-// TestContextJSON tests that the response is serialized as JSON63-// and Content-Type is set to application/json64-func TestContextJSON(t *testing.T) {65- req, _ := http.NewRequest("GET", "/test", nil)66- w := httptest.NewRecorder()98+func TestContextCopy(t *testing.T) {99+ c, _, _ := createTestContext()100+ c.index = 2101+ c.Request, _ = http.NewRequest("POST", "/hola", nil)102+ c.handlers = HandlersChain{func(c *Context) {}}103+ c.Params = Params{Param{Key: "foo", Value: "bar"}}104+ c.Set("foo", "bar")105 68- r := New()69- r.GET("/test", func(c *Context) {70- c.JSON(200, H{"foo": "bar"})71- })106+ cp := c.Copy()107+ assert.Nil(t, cp.handlers)108+ assert.Nil(t, cp.writermem.ResponseWriter)109+ assert.Equal(t, &cp.writermem, cp.Writer.(*responseWriter))110+ assert.Equal(t, cp.Request, c.Request)111+ assert.Equal(t, cp.index, AbortIndex)112+ assert.Equal(t, cp.Keys, c.Keys)113+ assert.Equal(t, cp.engine, c.engine)114+ assert.Equal(t, cp.Params, c.Params)115+}116 73- r.ServeHTTP(w, req)117+func TestContextFormParse(t *testing.T) {118+ c, _, _ := createTestContext()119+ c.Request, _ = http.NewRequest("GET", "http://example.com/?foo=bar&page=10", nil)120 75- if w.Body.String() != "{\"foo\":\"bar\"}\n" {76- t.Errorf("Response should be {\"foo\":\"bar\"}, was: %s", w.Body.String())77- }121+ assert.Equal(t, c.DefaultFormValue("foo", "none"), "bar")122+ assert.Equal(t, c.FormValue("foo"), "bar")123+ assert.Empty(t, c.PostFormValue("foo"))124 79- if w.HeaderMap.Get("Content-Type") != "application/json; charset=utf-8" {80- t.Errorf("Content-Type should be application/json, was %s", w.HeaderMap.Get("Content-Type"))81- }125+ assert.Equal(t, c.DefaultFormValue("page", "0"), "10")126+ assert.Equal(t, c.FormValue("page"), "10")127+ assert.Empty(t, c.PostFormValue("page"))128+129+ assert.Equal(t, c.DefaultFormValue("NoKey", "nada"), "nada")130+ assert.Empty(t, c.FormValue("NoKey"))131+ assert.Empty(t, c.PostFormValue("NoKey"))132 }133 84-// TestContextHTML tests that the response executes the templates85-// and responds with Content-Type set to text/html86-func TestContextHTML(t *testing.T) {87- req, _ := http.NewRequest("GET", "/test", nil)88- w := httptest.NewRecorder()134+func TestContextPostFormParse(t *testing.T) {135+ c, _, _ := createTestContext()136+ body := bytes.NewBufferString("foo=bar&page=11&both=POST")137+ c.Request, _ = http.NewRequest("POST", "/?both=GET&id=main", body)138+ c.Request.Header.Add("Content-Type", MIMEPOSTForm)139 90- r := New()91- templ, _ := template.New("t").Parse(`Hello {{.Name}}`)92- r.SetHTMLTemplate(templ)140+ assert.Equal(t, c.DefaultPostFormValue("foo", "none"), "bar")141+ assert.Equal(t, c.PostFormValue("foo"), "bar")142+ assert.Equal(t, c.FormValue("foo"), "bar")143 94- type TestData struct{ Name string }144+ assert.Equal(t, c.DefaultPostFormValue("page", "0"), "11")145+ assert.Equal(t, c.PostFormValue("page"), "11")146+ assert.Equal(t, c.FormValue("page"), "11")147 96- r.GET("/test", func(c *Context) {97- c.HTML(200, "t", TestData{"alexandernyquist"})98- })148+ assert.Equal(t, c.PostFormValue("both"), "POST")149+ assert.Equal(t, c.FormValue("both"), "POST")150 100- r.ServeHTTP(w, req)151+ assert.Equal(t, c.FormValue("id"), "main")152+ assert.Empty(t, c.PostFormValue("id"))153 102- if w.Body.String() != "Hello alexandernyquist" {103- t.Errorf("Response should be Hello alexandernyquist, was: %s", w.Body.String())104- }154+ assert.Equal(t, c.DefaultPostFormValue("NoKey", "nada"), "nada")155+ assert.Empty(t, c.PostFormValue("NoKey"))156+ assert.Empty(t, c.FormValue("NoKey"))157+}158 106- if w.HeaderMap.Get("Content-Type") != "text/html; charset=utf-8" {107- t.Errorf("Content-Type should be text/html, was %s", w.HeaderMap.Get("Content-Type"))108- }159+// Tests that the response is serialized as JSON160+// and Content-Type is set to application/json161+func TestContextRenderJSON(t *testing.T) {162+ c, w, _ := createTestContext()163+ c.JSON(201, H{"foo": "bar"})164+165+ assert.Equal(t, w.Code, 201)166+ assert.Equal(t, w.Body.String(), "{\"foo\":\"bar\"}\n")167+ assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8")168 }169 111-// TestContextString tests that the response is returned112-// with Content-Type set to text/plain113-func TestContextString(t *testing.T) {114- req, _ := http.NewRequest("GET", "/test", nil)115- w := httptest.NewRecorder()170+// Tests that the response is serialized as JSON171+// and Content-Type is set to application/json172+func TestContextRenderIndentedJSON(t *testing.T) {173+ c, w, _ := createTestContext()174+ c.IndentedJSON(201, H{"foo": "bar", "bar": "foo", "nested": H{"foo": "bar"}})175 117- r := New()118- r.GET("/test", func(c *Context) {119- c.String(200, "test")120- })176+ assert.Equal(t, w.Code, 201)177+ assert.Equal(t, w.Body.String(), "{\n \"bar\": \"foo\",\n \"foo\": \"bar\",\n \"nested\": {\n \"foo\": \"bar\"\n }\n}")178+ assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8")179+}180 122- r.ServeHTTP(w, req)181+// Tests that the response executes the templates182+// and responds with Content-Type set to text/html183+func TestContextRenderHTML(t *testing.T) {184+ c, w, router := createTestContext()185+ templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))186+ router.SetHTMLTemplate(templ)187 124- if w.Body.String() != "test" {125- t.Errorf("Response should be test, was: %s", w.Body.String())126- }188+ c.HTML(201, "t", H{"name": "alexandernyquist"})189 128- if w.HeaderMap.Get("Content-Type") != "text/plain; charset=utf-8" {129- t.Errorf("Content-Type should be text/plain, was %s", w.HeaderMap.Get("Content-Type"))130- }190+ assert.Equal(t, w.Code, 201)191+ assert.Equal(t, w.Body.String(), "Hello alexandernyquist")192+ assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8")193 }194 195 // TestContextXML tests that the response is serialized as XML196 // and Content-Type is set to application/xml135-func TestContextXML(t *testing.T) {136- req, _ := http.NewRequest("GET", "/test", nil)137- w := httptest.NewRecorder()197+func TestContextRenderXML(t *testing.T) {198+ c, w, _ := createTestContext()199+ c.XML(201, H{"foo": "bar"})200 139- r := New()140- r.GET("/test", func(c *Context) {141- c.XML(200, H{"foo": "bar"})142- })201+ assert.Equal(t, w.Code, 201)202+ assert.Equal(t, w.Body.String(), "<map><foo>bar</foo></map>")203+ assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/xml; charset=utf-8")204+}205 144- r.ServeHTTP(w, req)206+// TestContextString tests that the response is returned207+// with Content-Type set to text/plain208+func TestContextRenderString(t *testing.T) {209+ c, w, _ := createTestContext()210+ c.String(201, "test %s %d", "string", 2)211 146- if w.Body.String() != "<map><foo>bar</foo></map>" {147- t.Errorf("Response should be <map><foo>bar</foo></map>, was: %s", w.Body.String())148- }212+ assert.Equal(t, w.Code, 201)213+ assert.Equal(t, w.Body.String(), "test string 2")214+ assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8")215+}216 150- if w.HeaderMap.Get("Content-Type") != "application/xml; charset=utf-8" {151- t.Errorf("Content-Type should be application/xml, was %s", w.HeaderMap.Get("Content-Type"))152- }217+// TestContextString tests that the response is returned218+// with Content-Type set to text/html219+func TestContextRenderHTMLString(t *testing.T) {220+ c, w, _ := createTestContext()221+ c.Header("Content-Type", "text/html; charset=utf-8")222+ c.String(201, "<html>%s %d</html>", "string", 3)223+224+ assert.Equal(t, w.Code, 201)225+ assert.Equal(t, w.Body.String(), "<html>string 3</html>")226+ assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8")227 }228 229 // TestContextData tests that the response can be written from `bytesting`230 // with specified MIME type157-func TestContextData(t *testing.T) {158- req, _ := http.NewRequest("GET", "/test/csv", nil)159- w := httptest.NewRecorder()231+func TestContextRenderData(t *testing.T) {232+ c, w, _ := createTestContext()233+ c.Data(201, "text/csv", []byte(`foo,bar`))234 161- r := New()162- r.GET("/test/csv", func(c *Context) {163- c.Data(200, "text/csv", []byte(`foo,bar`))164- })165-166- r.ServeHTTP(w, req)167-168- if w.Body.String() != "foo,bar" {169- t.Errorf("Response should be foo&bar, was: %s", w.Body.String())170- }171-172- if w.HeaderMap.Get("Content-Type") != "text/csv" {173- t.Errorf("Content-Type should be text/csv, was %s", w.HeaderMap.Get("Content-Type"))174- }235+ assert.Equal(t, w.Code, 201)236+ assert.Equal(t, w.Body.String(), "foo,bar")237+ assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/csv")238 }239 177-func TestContextFile(t *testing.T) {178- req, _ := http.NewRequest("GET", "/test/file", nil)179- w := httptest.NewRecorder()180-181- r := New()182- r.GET("/test/file", func(c *Context) {183- c.File("./gin.go")240+func TestContextRenderSSE(t *testing.T) {241+ c, w, _ := createTestContext()242+ c.SSEvent("float", 1.5)243+ c.Render(-1, sse.Event{244+ Id: "123",245+ Data: "text",246 })247+ c.SSEvent("chat", H{248+ "foo": "bar",249+ "bar": "foo",250+ })251 186- r.ServeHTTP(w, req)252+ assert.Equal(t, w.Body.String(), "event: float\ndata: 1.5\n\nid: 123\ndata: text\n\nevent: chat\ndata: {\"bar\":\"foo\",\"foo\":\"bar\"}\n\n")253+}254 188- bodyAsString := w.Body.String()255+func TestContextRenderFile(t *testing.T) {256+ c, w, _ := createTestContext()257+ c.Request, _ = http.NewRequest("GET", "/", nil)258+ c.File("./gin.go")259 190- if len(bodyAsString) == 0 {191- t.Errorf("Got empty body instead of file data")192- }193-194- if w.HeaderMap.Get("Content-Type") != "text/plain; charset=utf-8" {195- t.Errorf("Content-Type should be text/plain; charset=utf-8, was %s", w.HeaderMap.Get("Content-Type"))196- }260+ assert.Equal(t, w.Code, 200)261+ assert.Contains(t, w.Body.String(), "func New() *Engine {")262+ assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8")263 }264 199-// TestHandlerFunc - ensure that custom middleware works properly200-func TestHandlerFunc(t *testing.T) {265+func TestContextHeaders(t *testing.T) {266+ c, _, _ := createTestContext()267+ c.Header("Content-Type", "text/plain")268+ c.Header("X-Custom", "value")269 202- req, _ := http.NewRequest("GET", "/", nil)203- w := httptest.NewRecorder()270+ assert.Equal(t, c.Writer.Header().Get("Content-Type"), "text/plain")271+ assert.Equal(t, c.Writer.Header().Get("X-Custom"), "value")272 205- r := New()206- var stepsPassed int = 0273+ c.Header("Content-Type", "text/html")274+ c.Header("X-Custom", "")275 208- r.Use(func(context *Context) {209- stepsPassed += 1210- context.Next()211- stepsPassed += 1212- })276+ assert.Equal(t, c.Writer.Header().Get("Content-Type"), "text/html")277+ _, exist := c.Writer.Header()["X-Custom"]278+ assert.False(t, exist)279+}280 214- r.ServeHTTP(w, req)281+// TODO282+func TestContextRenderRedirectWithRelativePath(t *testing.T) {283+ c, w, _ := createTestContext()284+ c.Request, _ = http.NewRequest("POST", "http://example.com", nil)285+ assert.Panics(t, func() { c.Redirect(299, "/new_path") })286+ assert.Panics(t, func() { c.Redirect(309, "/new_path") })287 216- if w.Code != 404 {217- t.Errorf("Response code should be Not found, was: %s", w.Code)218- }219-220- if stepsPassed != 2 {221- t.Errorf("Falied to switch context in handler function: %s", stepsPassed)222- }288+ c.Redirect(302, "/path")289+ c.Writer.WriteHeaderNow()290+ assert.Equal(t, w.Code, 302)291+ assert.Equal(t, w.Header().Get("Location"), "/path")292 }293 225-// TestBadAbortHandlersChain - ensure that Abort after switch context will not interrupt pending handlers226-func TestBadAbortHandlersChain(t *testing.T) {227- // SETUP228- var stepsPassed int = 0229- r := New()230- r.Use(func(c *Context) {231- stepsPassed += 1232- c.Next()233- stepsPassed += 1234- // after check and abort235- c.AbortWithStatus(409)236- })237- r.Use(func(c *Context) {238- stepsPassed += 1239- c.Next()240- stepsPassed += 1241- c.AbortWithStatus(403)242- })294+func TestContextRenderRedirectWithAbsolutePath(t *testing.T) {295+ c, w, _ := createTestContext()296+ c.Request, _ = http.NewRequest("POST", "http://example.com", nil)297+ c.Redirect(302, "http://google.com")298+ c.Writer.WriteHeaderNow()299 244- // RUN245- w := PerformRequest(r, "GET", "/")246-247- // TEST248- if w.Code != 409 {249- t.Errorf("Response code should be Forbiden, was: %d", w.Code)250- }251- if stepsPassed != 4 {252- t.Errorf("Falied to switch context in handler function: %d", stepsPassed)253- }300+ assert.Equal(t, w.Code, 302)301+ assert.Equal(t, w.Header().Get("Location"), "http://google.com")302 }303 256-// TestAbortHandlersChain - ensure that Abort interrupt used middlewares in fifo order257-func TestAbortHandlersChain(t *testing.T) {258- // SETUP259- var stepsPassed int = 0260- r := New()261- r.Use(func(context *Context) {262- stepsPassed += 1263- context.AbortWithStatus(409)264- })265- r.Use(func(context *Context) {266- stepsPassed += 1267- context.Next()268- stepsPassed += 1269- })304+func TestContextNegotiationFormat(t *testing.T) {305+ c, _, _ := createTestContext()306+ c.Request, _ = http.NewRequest("POST", "", nil)307 271- // RUN272- w := PerformRequest(r, "GET", "/")273-274- // TEST275- if w.Code != 409 {276- t.Errorf("Response code should be Conflict, was: %d", w.Code)277- }278- if stepsPassed != 1 {279- t.Errorf("Falied to switch context in handler function: %d", stepsPassed)280- }308+ assert.Panics(t, func() { c.NegotiateFormat() })309+ assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEJSON)310+ assert.Equal(t, c.NegotiateFormat(MIMEHTML, MIMEJSON), MIMEHTML)311 }312 283-// TestFailHandlersChain - ensure that Fail interrupt used middlewares in fifo order as284-// as well as Abort285-func TestFailHandlersChain(t *testing.T) {286- // SETUP287- var stepsPassed int = 0288- r := New()289- r.Use(func(context *Context) {290- stepsPassed += 1291- context.Fail(500, errors.New("foo"))292- })293- r.Use(func(context *Context) {294- stepsPassed += 1295- context.Next()296- stepsPassed += 1297- })313+func TestContextNegotiationFormatWithAccept(t *testing.T) {314+ c, _, _ := createTestContext()315+ c.Request, _ = http.NewRequest("POST", "/", nil)316+ c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")317 299- // RUN300- w := PerformRequest(r, "GET", "/")301-302- // TEST303- if w.Code != 500 {304- t.Errorf("Response code should be Server error, was: %d", w.Code)305- }306- if stepsPassed != 1 {307- t.Errorf("Falied to switch context in handler function: %d", stepsPassed)308- }318+ assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEXML)319+ assert.Equal(t, c.NegotiateFormat(MIMEXML, MIMEHTML), MIMEHTML)320+ assert.Equal(t, c.NegotiateFormat(MIMEJSON), "")321 }322 311-func TestBindingJSON(t *testing.T) {323+func TestContextNegotiationFormatCustum(t *testing.T) {324+ c, _, _ := createTestContext()325+ c.Request, _ = http.NewRequest("POST", "/", nil)326+ c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")327 313- body := bytes.NewBuffer([]byte("{\"foo\":\"bar\"}"))328+ c.Accepted = nil329+ c.SetAccepted(MIMEJSON, MIMEXML)330 315- r := New()316- r.POST("/binding/json", func(c *Context) {317- var body struct {318- Foo string `json:"foo"`319- }320- if c.Bind(&body) {321- c.JSON(200, H{"parsed": body.Foo})322- }323- })331+ assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEJSON)332+ assert.Equal(t, c.NegotiateFormat(MIMEXML, MIMEHTML), MIMEXML)333+ assert.Equal(t, c.NegotiateFormat(MIMEJSON), MIMEJSON)334+}335 325- req, _ := http.NewRequest("POST", "/binding/json", body)326- req.Header.Set("Content-Type", "application/json")327- w := httptest.NewRecorder()336+// TestContextData tests that the response can be written from `bytesting`337+// with specified MIME type338+func TestContextAbortWithStatus(t *testing.T) {339+ c, w, _ := createTestContext()340+ c.index = 4341+ c.AbortWithStatus(401)342+ c.Writer.WriteHeaderNow()343 329- r.ServeHTTP(w, req)330-331- if w.Code != 200 {332- t.Errorf("Response code should be Ok, was: %s", w.Code)333- }334-335- if w.Body.String() != "{\"parsed\":\"bar\"}\n" {336- t.Errorf("Response should be {\"parsed\":\"bar\"}, was: %s", w.Body.String())337- }338-339- if w.HeaderMap.Get("Content-Type") != "application/json; charset=utf-8" {340- t.Errorf("Content-Type should be application/json, was %s", w.HeaderMap.Get("Content-Type"))341- }344+ assert.Equal(t, c.index, AbortIndex)345+ assert.Equal(t, c.Writer.Status(), 401)346+ assert.Equal(t, w.Code, 401)347+ assert.True(t, c.IsAborted())348 }349 344-func TestBindingJSONEncoding(t *testing.T) {350+func TestContextError(t *testing.T) {351+ c, _, _ := createTestContext()352+ assert.Empty(t, c.Errors)353 346- body := bytes.NewBuffer([]byte("{\"foo\":\"嘉\"}"))354+ c.Error(errors.New("first error"))355+ assert.Len(t, c.Errors, 1)356+ assert.Equal(t, c.Errors.String(), "Error #01: first error\n")357 348- r := New()349- r.POST("/binding/json", func(c *Context) {350- var body struct {351- Foo string `json:"foo"`352- }353- if c.Bind(&body) {354- c.JSON(200, H{"parsed": body.Foo})355- }358+ c.Error(&Error{359+ Err: errors.New("second error"),360+ Meta: "some data 2",361+ Type: ErrorTypePublic,362 })363+ assert.Len(t, c.Errors, 2)364 358- req, _ := http.NewRequest("POST", "/binding/json", body)359- req.Header.Set("Content-Type", "application/json; charset=utf-8")360- w := httptest.NewRecorder()365+ assert.Equal(t, c.Errors[0].Err, errors.New("first error"))366+ assert.Nil(t, c.Errors[0].Meta)367+ assert.Equal(t, c.Errors[0].Type, ErrorTypePrivate)368 362- r.ServeHTTP(w, req)369+ assert.Equal(t, c.Errors[1].Err, errors.New("second error"))370+ assert.Equal(t, c.Errors[1].Meta, "some data 2")371+ assert.Equal(t, c.Errors[1].Type, ErrorTypePublic)372 364- if w.Code != 200 {365- t.Errorf("Response code should be Ok, was: %s", w.Code)366- }367-368- if w.Body.String() != "{\"parsed\":\"嘉\"}\n" {369- t.Errorf("Response should be {\"parsed\":\"嘉\"}, was: %s", w.Body.String())370- }371-372- if w.HeaderMap.Get("Content-Type") != "application/json; charset=utf-8" {373- t.Errorf("Content-Type should be application/json, was %s", w.HeaderMap.Get("Content-Type"))374- }373+ assert.Equal(t, c.Errors.Last(), c.Errors[1])374 }375 377-func TestBindingJSONNoContentType(t *testing.T) {376+func TestContextTypedError(t *testing.T) {377+ c, _, _ := createTestContext()378+ c.Error(errors.New("externo 0")).SetType(ErrorTypePublic)379+ c.Error(errors.New("interno 0")).SetType(ErrorTypePrivate)380 379- body := bytes.NewBuffer([]byte("{\"foo\":\"bar\"}"))380-381- r := New()382- r.POST("/binding/json", func(c *Context) {383- var body struct {384- Foo string `json:"foo"`385- }386- if c.Bind(&body) {387- c.JSON(200, H{"parsed": body.Foo})388- }389-390- })391-392- req, _ := http.NewRequest("POST", "/binding/json", body)393- w := httptest.NewRecorder()394-395- r.ServeHTTP(w, req)396-397- if w.Code != 400 {398- t.Errorf("Response code should be Bad request, was: %s", w.Code)381+ for _, err := range c.Errors.ByType(ErrorTypePublic) {382+ assert.Equal(t, err.Type, ErrorTypePublic)383 }400-401- if w.Body.String() == "{\"parsed\":\"bar\"}\n" {402- t.Errorf("Response should not be {\"parsed\":\"bar\"}, was: %s", w.Body.String())384+ for _, err := range c.Errors.ByType(ErrorTypePrivate) {385+ assert.Equal(t, err.Type, ErrorTypePrivate)386 }404-405- if w.HeaderMap.Get("Content-Type") == "application/json" {406- t.Errorf("Content-Type should not be application/json, was %s", w.HeaderMap.Get("Content-Type"))407- }387+ assert.Equal(t, c.Errors.Errors(), []string{"externo 0", "interno 0"})388 }389 410-func TestBindingJSONMalformed(t *testing.T) {390+func TestContextAbortWithError(t *testing.T) {391+ c, w, _ := createTestContext()392+ c.AbortWithError(401, errors.New("bad input")).SetMeta("some input")393+ c.Writer.WriteHeaderNow()394 412- body := bytes.NewBuffer([]byte("\"foo\":\"bar\"\n"))395+ assert.Equal(t, w.Code, 401)396+ assert.Equal(t, c.index, AbortIndex)397+ assert.True(t, c.IsAborted())398+}399 414- r := New()415- r.POST("/binding/json", func(c *Context) {416- var body struct {417- Foo string `json:"foo"`418- }419- if c.Bind(&body) {420- c.JSON(200, H{"parsed": body.Foo})421- }400+func TestContextClientIP(t *testing.T) {401+ c, _, _ := createTestContext()402+ c.Request, _ = http.NewRequest("POST", "/", nil)403 423- })404+ c.Request.Header.Set("X-Real-IP", "10.10.10.10")405+ c.Request.Header.Set("X-Forwarded-For", "20.20.20.20 , 30.30.30.30")406+ c.Request.RemoteAddr = "40.40.40.40"407 425- req, _ := http.NewRequest("POST", "/binding/json", body)426- req.Header.Set("Content-Type", "application/json")408+ assert.Equal(t, c.ClientIP(), "10.10.10.10")409+ c.Request.Header.Del("X-Real-IP")410+ assert.Equal(t, c.ClientIP(), "20.20.20.20")411+ c.Request.Header.Del("X-Forwarded-For")412+ assert.Equal(t, c.ClientIP(), "40.40.40.40")413+}414 428- w := httptest.NewRecorder()415+func TestContextContentType(t *testing.T) {416+ c, _, _ := createTestContext()417+ c.Request, _ = http.NewRequest("POST", "/", nil)418+ c.Request.Header.Set("Content-Type", "application/json; charset=utf-8")419 430- r.ServeHTTP(w, req)420+ assert.Equal(t, c.ContentType(), "application/json")421+}422 432- if w.Code != 400 {433- t.Errorf("Response code should be Bad request, was: %s", w.Code)423+func TestContextAutoBind(t *testing.T) {424+ c, w, _ := createTestContext()425+ c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))426+ c.Request.Header.Add("Content-Type", MIMEJSON)427+ var obj struct {428+ Foo string `json:"foo"`429+ Bar string `json:"bar"`430 }435- if w.Body.String() == "{\"parsed\":\"bar\"}\n" {436- t.Errorf("Response should not be {\"parsed\":\"bar\"}, was: %s", w.Body.String())437- }438-439- if w.HeaderMap.Get("Content-Type") == "application/json" {440- t.Errorf("Content-Type should not be application/json, was %s", w.HeaderMap.Get("Content-Type"))441- }431+ assert.NoError(t, c.Bind(&obj))432+ assert.Equal(t, obj.Bar, "foo")433+ assert.Equal(t, obj.Foo, "bar")434+ assert.Equal(t, w.Body.Len(), 0)435 }436 444-func TestBindingForm(t *testing.T) {445-446- body := bytes.NewBuffer([]byte("foo=bar&num=123&unum=1234567890"))447-448- r := New()449- r.POST("/binding/form", func(c *Context) {450- var body struct {451- Foo string `form:"foo"`452- Num int `form:"num"`453- Unum uint `form:"unum"`454- }455- if c.Bind(&body) {456- c.JSON(200, H{"foo": body.Foo, "num": body.Num, "unum": body.Unum})457- }458- })459-460- req, _ := http.NewRequest("POST", "/binding/form", body)461- req.Header.Set("Content-Type", "application/x-www-form-urlencoded")462- w := httptest.NewRecorder()463-464- r.ServeHTTP(w, req)465-466- if w.Code != 200 {467- t.Errorf("Response code should be Ok, was: %d", w.Code)437+func TestContextBadAutoBind(t *testing.T) {438+ c, w, _ := createTestContext()439+ c.Request, _ = http.NewRequest("POST", "http://example.com", bytes.NewBufferString("\"foo\":\"bar\", \"bar\":\"foo\"}"))440+ c.Request.Header.Add("Content-Type", MIMEJSON)441+ var obj struct {442+ Foo string `json:"foo"`443+ Bar string `json:"bar"`444 }445 470- expected := "{\"foo\":\"bar\",\"num\":123,\"unum\":1234567890}\n"471- if w.Body.String() != expected {472- t.Errorf("Response should be %s, was %s", expected, w.Body.String())473- }446+ assert.False(t, c.IsAborted())447+ assert.Error(t, c.Bind(&obj))448+ c.Writer.WriteHeaderNow()449 475- if w.HeaderMap.Get("Content-Type") != "application/json; charset=utf-8" {476- t.Errorf("Content-Type should be application/json, was %s", w.HeaderMap.Get("Content-Type"))477- }450+ assert.Empty(t, obj.Bar)451+ assert.Empty(t, obj.Foo)452+ assert.Equal(t, w.Code, 400)453+ assert.True(t, c.IsAborted())454 }455 480-func TestClientIP(t *testing.T) {481- r := New()482-483- var clientIP string = ""484- r.GET("/", func(c *Context) {485- clientIP = c.ClientIP()486- })487-488- body := bytes.NewBuffer([]byte(""))489- req, _ := http.NewRequest("GET", "/", body)490- req.RemoteAddr = "clientip:1234"491- w := httptest.NewRecorder()492- r.ServeHTTP(w, req)493-494- if clientIP != "clientip:1234" {495- t.Errorf("ClientIP should not be %s, but clientip:1234", clientIP)456+func TestContextBindWith(t *testing.T) {457+ c, w, _ := createTestContext()458+ c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))459+ c.Request.Header.Add("Content-Type", MIMEXML)460+ var obj struct {461+ Foo string `json:"foo"`462+ Bar string `json:"bar"`463 }464+ assert.NoError(t, c.BindWith(&obj, binding.JSON))465+ assert.Equal(t, obj.Bar, "foo")466+ assert.Equal(t, obj.Foo, "bar")467+ assert.Equal(t, w.Body.Len(), 0)468 }469 499-func TestClientIPWithXForwardedForWithProxy(t *testing.T) {500- r := New()501- r.Use(ForwardedFor())470+func TestContextGolangContext(t *testing.T) {471+ c, _, _ := createTestContext()472+ c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))473+ assert.NoError(t, c.Err())474+ assert.Nil(t, c.Done())475+ ti, ok := c.Deadline()476+ assert.Equal(t, ti, time.Time{})477+ assert.False(t, ok)478+ assert.Equal(t, c.Value(0), c.Request)479+ assert.Nil(t, c.Value("foo"))480 503- var clientIP string = ""504- r.GET("/", func(c *Context) {505- clientIP = c.ClientIP()506- })507-508- body := bytes.NewBuffer([]byte(""))509- req, _ := http.NewRequest("GET", "/", body)510- req.RemoteAddr = "172.16.8.3:1234"511- req.Header.Set("X-Real-Ip", "realip")512- req.Header.Set("X-Forwarded-For", "1.2.3.4, 10.10.0.4, 192.168.0.43, 172.16.8.4")513- w := httptest.NewRecorder()514- r.ServeHTTP(w, req)515-516- if clientIP != "1.2.3.4:0" {517- t.Errorf("ClientIP should not be %s, but 1.2.3.4:0", clientIP)518- }481+ c.Set("foo", "bar")482+ assert.Equal(t, c.Value("foo"), "bar")483+ assert.Nil(t, c.Value(1))484 }modified:context.go+267 added-235 removed
3 unmodified lines4 5 package gin6 7 import (8- "bytes"8 "errors"10- "fmt"11- "github.com/gin-gonic/gin/binding"12- "github.com/gin-gonic/gin/render"13- "github.com/julienschmidt/httprouter"14- "log"15- "net"9+ "io"10+ "math"11 "net/http"12 "strings"13+ "time"14+15+ "github.com/gin-gonic/gin/binding"16+ "github.com/gin-gonic/gin/render"17+ "github.com/manucorporat/sse"18+ "golang.org/x/net/context"19 )20 21 const (21- ErrorTypeInternal = 1 << iota22- ErrorTypeExternal = 1 << iota23- ErrorTypeAll = 0xffffffff22+ MIMEJSON = binding.MIMEJSON23+ MIMEHTML = binding.MIMEHTML24+ MIMEXML = binding.MIMEXML25+ MIMEXML2 = binding.MIMEXML226+ MIMEPlain = binding.MIMEPlain27+ MIMEPOSTForm = binding.MIMEPOSTForm28+ MIMEMultipartPOSTForm = binding.MIMEMultipartPOSTForm29 )30 26-// Used internally to collect errors that occurred during an http request.27-type errorMsg struct {28- Err string `json:"error"`29- Type uint32 `json:"-"`30- Meta interface{} `json:"meta"`31+const AbortIndex = math.MaxInt8 / 232+33+var _ context.Context = &Context{}34+35+// Param is a single URL parameter, consisting of a key and a value.36+type Param struct {37+ Key string38+ Value string39 }40 33-type errorMsgs []errorMsg41+// Params is a Param-slice, as returned by the router.42+// The slice is ordered, the first URL parameter is also the first slice value.43+// It is therefore safe to read values by the index.44+type Params []Param45 35-func (a errorMsgs) ByType(typ uint32) errorMsgs {36- if len(a) == 0 {37- return a38- }39- result := make(errorMsgs, 0, len(a))40- for _, msg := range a {41- if msg.Type&typ > 0 {42- result = append(result, msg)46+// ByName returns the value of the first Param which key matches the given name.47+// If no matching Param is found, an empty string is returned.48+func (ps Params) Get(name string) (string, bool) {49+ for _, entry := range ps {50+ if entry.Key == name {51+ return entry.Value, true52 }53 }45- return result54+ return "", false55 }56 48-func (a errorMsgs) String() string {49- if len(a) == 0 {50- return ""51- }52- var buffer bytes.Buffer53- for i, msg := range a {54- text := fmt.Sprintf("Error #%02d: %s \n Meta: %v\n", (i + 1), msg.Err, msg.Meta)55- buffer.WriteString(text)56- }57- return buffer.String()57+func (ps Params) ByName(name string) (va string) {58+ va, _ = ps.Get(name)59+ return60 }61 62 // Context is the most important part of gin. It allows us to pass variables between middleware,63 // manage the flow, validate the JSON of a request and render a JSON response for example.64 type Context struct {65 writermem responseWriter66 Request *http.Request67 Writer ResponseWriter66- Keys map[string]interface{}67- Errors errorMsgs68- Params httprouter.Params69- Engine *Engine70- handlers []HandlerFunc71- index int872- accepted []string68+69+ Params Params70+ handlers HandlersChain71+ index int872+73+ engine *Engine74+ Keys map[string]interface{}75+ Errors errorMsgs76+ Accepted []string77 }78 79 /************************************/80 /********** CONTEXT CREATION ********/81 /************************************/82 79-func (engine *Engine) createContext(w http.ResponseWriter, req *http.Request, params httprouter.Params, handlers []HandlerFunc) *Context {80- c := engine.pool.Get().(*Context)81- c.writermem.reset(w)82- c.Request = req83- c.Params = params84- c.handlers = handlers85- c.Keys = nil83+func (c *Context) reset() {84+ c.Writer = &c.writermem85+ c.Params = c.Params[0:0]86+ c.handlers = nil87 c.index = -187- c.accepted = nil88+ c.Keys = nil89 c.Errors = c.Errors[0:0]89- return c90+ c.Accepted = nil91 }92 92-func (engine *Engine) reuseContext(c *Context) {93- engine.pool.Put(c)94-}95-93 func (c *Context) Copy() *Context {94 var cp Context = *c95+ cp.writermem.ResponseWriter = nil96+ cp.Writer = &cp.writermem97 cp.index = AbortIndex98 cp.handlers = nil99 return &cp100 }12 unmodified lines113 c.handlers[c.index](c)114 }115 }116 118-// Forces the system to do not continue calling the pending handlers in the chain.117+// Forces the system to not continue calling the pending handlers in the chain.118 func (c *Context) Abort() {119 c.index = AbortIndex120 }121 3 unmodified lines125 c.Writer.WriteHeader(code)126 c.Abort()127 }128 130-/************************************/131-/********* ERROR MANAGEMENT *********/132-/************************************/133-134-// Fail is the same as Abort plus an error message.135-// Calling `context.Fail(500, err)` is equivalent to:136-// ```137-// context.Error("Operation aborted", err)138-// context.AbortWithStatus(500)139-// ```140-func (c *Context) Fail(code int, err error) {141- c.Error(err, "Operation aborted")129+func (c *Context) AbortWithError(code int, err error) *Error {130 c.AbortWithStatus(code)131+ return c.Error(err)132 }133 145-func (c *Context) ErrorTyped(err error, typ uint32, meta interface{}) {146- c.Errors = append(c.Errors, errorMsg{147- Err: err.Error(),148- Type: typ,149- Meta: meta,150- })134+func (c *Context) IsAborted() bool {135+ return c.index == AbortIndex136 }137 138+/************************************/139+/********* ERROR MANAGEMENT *********/140+/************************************/141+142 // Attaches an error to the current context. The error is pushed to a list of errors.143 // It's a good idea to call Error for each error that occurred during the resolution of a request.144 // A middleware can be used to collect all the errors and push them to a database together, print a log, or append it in the HTTP response.156-func (c *Context) Error(err error, meta interface{}) {157- c.ErrorTyped(err, ErrorTypeExternal, meta)158-}159-160-func (c *Context) LastError() error {161- nuErrors := len(c.Errors)162- if nuErrors > 0 {163- return errors.New(c.Errors[nuErrors-1].Err)164- } else {165- return nil145+func (c *Context) Error(err error) *Error {146+ var parsedError *Error147+ switch err.(type) {148+ case *Error:149+ parsedError = err.(*Error)150+ default:151+ parsedError = &Error{152+ Err: err,153+ Type: ErrorTypePrivate,154+ }155 }156+ c.Errors = append(c.Errors, parsedError)157+ return parsedError158 }159 160 /************************************/161 /******** METADATA MANAGEMENT********/162 /************************************/163 164 // Sets a new pair key/value just for the specified context.165 // It also lazy initializes the hashmap.175-func (c *Context) Set(key string, item interface{}) {166+func (c *Context) Set(key string, value interface{}) {167 if c.Keys == nil {168 c.Keys = make(map[string]interface{})169 }179- c.Keys[key] = item170+ c.Keys[key] = value171 }172 173 // Get returns the value for the given key or an error if the key does not exist.183-func (c *Context) Get(key string) (interface{}, error) {174+func (c *Context) Get(key string) (value interface{}, exists bool) {175 if c.Keys != nil {185- value, ok := c.Keys[key]186- if ok {187- return value, nil188- }176+ value, exists = c.Keys[key]177 }190- return nil, errors.New("Key does not exist.")178+ return179 }180 181 // MustGet returns the value for the given key or panics if the value doesn't exist.182 func (c *Context) MustGet(key string) interface{} {195- value, err := c.Get(key)196- if err != nil || value == nil {197- log.Panicf("Key %s doesn't exist", value)183+ if value, exists := c.Get(key); exists {184+ return value185 }199- return value186+ panic("Key \"" + key + "\" does not exist")187 }188 202-func ipInMasks(ip net.IP, masks []interface{}) bool {203- for _, proxy := range masks {204- var mask *net.IPNet205- var err error189+/************************************/190+/************ INPUT DATA ************/191+/************************************/192 207- switch t := proxy.(type) {208- case string:209- if _, mask, err = net.ParseCIDR(t); err != nil {210- panic(err)211- }212- case net.IP:213- mask = &net.IPNet{IP: t, Mask: net.CIDRMask(len(t)*8, len(t)*8)}214- case net.IPNet:215- mask = &t216- }193+/** Shortcut for c.Request.FormValue(key) */194+func (c *Context) FormValue(key string) (va string) {195+ va, _ = c.formValue(key)196+ return197+}198 218- if mask.Contains(ip) {219- return true220- }221- }199+/** Shortcut for c.Request.PostFormValue(key) */200+func (c *Context) PostFormValue(key string) (va string) {201+ va, _ = c.postFormValue(key)202+ return203+}204 205+/** Shortcut for c.Params.ByName(key) */206+func (c *Context) ParamValue(key string) (va string) {207+ va, _ = c.paramValue(key)223- return false208+ return209 }210 226-// the ForwardedFor middleware unwraps the X-Forwarded-For headers, be careful to only use this227-// middleware if you've got servers in front of this server. The list with (known) proxies and228-// local ips are being filtered out of the forwarded for list, giving the last not local ip being229-// the real client ip.230-func ForwardedFor(proxies ...interface{}) HandlerFunc {231- if len(proxies) == 0 {232- // default to local ips233- var reservedLocalIps = []string{"10.0.0.0/8", "127.0.0.1/32", "172.16.0.0/12", "192.168.0.0/16"}211+func (c *Context) DefaultPostFormValue(key, defaultValue string) string {212+ if va, ok := c.postFormValue(key); ok {213+ return va214+ }215+ return defaultValue216+}217 235- proxies = make([]interface{}, len(reservedLocalIps))218+func (c *Context) DefaultFormValue(key, defaultValue string) string {219+ if va, ok := c.formValue(key); ok {220+ return va221+ }222+ return defaultValue223+}224 237- for i, v := range reservedLocalIps {238- proxies[i] = v239- }225+func (c *Context) DefaultParamValue(key, defaultValue string) string {226+ if va, ok := c.paramValue(key); ok {227+ return va228 }229+ return defaultValue230+}231 242- return func(c *Context) {243- // the X-Forwarded-For header contains an array with left most the client ip, then244- // comma separated, all proxies the request passed. The last proxy appears245- // as the remote address of the request. Returning the client246- // ip to comply with default RemoteAddr response.232+func (c *Context) paramValue(key string) (string, bool) {233+ return c.Params.Get(key)234+}235 248- // check if remoteaddr is local ip or in list of defined proxies249- remoteIp := net.ParseIP(strings.Split(c.Request.RemoteAddr, ":")[0])250-251- if !ipInMasks(remoteIp, proxies) {252- return253- }254-255- if forwardedFor := c.Request.Header.Get("X-Forwarded-For"); forwardedFor != "" {256- parts := strings.Split(forwardedFor, ",")257-258- for i := len(parts) - 1; i >= 0; i-- {259- part := parts[i]260-261- ip := net.ParseIP(strings.TrimSpace(part))262-263- if ipInMasks(ip, proxies) {264- continue265- }266-267- // returning remote addr conform the original remote addr format268- c.Request.RemoteAddr = ip.String() + ":0"269-270- // remove forwarded for address271- c.Request.Header.Set("X-Forwarded-For", "")272- return273- }274- }236+func (c *Context) formValue(key string) (string, bool) {237+ req := c.Request238+ req.ParseForm()239+ if values, ok := req.Form[key]; ok && len(values) > 0 {240+ return values[0], true241 }242+ return "", false243 }244 278-func (c *Context) ClientIP() string {279- return c.Request.RemoteAddr245+func (c *Context) postFormValue(key string) (string, bool) {246+ req := c.Request247+ req.ParseForm()248+ if values, ok := req.PostForm[key]; ok && len(values) > 0 {249+ return values[0], true250+ }251+ return "", false252 }253 282-/************************************/283-/********* PARSING REQUEST **********/284-/************************************/285-254 // This function checks the Content-Type to select a binding engine automatically,255 // Depending the "Content-Type" header different bindings are used:256 // "application/json" --> JSON binding257 // "application/xml" --> XML binding258 // else --> returns an error259 // if Parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input. It decodes the json payload into the struct specified as a pointer.Like ParseBody() but this method also writes a 400 error if the json is not valid.292-func (c *Context) Bind(obj interface{}) bool {293- var b binding.Binding294- ctype := filterFlags(c.Request.Header.Get("Content-Type"))295- switch {296- case c.Request.Method == "GET" || ctype == MIMEPOSTForm:297- b = binding.Form298- case ctype == MIMEMultipartPOSTForm:299- b = binding.MultipartForm300- case ctype == MIMEJSON:301- b = binding.JSON302- case ctype == MIMEXML || ctype == MIMEXML2:303- b = binding.XML304- default:305- c.Fail(400, errors.New("unknown content-type: "+ctype))306- return false307- }260+func (c *Context) Bind(obj interface{}) error {261+ b := binding.Default(c.Request.Method, c.ContentType())262 return c.BindWith(obj, b)263 }264 265+func (c *Context) BindJSON(obj interface{}) error {266+ return c.BindWith(obj, binding.JSON)267+}268+311-func (c *Context) BindWith(obj interface{}, b binding.Binding) bool {269+func (c *Context) BindWith(obj interface{}, b binding.Binding) error {270 if err := b.Bind(c.Request, obj); err != nil {313- c.Fail(400, err)314- return false271+ c.AbortWithError(400, err).SetType(ErrorTypeBind)272+ return err273 }316- return true274+ return nil275 }276 277+func (c *Context) ClientIP() string {278+ clientIP := c.Request.Header.Get("X-Real-IP")279+ if len(clientIP) > 0 {280+ return clientIP281+ }282+ clientIP = c.Request.Header.Get("X-Forwarded-For")283+ clientIP = strings.Split(clientIP, ",")[0]284+ if len(clientIP) > 0 {285+ return strings.TrimSpace(clientIP)286+ }287+ return c.Request.RemoteAddr288+}289+290+func (c *Context) ContentType() string {291+ return filterFlags(c.Request.Header.Get("Content-Type"))292+}293+294 /************************************/295 /******** RESPONSE RENDERING ********/296 /************************************/297 323-func (c *Context) Render(code int, render render.Render, obj ...interface{}) {324- if err := render.Render(c.Writer, code, obj...); err != nil {325- c.ErrorTyped(err, ErrorTypeInternal, obj)326- c.AbortWithStatus(500)298+func (c *Context) Header(key, value string) {299+ if len(value) == 0 {300+ c.Writer.Header().Del(key)301+ } else {302+ c.Writer.Header().Set(key, value)303 }304 }305 306+func (c *Context) Render(code int, r render.Render) {307+ c.Writer.WriteHeader(code)308+ if err := r.Write(c.Writer); err != nil {309+ debugPrintError(err)310+ c.AbortWithError(500, err).SetType(ErrorTypeRender)311+ }312+}313+314+// Renders the HTTP template specified by its file name.315+// It also updates the HTTP code and sets the Content-Type as "text/html".316+// See http://golang.org/doc/articles/wiki/317+func (c *Context) HTML(code int, name string, obj interface{}) {318+ instance := c.engine.HTMLRender.Instance(name, obj)319+ c.Render(code, instance)320+}321+322+func (c *Context) IndentedJSON(code int, obj interface{}) {323+ c.Render(code, render.IndentedJSON{Data: obj})324+}325+326 // Serializes the given struct as JSON into the response body in a fast and efficient way.327 // It also sets the Content-Type as "application/json".328 func (c *Context) JSON(code int, obj interface{}) {333- c.Render(code, render.JSON, obj)329+ c.Render(code, render.JSON{Data: obj})330 }331 332 // Serializes the given struct as XML into the response body in a fast and efficient way.333 // It also sets the Content-Type as "application/xml".334 func (c *Context) XML(code int, obj interface{}) {339- c.Render(code, render.XML, obj)335+ c.Render(code, render.XML{Data: obj})336 }337 342-// Renders the HTTP template specified by its file name.343-// It also updates the HTTP code and sets the Content-Type as "text/html".344-// See http://golang.org/doc/articles/wiki/345-func (c *Context) HTML(code int, name string, obj interface{}) {346- c.Render(code, c.Engine.HTMLRender, name, obj)347-}348-338 // Writes the given string into the response body and sets the Content-Type to "text/plain".339 func (c *Context) String(code int, format string, values ...interface{}) {351- c.Render(code, render.Plain, format, values)340+ c.Render(code, render.String{341+ Format: format,342+ Data: values},343+ )344 }345 354-// Writes the given string into the response body and sets the Content-Type to "text/html" without template.355-func (c *Context) HTMLString(code int, format string, values ...interface{}) {356- c.Render(code, render.HTMLPlain, format, values)357-}358-346 // Returns a HTTP redirect to the specific location.347 func (c *Context) Redirect(code int, location string) {361- if code >= 300 && code <= 308 {362- c.Render(code, render.Redirect, location)363- } else {364- panic(fmt.Sprintf("Cannot send a redirect with status code %d", code))365- }348+ c.Render(-1, render.Redirect{349+ Code: code,350+ Location: location,351+ Request: c.Request,352+ })353 }354 355 // Writes some data into the body stream and updates the HTTP code.356 func (c *Context) Data(code int, contentType string, data []byte) {370- if len(contentType) > 0 {371- c.Writer.Header().Set("Content-Type", contentType)372- }373- c.Writer.WriteHeader(code)374- c.Writer.Write(data)357+ c.Render(code, render.Data{358+ ContentType: contentType,359+ Data: data,360+ })361 }362 363 // Writes the specified file into the body stream364 func (c *Context) File(filepath string) {365 http.ServeFile(c.Writer, c.Request, filepath)366 }367 368+func (c *Context) SSEvent(name string, message interface{}) {369+ c.Render(-1, sse.Event{370+ Event: name,371+ Data: message,372+ })373+}374+375+func (c *Context) Stream(step func(w io.Writer) bool) {376+ w := c.Writer377+ clientGone := w.CloseNotify()378+ for {379+ select {380+ case <-clientGone:381+ return382+ default:383+ keepopen := step(w)384+ w.Flush()385+ if !keepopen {386+ return387+ }388+ }389+ }390+}391+392 /************************************/393 /******** CONTENT NEGOTIATION *******/394 /************************************/395 396 type Negotiate struct {397 Offered []string388- HTMLPath string398+ HTMLName string399 HTMLData interface{}400 JSONData interface{}401 XMLData interface{}402 Data interface{}403 }404 405 func (c *Context) Negotiate(code int, config Negotiate) {406 switch c.NegotiateFormat(config.Offered...) {397- case MIMEJSON:407+ case binding.MIMEJSON:408 data := chooseData(config.JSONData, config.Data)409 c.JSON(code, data)410 401- case MIMEHTML:411+ case binding.MIMEHTML:412 data := chooseData(config.HTMLData, config.Data)403- if len(config.HTMLPath) == 0 {404- panic("negotiate config is wrong. html path is needed")405- }406- c.HTML(code, config.HTMLPath, data)413+ c.HTML(code, config.HTMLName, data)414 408- case MIMEXML:415+ case binding.MIMEXML:416 data := chooseData(config.XMLData, config.Data)417 c.XML(code, data)418 419 default:413- c.Fail(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server"))420+ c.AbortWithError(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server"))421 }422 }423 424 func (c *Context) NegotiateFormat(offered ...string) string {425 if len(offered) == 0 {426 panic("you must provide at least one offer")427 }421- if c.accepted == nil {422- c.accepted = parseAccept(c.Request.Header.Get("Accept"))428+ if c.Accepted == nil {429+ c.Accepted = parseAccept(c.Request.Header.Get("Accept"))430 }424- if len(c.accepted) == 0 {431+ if len(c.Accepted) == 0 {432 return offered[0]426-427- } else {428- for _, accepted := range c.accepted {429- for _, offert := range offered {430- if accepted == offert {431- return offert433+ }434+ for _, accepted := range c.Accepted {435+ for _, offert := range offered {436+ if accepted == offert {437+ return offert432- }438 }439 }435- return ""440 }441+ return ""442 }443 444 func (c *Context) SetAccepted(formats ...string) {440- c.accepted = formats445+ c.Accepted = formats446 }447+448+/************************************/449+/******** CONTENT NEGOTIATION *******/450+/************************************/451+452+func (c *Context) Deadline() (deadline time.Time, ok bool) {453+ return454+}455+456+func (c *Context) Done() <-chan struct{} {457+ return nil458+}459+460+func (c *Context) Err() error {461+ return nil462+}463+464+func (c *Context) Value(key interface{}) interface{} {465+ if key == 0 {466+ return c.Request467+ }468+ if keyAsString, ok := key.(string); ok {469+ val, _ := c.Get(keyAsString)470+ return val471+ }472+ return nil473+}added:debug_test.go+79 added
1+// Copyright 2014 Manu Martinez-Almeida. All rights reserved.2+// Use of this source code is governed by a MIT style3+// license that can be found in the LICENSE file.4+5+package gin6+7+import (8+ "bytes"9+ "errors"10+ "io"11+ "log"12+ "testing"13+14+ "github.com/stretchr/testify/assert"15+)16+17+var cachedDebugLogger *log.Logger = nil18+19+// TODO20+// func debugRoute(httpMethod, absolutePath string, handlers HandlersChain) {21+// func debugPrint(format string, values ...interface{}) {22+23+func TestIsDebugging(t *testing.T) {24+ SetMode(DebugMode)25+ assert.True(t, IsDebugging())26+ SetMode(ReleaseMode)27+ assert.False(t, IsDebugging())28+ SetMode(TestMode)29+ assert.False(t, IsDebugging())30+}31+32+func TestDebugPrint(t *testing.T) {33+ var w bytes.Buffer34+ setup(&w)35+ defer teardown()36+37+ SetMode(ReleaseMode)38+ debugPrint("DEBUG this!")39+ SetMode(TestMode)40+ debugPrint("DEBUG this!")41+ assert.Empty(t, w.String())42+43+ SetMode(DebugMode)44+ debugPrint("these are %d %s\n", 2, "error messages")45+ assert.Equal(t, w.String(), "[GIN-debug] these are 2 error messages\n")46+}47+48+func TestDebugPrintError(t *testing.T) {49+ var w bytes.Buffer50+ setup(&w)51+ defer teardown()52+53+ SetMode(DebugMode)54+ debugPrintError(nil)55+ assert.Empty(t, w.String())56+57+ debugPrintError(errors.New("this is an error"))58+ assert.Equal(t, w.String(), "[GIN-debug] [ERROR] this is an error\n")59+}60+61+func setup(w io.Writer) {62+ SetMode(DebugMode)63+ if cachedDebugLogger == nil {64+ cachedDebugLogger = debugLogger65+ debugLogger = log.New(w, debugLogger.Prefix(), 0)66+ } else {67+ panic("setup failed")68+ }69+}70+71+func teardown() {72+ SetMode(TestMode)73+ if cachedDebugLogger != nil {74+ debugLogger = cachedDebugLogger75+ cachedDebugLogger = nil76+ } else {77+ panic("teardown failed")78+ }79+}added:debug.go+40 added
1+// Copyright 2014 Manu Martinez-Almeida. All rights reserved.2+// Use of this source code is governed by a MIT style3+// license that can be found in the LICENSE file.4+5+package gin6+7+import (8+ "log"9+ "os"10+)11+12+var debugLogger = log.New(os.Stdout, "[GIN-debug] ", 0)13+14+func IsDebugging() bool {15+ return ginMode == debugCode16+}17+18+func debugPrintRoute(httpMethod, absolutePath string, handlers HandlersChain) {19+ if IsDebugging() {20+ nuHandlers := len(handlers)21+ handlerName := nameOfFunction(handlers[nuHandlers-1])22+ debugPrint("%-5s %-25s --> %s (%d handlers)\n", httpMethod, absolutePath, handlerName, nuHandlers)23+ }24+}25+26+func debugPrint(format string, values ...interface{}) {27+ if IsDebugging() {28+ debugLogger.Printf(format, values...)29+ }30+}31+32+func debugPrintWARNING() {33+ debugPrint("[WARNING] Running in DEBUG mode! Disable it before going production\n")34+}35+36+func debugPrintError(err error) {37+ if err != nil {38+ debugPrint("[ERROR] %v\n", err)39+ }40+}modified:deprecated.go-42 removed
1 unmodified line2 // Use of this source code is governed by a MIT style3 // license that can be found in the LICENSE file.4 5 package gin6-7-import (8- "github.com/gin-gonic/gin/binding"9- "net/http"10-)11-12-// DEPRECATED, use Bind() instead.13-// Like ParseBody() but this method also writes a 400 error if the json is not valid.14-func (c *Context) EnsureBody(item interface{}) bool {15- return c.Bind(item)16-}17-18-// DEPRECATED use bindings directly19-// Parses the body content as a JSON input. It decodes the json payload into the struct specified as a pointer.20-func (c *Context) ParseBody(item interface{}) error {21- return binding.JSON.Bind(c.Request, item)22-}23-24-// DEPRECATED use gin.Static() instead25-// ServeFiles serves files from the given file system root.26-// The path must end with "/*filepath", files are then served from the local27-// path /defined/root/dir/*filepath.28-// For example if root is "/etc" and *filepath is "passwd", the local file29-// "/etc/passwd" would be served.30-// Internally a http.FileServer is used, therefore http.NotFound is used instead31-// of the Router's NotFound handler.32-// To use the operating system's file system implementation,33-// use http.Dir:34-// router.ServeFiles("/src/*filepath", http.Dir("/var/www"))35-func (engine *Engine) ServeFiles(path string, root http.FileSystem) {36- engine.router.ServeFiles(path, root)37-}38-39-// DEPRECATED use gin.LoadHTMLGlob() or gin.LoadHTMLFiles() instead40-func (engine *Engine) LoadHTMLTemplates(pattern string) {41- engine.LoadHTMLGlob(pattern)42-}43-44-// DEPRECATED. Use NoRoute() instead45-func (engine *Engine) NotFound404(handlers ...HandlerFunc) {46- engine.NoRoute(handlers...)47-}added:errors_test.go+90 added
1+// Copyright 2014 Manu Martinez-Almeida. All rights reserved.2+// Use of this source code is governed by a MIT style3+// license that can be found in the LICENSE file.4+5+package gin6+7+import (8+ "errors"9+ "testing"10+11+ "github.com/stretchr/testify/assert"12+)13+14+func TestError(t *testing.T) {15+ baseError := errors.New("test error")16+ err := &Error{17+ Err: baseError,18+ Type: ErrorTypePrivate,19+ }20+ assert.Equal(t, err.Error(), baseError.Error())21+ assert.Equal(t, err.JSON(), H{"error": baseError.Error()})22+23+ assert.Equal(t, err.SetType(ErrorTypePublic), err)24+ assert.Equal(t, err.Type, ErrorTypePublic)25+26+ assert.Equal(t, err.SetMeta("some data"), err)27+ assert.Equal(t, err.Meta, "some data")28+ assert.Equal(t, err.JSON(), H{29+ "error": baseError.Error(),30+ "meta": "some data",31+ })32+33+ err.SetMeta(H{34+ "status": "200",35+ "data": "some data",36+ })37+ assert.Equal(t, err.JSON(), H{38+ "error": baseError.Error(),39+ "status": "200",40+ "data": "some data",41+ })42+43+ err.SetMeta(H{44+ "error": "custom error",45+ "status": "200",46+ "data": "some data",47+ })48+ assert.Equal(t, err.JSON(), H{49+ "error": "custom error",50+ "status": "200",51+ "data": "some data",52+ })53+}54+55+func TestErrorSlice(t *testing.T) {56+ errs := errorMsgs{57+ {Err: errors.New("first"), Type: ErrorTypePrivate},58+ {Err: errors.New("second"), Type: ErrorTypePrivate, Meta: "some data"},59+ {Err: errors.New("third"), Type: ErrorTypePublic, Meta: H{"status": "400"}},60+ }61+62+ assert.Equal(t, errs.Last().Error(), "third")63+ assert.Equal(t, errs.Errors(), []string{"first", "second", "third"})64+ assert.Equal(t, errs.ByType(ErrorTypePublic).Errors(), []string{"third"})65+ assert.Equal(t, errs.ByType(ErrorTypePrivate).Errors(), []string{"first", "second"})66+ assert.Equal(t, errs.ByType(ErrorTypePublic|ErrorTypePrivate).Errors(), []string{"first", "second", "third"})67+ assert.Empty(t, errs.ByType(ErrorTypeBind))68+69+ assert.Equal(t, errs.String(), `Error #01: first70+Error #02: second71+ Meta: some data72+Error #03: third73+ Meta: map[status:400]74+`)75+ assert.Equal(t, errs.JSON(), []interface{}{76+ H{"error": "first"},77+ H{"error": "second", "meta": "some data"},78+ H{"error": "third", "status": "400"},79+ })80+81+ errs = errorMsgs{82+ {Err: errors.New("first"), Type: ErrorTypePrivate},83+ }84+ assert.Equal(t, errs.JSON(), H{"error": "first"})85+86+ errs = errorMsgs{}87+ assert.Nil(t, errs.Last())88+ assert.Nil(t, errs.JSON())89+ assert.Empty(t, errs.String())90+}added:errors.go+128 added
1+// Copyright 2014 Manu Martinez-Almeida. All rights reserved.2+// Use of this source code is governed by a MIT style3+// license that can be found in the LICENSE file.4+5+package gin6+7+import (8+ "bytes"9+ "fmt"10+ "reflect"11+)12+13+const (14+ ErrorTypeBind = 1 << 3115+ ErrorTypeRender = 1 << 3016+ ErrorTypePrivate = 1 << 017+ ErrorTypePublic = 1 << 118+19+ ErrorTypeAny = 0xffffffff20+ ErrorTypeNu = 221+)22+23+// Used internally to collect errors that occurred during an http request.24+type Error struct {25+ Err error `json:"error"`26+ Type int `json:"-"`27+ Meta interface{} `json:"meta"`28+}29+30+var _ error = &Error{}31+32+func (msg *Error) SetType(flags int) *Error {33+ msg.Type = flags34+ return msg35+}36+37+func (msg *Error) SetMeta(data interface{}) *Error {38+ msg.Meta = data39+ return msg40+}41+42+func (msg *Error) JSON() interface{} {43+ json := H{}44+ if msg.Meta != nil {45+ value := reflect.ValueOf(msg.Meta)46+ switch value.Kind() {47+ case reflect.Struct:48+ return msg.Meta49+ case reflect.Map:50+ for _, key := range value.MapKeys() {51+ json[key.String()] = value.MapIndex(key).Interface()52+ }53+ default:54+ json["meta"] = msg.Meta55+ }56+ }57+ if _, ok := json["error"]; !ok {58+ json["error"] = msg.Error()59+ }60+ return json61+}62+63+func (msg *Error) Error() string {64+ return msg.Err.Error()65+}66+67+type errorMsgs []*Error68+69+func (a errorMsgs) ByType(typ int) errorMsgs {70+ if len(a) == 0 {71+ return a72+ }73+ result := make(errorMsgs, 0, len(a))74+ for _, msg := range a {75+ if msg.Type&typ > 0 {76+ result = append(result, msg)77+ }78+ }79+ return result80+}81+82+func (a errorMsgs) Last() *Error {83+ length := len(a)84+ if length == 0 {85+ return nil86+ }87+ return a[length-1]88+}89+90+func (a errorMsgs) Errors() []string {91+ if len(a) == 0 {92+ return []string{}93+ }94+ errorStrings := make([]string, len(a))95+ for i, err := range a {96+ errorStrings[i] = err.Error()97+ }98+ return errorStrings99+}100+101+func (a errorMsgs) JSON() interface{} {102+ switch len(a) {103+ case 0:104+ return nil105+ case 1:106+ return a.Last().JSON()107+ default:108+ json := make([]interface{}, len(a))109+ for i, err := range a {110+ json[i] = err.JSON()111+ }112+ return json113+ }114+}115+116+func (a errorMsgs) String() string {117+ if len(a) == 0 {118+ return ""119+ }120+ var buffer bytes.Buffer121+ for i, msg := range a {122+ fmt.Fprintf(&buffer, "Error #%02d: %s\n", (i + 1), msg.Err)123+ if msg.Meta != nil {124+ fmt.Fprintf(&buffer, " Meta: %v\n", msg.Meta)125+ }126+ }127+ return buffer.String()128+}modified:gin_test.go+111 added-167 removed
3 unmodified lines4 5 package gin6 7 import (8- "io/ioutil"9- "net/http"10- "net/http/httptest"11- "os"12- "path"13- "strings"8 "testing"9+10+ "github.com/stretchr/testify/assert"11 )12 13+//TODO14+// func (engine *Engine) LoadHTMLGlob(pattern string) {15+// func (engine *Engine) LoadHTMLFiles(files ...string) {16+// func (engine *Engine) Run(addr string) error {17+// func (engine *Engine) RunTLS(addr string, cert string, key string) error {18+19 func init() {20 SetMode(TestMode)21 }22 21-func PerformRequest(r http.Handler, method, path string) *httptest.ResponseRecorder {22- req, _ := http.NewRequest(method, path, nil)23- w := httptest.NewRecorder()24- r.ServeHTTP(w, req)25- return w23+func TestCreateEngine(t *testing.T) {24+ router := New()25+ assert.Equal(t, "/", router.BasePath)26+ assert.Equal(t, router.engine, router)27+ assert.Empty(t, router.Handlers)28+ assert.True(t, router.RedirectTrailingSlash)29+ assert.True(t, router.RedirectFixedPath)30+ assert.True(t, router.HandleMethodNotAllowed)31+32+ assert.Panics(t, func() { router.addRoute("", "/", HandlersChain{func(_ *Context) {}}) })33+ assert.Panics(t, func() { router.addRoute("GET", "a", HandlersChain{func(_ *Context) {}}) })34+ assert.Panics(t, func() { router.addRoute("GET", "/", HandlersChain{}) })35 }36 28-// TestSingleRouteOK tests that POST route is correctly invoked.29-func testRouteOK(method string, t *testing.T) {30- // SETUP31- passed := false32- r := New()33- r.Handle(method, "/test", []HandlerFunc{func(c *Context) {34- passed = true35- }})36-37- // RUN38- w := PerformRequest(r, method, "/test")39-40- // TEST41- if passed == false {42- t.Errorf(method + " route handler was not invoked.")43- }44- if w.Code != http.StatusOK {45- t.Errorf("Status code should be %v, was %d", http.StatusOK, w.Code)46- }37+func TestCreateDefaultRouter(t *testing.T) {38+ router := Default()39+ assert.Len(t, router.Handlers, 2)40 }48-func TestRouterGroupRouteOK(t *testing.T) {49- testRouteOK("POST", t)50- testRouteOK("DELETE", t)51- testRouteOK("PATCH", t)52- testRouteOK("PUT", t)53- testRouteOK("OPTIONS", t)54- testRouteOK("HEAD", t)55-}41 57-// TestSingleRouteOK tests that POST route is correctly invoked.58-func testRouteNotOK(method string, t *testing.T) {59- // SETUP60- passed := false61- r := New()62- r.Handle(method, "/test_2", []HandlerFunc{func(c *Context) {63- passed = true64- }})42+func TestNoRouteWithoutGlobalHandlers(t *testing.T) {43+ middleware0 := func(c *Context) {}44+ middleware1 := func(c *Context) {}45 66- // RUN67- w := PerformRequest(r, method, "/test")46+ router := New()47 69- // TEST70- if passed == true {71- t.Errorf(method + " route handler was invoked, when it should not")72- }73- if w.Code != http.StatusNotFound {74- // If this fails, it's because httprouter needs to be updated to at least f78f58a0db75- t.Errorf("Status code should be %v, was %d. Location: %s", http.StatusNotFound, w.Code, w.HeaderMap.Get("Location"))76- }77-}48+ router.NoRoute(middleware0)49+ assert.Nil(t, router.Handlers)50+ assert.Len(t, router.noRoute, 1)51+ assert.Len(t, router.allNoRoute, 1)52+ assert.Equal(t, router.noRoute[0], middleware0)53+ assert.Equal(t, router.allNoRoute[0], middleware0)54 79-// TestSingleRouteOK tests that POST route is correctly invoked.80-func TestRouteNotOK(t *testing.T) {81- testRouteNotOK("POST", t)82- testRouteNotOK("DELETE", t)83- testRouteNotOK("PATCH", t)84- testRouteNotOK("PUT", t)85- testRouteNotOK("OPTIONS", t)86- testRouteNotOK("HEAD", t)55+ router.NoRoute(middleware1, middleware0)56+ assert.Len(t, router.noRoute, 2)57+ assert.Len(t, router.allNoRoute, 2)58+ assert.Equal(t, router.noRoute[0], middleware1)59+ assert.Equal(t, router.allNoRoute[0], middleware1)60+ assert.Equal(t, router.noRoute[1], middleware0)61+ assert.Equal(t, router.allNoRoute[1], middleware0)62 }63 89-// TestSingleRouteOK tests that POST route is correctly invoked.90-func testRouteNotOK2(method string, t *testing.T) {91- // SETUP92- passed := false93- r := New()94- var methodRoute string95- if method == "POST" {96- methodRoute = "GET"97- } else {98- methodRoute = "POST"99- }100- r.Handle(methodRoute, "/test", []HandlerFunc{func(c *Context) {101- passed = true102- }})64+func TestNoRouteWithGlobalHandlers(t *testing.T) {65+ middleware0 := func(c *Context) {}66+ middleware1 := func(c *Context) {}67+ middleware2 := func(c *Context) {}68 104- // RUN105- w := PerformRequest(r, method, "/test")69+ router := New()70+ router.Use(middleware2)71 107- // TEST108- if passed == true {109- t.Errorf(method + " route handler was invoked, when it should not")110- }111- if w.Code != http.StatusMethodNotAllowed {112- t.Errorf("Status code should be %v, was %d. Location: %s", http.StatusMethodNotAllowed, w.Code, w.HeaderMap.Get("Location"))113- }114-}72+ router.NoRoute(middleware0)73+ assert.Len(t, router.allNoRoute, 2)74+ assert.Len(t, router.Handlers, 1)75+ assert.Len(t, router.noRoute, 1)76 116-// TestSingleRouteOK tests that POST route is correctly invoked.117-func TestRouteNotOK2(t *testing.T) {118- testRouteNotOK2("POST", t)119- testRouteNotOK2("DELETE", t)120- testRouteNotOK2("PATCH", t)121- testRouteNotOK2("PUT", t)122- testRouteNotOK2("OPTIONS", t)123- testRouteNotOK2("HEAD", t)77+ assert.Equal(t, router.Handlers[0], middleware2)78+ assert.Equal(t, router.noRoute[0], middleware0)79+ assert.Equal(t, router.allNoRoute[0], middleware2)80+ assert.Equal(t, router.allNoRoute[1], middleware0)81+82+ router.Use(middleware1)83+ assert.Len(t, router.allNoRoute, 3)84+ assert.Len(t, router.Handlers, 2)85+ assert.Len(t, router.noRoute, 1)86+87+ assert.Equal(t, router.Handlers[0], middleware2)88+ assert.Equal(t, router.Handlers[1], middleware1)89+ assert.Equal(t, router.noRoute[0], middleware0)90+ assert.Equal(t, router.allNoRoute[0], middleware2)91+ assert.Equal(t, router.allNoRoute[1], middleware1)92+ assert.Equal(t, router.allNoRoute[2], middleware0)93 }94 126-// TestHandleStaticFile - ensure the static file handles properly127-func TestHandleStaticFile(t *testing.T) {128- // SETUP file129- testRoot, _ := os.Getwd()130- f, err := ioutil.TempFile(testRoot, "")131- if err != nil {132- t.Error(err)133- }134- defer os.Remove(f.Name())135- filePath := path.Join("/", path.Base(f.Name()))136- f.WriteString("Gin Web Framework")137- f.Close()95+func TestNoMethodWithoutGlobalHandlers(t *testing.T) {96+ middleware0 := func(c *Context) {}97+ middleware1 := func(c *Context) {}98 139- // SETUP gin140- r := New()99+ router := New()141- r.Static("./", testRoot)100 143- // RUN144- w := PerformRequest(r, "GET", filePath)101+ router.NoMethod(middleware0)102+ assert.Empty(t, router.Handlers)103+ assert.Len(t, router.noMethod, 1)104+ assert.Len(t, router.allNoMethod, 1)105+ assert.Equal(t, router.noMethod[0], middleware0)106+ assert.Equal(t, router.allNoMethod[0], middleware0)107 146- // TEST147- if w.Code != 200 {148- t.Errorf("Response code should be 200, was: %d", w.Code)149- }150- if w.Body.String() != "Gin Web Framework" {151- t.Errorf("Response should be test, was: %s", w.Body.String())152- }153- if w.HeaderMap.Get("Content-Type") != "text/plain; charset=utf-8" {154- t.Errorf("Content-Type should be text/plain, was %s", w.HeaderMap.Get("Content-Type"))155- }108+ router.NoMethod(middleware1, middleware0)109+ assert.Len(t, router.noMethod, 2)110+ assert.Len(t, router.allNoMethod, 2)111+ assert.Equal(t, router.noMethod[0], middleware1)112+ assert.Equal(t, router.allNoMethod[0], middleware1)113+ assert.Equal(t, router.noMethod[1], middleware0)114+ assert.Equal(t, router.allNoMethod[1], middleware0)115 }116 158-// TestHandleStaticDir - ensure the root/sub dir handles properly159-func TestHandleStaticDir(t *testing.T) {117+func TestRebuild404Handlers(t *testing.T) {160- // SETUP161- r := New()162- r.Static("/", "./")118 164- // RUN165- w := PerformRequest(r, "GET", "/")166-167- // TEST168- bodyAsString := w.Body.String()169- if w.Code != 200 {170- t.Errorf("Response code should be 200, was: %d", w.Code)171- }172- if len(bodyAsString) == 0 {173- t.Errorf("Got empty body instead of file tree")174- }175- if !strings.Contains(bodyAsString, "gin.go") {176- t.Errorf("Can't find:`gin.go` in file tree: %s", bodyAsString)177- }178- if w.HeaderMap.Get("Content-Type") != "text/html; charset=utf-8" {179- t.Errorf("Content-Type should be text/plain, was %s", w.HeaderMap.Get("Content-Type"))180- }119 }120 183-// TestHandleHeadToDir - ensure the root/sub dir handles properly184-func TestHandleHeadToDir(t *testing.T) {185- // SETUP186- r := New()187- r.Static("/", "./")121+func TestNoMethodWithGlobalHandlers(t *testing.T) {122+ middleware0 := func(c *Context) {}123+ middleware1 := func(c *Context) {}124+ middleware2 := func(c *Context) {}125 189- // RUN190- w := PerformRequest(r, "HEAD", "/")126+ router := New()127+ router.Use(middleware2)128 192- // TEST193- bodyAsString := w.Body.String()194- if w.Code != 200 {195- t.Errorf("Response code should be Ok, was: %s", w.Code)196- }197- if len(bodyAsString) == 0 {198- t.Errorf("Got empty body instead of file tree")199- }200- if !strings.Contains(bodyAsString, "gin.go") {201- t.Errorf("Can't find:`gin.go` in file tree: %s", bodyAsString)202- }203- if w.HeaderMap.Get("Content-Type") != "text/html; charset=utf-8" {204- t.Errorf("Content-Type should be text/plain, was %s", w.HeaderMap.Get("Content-Type"))205- }129+ router.NoMethod(middleware0)130+ assert.Len(t, router.allNoMethod, 2)131+ assert.Len(t, router.Handlers, 1)132+ assert.Len(t, router.noMethod, 1)133+134+ assert.Equal(t, router.Handlers[0], middleware2)135+ assert.Equal(t, router.noMethod[0], middleware0)136+ assert.Equal(t, router.allNoMethod[0], middleware2)137+ assert.Equal(t, router.allNoMethod[1], middleware0)138+139+ router.Use(middleware1)140+ assert.Len(t, router.allNoMethod, 3)141+ assert.Len(t, router.Handlers, 2)142+ assert.Len(t, router.noMethod, 1)143+144+ assert.Equal(t, router.Handlers[0], middleware2)145+ assert.Equal(t, router.Handlers[1], middleware1)146+ assert.Equal(t, router.noMethod[0], middleware0)147+ assert.Equal(t, router.allNoMethod[0], middleware2)148+ assert.Equal(t, router.allNoMethod[1], middleware1)149+ assert.Equal(t, router.allNoMethod[2], middleware0)150 }modified:gin.go+207 added-81 removed
3 unmodified lines4 5 package gin6 7 import (8- "github.com/gin-gonic/gin/render"9- "github.com/julienschmidt/httprouter"8 "html/template"11- "math"9+ "net"10 "net/http"11+ "os"12 "sync"14-)13 16-const (17- AbortIndex = math.MaxInt8 / 218- MIMEJSON = "application/json"19- MIMEHTML = "text/html"20- MIMEXML = "application/xml"21- MIMEXML2 = "text/xml"22- MIMEPlain = "text/plain"23- MIMEPOSTForm = "application/x-www-form-urlencoded"24- MIMEMultipartPOSTForm = "multipart/form-data"14+ "github.com/gin-gonic/gin/binding"15+ "github.com/gin-gonic/gin/render"16 )17 18+const Version = "v1.0rc1"19+20+var default404Body = []byte("404 page not found")21+var default405Body = []byte("405 method not allowed")22+23 type (28- HandlerFunc func(*Context)24+ HandlerFunc func(*Context)25+ HandlersChain []HandlerFunc26 27 // Represents the web framework, it wraps the blazing fast httprouter multiplexer and a list of global middlewares.28 Engine struct {32- *RouterGroup33- HTMLRender render.Render34- Default404Body []byte35- Default405Body []byte36- pool sync.Pool37- allNoRouteNoMethod []HandlerFunc38- noRoute []HandlerFunc39- noMethod []HandlerFunc40- router *httprouter.Router29+ RouterGroup30+ HTMLRender render.HTMLRender31+ pool sync.Pool32+ allNoRoute HandlersChain33+ allNoMethod HandlersChain34+ noRoute HandlersChain35+ noMethod HandlersChain36+ trees map[string]*node37+38+ // Enables automatic redirection if the current route can't be matched but a39+ // handler for the path with (without) the trailing slash exists.40+ // For example if /foo/ is requested but a route only exists for /foo, the41+ // client is redirected to /foo with http status code 301 for GET requests42+ // and 307 for all other request methods.43+ RedirectTrailingSlash bool44+45+ // If enabled, the router tries to fix the current request path, if no46+ // handle is registered for it.47+ // First superfluous path elements like ../ or // are removed.48+ // Afterwards the router does a case-insensitive lookup of the cleaned path.49+ // If a handle can be found for this route, the router makes a redirection50+ // to the corrected path with status code 301 for GET requests and 307 for51+ // all other request methods.52+ // For example /FOO and /..//Foo could be redirected to /foo.53+ // RedirectTrailingSlash is independent of this option.54+ RedirectFixedPath bool55+56+ // If enabled, the router checks if another method is allowed for the57+ // current route, if the current request can not be routed.58+ // If this is the case, the request is answered with 'Method Not Allowed'59+ // and HTTP status code 405.60+ // If no other Method is allowed, the request is delegated to the NotFound61+ // handler.62+ HandleMethodNotAllowed bool63 }64 )65 66 // Returns a new blank Engine instance without any middleware attached.67 // The most basic configuration68 func New() *Engine {69+ debugPrintWARNING()47- engine := &Engine{}48- engine.RouterGroup = &RouterGroup{49- Handlers: nil,50- absolutePath: "/",51- engine: engine,70+ engine := &Engine{71+ RouterGroup: RouterGroup{72+ Handlers: nil,73+ BasePath: "/",74+ },75+ RedirectTrailingSlash: true,76+ RedirectFixedPath: true,77+ HandleMethodNotAllowed: true,78+ trees: make(map[string]*node),79 }53- engine.router = httprouter.New()54- engine.Default404Body = []byte("404 page not found")55- engine.Default405Body = []byte("405 method not allowed")56- engine.router.NotFound = engine.handle40457- engine.router.MethodNotAllowed = engine.handle40580+ engine.RouterGroup.engine = engine81 engine.pool.New = func() interface{} {59- c := &Context{Engine: engine}60- c.Writer = &c.writermem61- return c82+ return engine.allocateContext()83 }84 return engine85 }86 3 unmodified lines90 engine.Use(Recovery(), Logger())91 return engine92 }93 94+func (engine *Engine) allocateContext() (context *Context) {95+ return &Context{engine: engine}96+}97+98 func (engine *Engine) LoadHTMLGlob(pattern string) {99 if IsDebugging() {75- render.HTMLDebug.AddGlob(pattern)76- engine.HTMLRender = render.HTMLDebug100+ engine.HTMLRender = render.HTMLDebug{Glob: pattern}101 } else {102 templ := template.Must(template.ParseGlob(pattern))103 engine.SetHTMLTemplate(templ)104 }105 }106 107 func (engine *Engine) LoadHTMLFiles(files ...string) {108 if IsDebugging() {85- render.HTMLDebug.AddFiles(files...)86- engine.HTMLRender = render.HTMLDebug109+ engine.HTMLRender = render.HTMLDebug{Files: files}110 } else {111 templ := template.Must(template.ParseFiles(files...))112 engine.SetHTMLTemplate(templ)113 }114 }115 116 func (engine *Engine) SetHTMLTemplate(templ *template.Template) {94- engine.HTMLRender = render.HTMLRender{95- Template: templ,96- }117+ engine.HTMLRender = render.HTMLProduction{Template: templ}118 }119 120 // Adds handlers for NoRoute. It return a 404 code by default.121 func (engine *Engine) NoRoute(handlers ...HandlerFunc) {12 unmodified lines134 engine.rebuild405Handlers()135 }136 137 func (engine *Engine) rebuild404Handlers() {117- engine.allNoRouteNoMethod = engine.combineHandlers(engine.noRoute)138+ engine.allNoRoute = engine.combineHandlers(engine.noRoute)139 }140 141 func (engine *Engine) rebuild405Handlers() {121- engine.allNoRouteNoMethod = engine.combineHandlers(engine.noMethod)142+ engine.allNoMethod = engine.combineHandlers(engine.noMethod)143 }144 124-func (engine *Engine) handle404(w http.ResponseWriter, req *http.Request) {125- c := engine.createContext(w, req, nil, engine.allNoRouteNoMethod)126- // set 404 by default, useful for logging127- c.Writer.WriteHeader(404)128- c.Next()129- if !c.Writer.Written() {130- if c.Writer.Status() == 404 {131- c.Data(-1, MIMEPlain, engine.Default404Body)132- } else {133- c.Writer.WriteHeaderNow()134- }145+func (engine *Engine) addRoute(method, path string, handlers HandlersChain) {146+ debugPrintRoute(method, path, handlers)147+148+ if path[0] != '/' {149+ panic("path must begin with '/'")150 }136- engine.reuseContext(c)151+ if method == "" {152+ panic("HTTP method can not be empty")153+ }154+ if len(handlers) == 0 {155+ panic("there must be at least one handler")156+ }157+158+ root := engine.trees[method]159+ if root == nil {160+ root = new(node)161+ engine.trees[method] = root162+ }163+ root.addRoute(path, handlers)164 }165 139-func (engine *Engine) handle405(w http.ResponseWriter, req *http.Request) {140- c := engine.createContext(w, req, nil, engine.allNoRouteNoMethod)141- // set 405 by default, useful for logging142- c.Writer.WriteHeader(405)143- c.Next()144- if !c.Writer.Written() {145- if c.Writer.Status() == 405 {146- c.Data(-1, MIMEPlain, engine.Default405Body)147- } else {148- c.Writer.WriteHeaderNow()149- }166+func (engine *Engine) Run(addr string) (err error) {167+ debugPrint("Listening and serving HTTP on %s\n", addr)168+ defer func() { debugPrintError(err) }()169+170+ err = http.ListenAndServe(addr, engine)171+ return172+}173+174+func (engine *Engine) RunTLS(addr string, cert string, key string) (err error) {175+ debugPrint("Listening and serving HTTPS on %s\n", addr)176+ defer func() { debugPrintError(err) }()177+178+ err = http.ListenAndServe(addr, engine)179+ return180+}181+182+func (engine *Engine) RunUnix(file string) (err error) {183+ debugPrint("Listening and serving HTTP on unix:/%s", file)184+ defer func() { debugPrintError(err) }()185+186+ os.Remove(file)187+ listener, err := net.Listen("unix", file)188+ if err != nil {189+ return190 }151- engine.reuseContext(c)191+ defer listener.Close()192+ err = http.Serve(listener, engine)193+ return194 }195 196 // ServeHTTP makes the router implement the http.Handler interface.155-func (engine *Engine) ServeHTTP(writer http.ResponseWriter, request *http.Request) {156- engine.router.ServeHTTP(writer, request)197+func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {198+ c := engine.getcontext(w, req)199+ engine.handleHTTPRequest(c)200+ engine.putcontext(c)201 }202 159-func (engine *Engine) Run(addr string) error {160- debugPrint("Listening and serving HTTP on %s\n", addr)161- if err := http.ListenAndServe(addr, engine); err != nil {162- return err203+func (engine *Engine) getcontext(w http.ResponseWriter, req *http.Request) *Context {204+ c := engine.pool.Get().(*Context)205+ c.writermem.reset(w)206+ c.Request = req207+ c.reset()208+ return c209+}210+211+func (engine *Engine) putcontext(c *Context) {212+ engine.pool.Put(c)213+}214+215+func (engine *Engine) handleHTTPRequest(context *Context) {216+ httpMethod := context.Request.Method217+ path := context.Request.URL.Path218+219+ // Find root of the tree for the given HTTP method220+ if root := engine.trees[httpMethod]; root != nil {221+ // Find route in tree222+ handlers, params, tsr := root.getValue(path, context.Params)223+ if handlers != nil {224+ context.handlers = handlers225+ context.Params = params226+ context.Next()227+ context.writermem.WriteHeaderNow()228+ return229+230+ } else if httpMethod != "CONNECT" && path != "/" {231+ if engine.serveAutoRedirect(context, root, tsr) {232+ return233+ }234+ }235 }236+237+ if engine.HandleMethodNotAllowed {238+ for method, root := range engine.trees {239+ if method != httpMethod {240+ if handlers, _, _ := root.getValue(path, nil); handlers != nil {241+ context.handlers = engine.allNoMethod242+ serveError(context, 405, default405Body)164- return nil243+ return244+ }245+ }246+ }247+ }248+ context.handlers = engine.allNoRoute249+ serveError(context, 404, default404Body)250 }251 167-func (engine *Engine) RunTLS(addr string, cert string, key string) error {168- debugPrint("Listening and serving HTTPS on %s\n", addr)169- if err := http.ListenAndServeTLS(addr, cert, key, engine); err != nil {170- return err252+func (engine *Engine) serveAutoRedirect(c *Context, root *node, tsr bool) bool {253+ req := c.Request254+ path := req.URL.Path255+ code := 301 // Permanent redirect, request with GET method256+ if req.Method != "GET" {257+ code = 307258 }259+260+ if tsr && engine.RedirectTrailingSlash {261+ if len(path) > 1 && path[len(path)-1] == '/' {262+ req.URL.Path = path[:len(path)-1]263+ } else {264+ req.URL.Path = path + "/"265+ }266+ debugPrint("redirecting request %d: %s --> %s", code, path, req.URL.String())267+ http.Redirect(c.Writer, req, req.URL.String(), code)268+ c.writermem.WriteHeaderNow()172- return nil269+ return true270+ }271+272+ // Try to fix the request path273+ if engine.RedirectFixedPath {274+ fixedPath, found := root.findCaseInsensitivePath(275+ CleanPath(path),276+ engine.RedirectTrailingSlash,277+ )278+ if found {279+ req.URL.Path = string(fixedPath)280+ debugPrint("redirecting request %d: %s --> %s", code, path, req.URL.String())281+ http.Redirect(c.Writer, req, req.URL.String(), code)282+ c.writermem.WriteHeaderNow()283+ return true284+ }285+ }286+ return false287 }288+289+func serveError(c *Context, code int, defaultMessage []byte) {290+ c.writermem.status = code291+ c.Next()292+ if !c.Writer.Written() {293+ if c.Writer.Status() == code {294+ c.Data(-1, binding.MIMEPlain, defaultMessage)295+ } else {296+ c.Writer.WriteHeaderNow()297+ }298+ }299+}added:githubapi_test.go+344 added
1+// Copyright 2014 Manu Martinez-Almeida. All rights reserved.2+// Use of this source code is governed by a MIT style3+// license that can be found in the LICENSE file.4+5+package gin6+7+import (8+ "bytes"9+ "fmt"10+ "math/rand"11+ "testing"12+13+ "github.com/stretchr/testify/assert"14+)15+16+type route struct {17+ method string18+ path string19+}20+21+// http://developer.github.com/v3/22+var githubAPI = []route{23+ // OAuth Authorizations24+ {"GET", "/authorizations"},25+ {"GET", "/authorizations/:id"},26+ {"POST", "/authorizations"},27+ //{"PUT", "/authorizations/clients/:client_id"},28+ //{"PATCH", "/authorizations/:id"},29+ {"DELETE", "/authorizations/:id"},30+ {"GET", "/applications/:client_id/tokens/:access_token"},31+ {"DELETE", "/applications/:client_id/tokens"},32+ {"DELETE", "/applications/:client_id/tokens/:access_token"},33+34+ // Activity35+ {"GET", "/events"},36+ {"GET", "/repos/:owner/:repo/events"},37+ {"GET", "/networks/:owner/:repo/events"},38+ {"GET", "/orgs/:org/events"},39+ {"GET", "/users/:user/received_events"},40+ {"GET", "/users/:user/received_events/public"},41+ {"GET", "/users/:user/events"},42+ {"GET", "/users/:user/events/public"},43+ {"GET", "/users/:user/events/orgs/:org"},44+ {"GET", "/feeds"},45+ {"GET", "/notifications"},46+ {"GET", "/repos/:owner/:repo/notifications"},47+ {"PUT", "/notifications"},48+ {"PUT", "/repos/:owner/:repo/notifications"},49+ {"GET", "/notifications/threads/:id"},50+ //{"PATCH", "/notifications/threads/:id"},51+ {"GET", "/notifications/threads/:id/subscription"},52+ {"PUT", "/notifications/threads/:id/subscription"},53+ {"DELETE", "/notifications/threads/:id/subscription"},54+ {"GET", "/repos/:owner/:repo/stargazers"},55+ {"GET", "/users/:user/starred"},56+ {"GET", "/user/starred"},57+ {"GET", "/user/starred/:owner/:repo"},58+ {"PUT", "/user/starred/:owner/:repo"},59+ {"DELETE", "/user/starred/:owner/:repo"},60+ {"GET", "/repos/:owner/:repo/subscribers"},61+ {"GET", "/users/:user/subscriptions"},62+ {"GET", "/user/subscriptions"},63+ {"GET", "/repos/:owner/:repo/subscription"},64+ {"PUT", "/repos/:owner/:repo/subscription"},65+ {"DELETE", "/repos/:owner/:repo/subscription"},66+ {"GET", "/user/subscriptions/:owner/:repo"},67+ {"PUT", "/user/subscriptions/:owner/:repo"},68+ {"DELETE", "/user/subscriptions/:owner/:repo"},69+70+ // Gists71+ {"GET", "/users/:user/gists"},72+ {"GET", "/gists"},73+ //{"GET", "/gists/public"},74+ //{"GET", "/gists/starred"},75+ {"GET", "/gists/:id"},76+ {"POST", "/gists"},77+ //{"PATCH", "/gists/:id"},78+ {"PUT", "/gists/:id/star"},79+ {"DELETE", "/gists/:id/star"},80+ {"GET", "/gists/:id/star"},81+ {"POST", "/gists/:id/forks"},82+ {"DELETE", "/gists/:id"},83+84+ // Git Data85+ {"GET", "/repos/:owner/:repo/git/blobs/:sha"},86+ {"POST", "/repos/:owner/:repo/git/blobs"},87+ {"GET", "/repos/:owner/:repo/git/commits/:sha"},88+ {"POST", "/repos/:owner/:repo/git/commits"},89+ //{"GET", "/repos/:owner/:repo/git/refs/*ref"},90+ {"GET", "/repos/:owner/:repo/git/refs"},91+ {"POST", "/repos/:owner/:repo/git/refs"},92+ //{"PATCH", "/repos/:owner/:repo/git/refs/*ref"},93+ //{"DELETE", "/repos/:owner/:repo/git/refs/*ref"},94+ {"GET", "/repos/:owner/:repo/git/tags/:sha"},95+ {"POST", "/repos/:owner/:repo/git/tags"},96+ {"GET", "/repos/:owner/:repo/git/trees/:sha"},97+ {"POST", "/repos/:owner/:repo/git/trees"},98+99+ // Issues100+ {"GET", "/issues"},101+ {"GET", "/user/issues"},102+ {"GET", "/orgs/:org/issues"},103+ {"GET", "/repos/:owner/:repo/issues"},104+ {"GET", "/repos/:owner/:repo/issues/:number"},105+ {"POST", "/repos/:owner/:repo/issues"},106+ //{"PATCH", "/repos/:owner/:repo/issues/:number"},107+ {"GET", "/repos/:owner/:repo/assignees"},108+ {"GET", "/repos/:owner/:repo/assignees/:assignee"},109+ {"GET", "/repos/:owner/:repo/issues/:number/comments"},110+ //{"GET", "/repos/:owner/:repo/issues/comments"},111+ //{"GET", "/repos/:owner/:repo/issues/comments/:id"},112+ {"POST", "/repos/:owner/:repo/issues/:number/comments"},113+ //{"PATCH", "/repos/:owner/:repo/issues/comments/:id"},114+ //{"DELETE", "/repos/:owner/:repo/issues/comments/:id"},115+ {"GET", "/repos/:owner/:repo/issues/:number/events"},116+ //{"GET", "/repos/:owner/:repo/issues/events"},117+ //{"GET", "/repos/:owner/:repo/issues/events/:id"},118+ {"GET", "/repos/:owner/:repo/labels"},119+ {"GET", "/repos/:owner/:repo/labels/:name"},120+ {"POST", "/repos/:owner/:repo/labels"},121+ //{"PATCH", "/repos/:owner/:repo/labels/:name"},122+ {"DELETE", "/repos/:owner/:repo/labels/:name"},123+ {"GET", "/repos/:owner/:repo/issues/:number/labels"},124+ {"POST", "/repos/:owner/:repo/issues/:number/labels"},125+ {"DELETE", "/repos/:owner/:repo/issues/:number/labels/:name"},126+ {"PUT", "/repos/:owner/:repo/issues/:number/labels"},127+ {"DELETE", "/repos/:owner/:repo/issues/:number/labels"},128+ {"GET", "/repos/:owner/:repo/milestones/:number/labels"},129+ {"GET", "/repos/:owner/:repo/milestones"},130+ {"GET", "/repos/:owner/:repo/milestones/:number"},131+ {"POST", "/repos/:owner/:repo/milestones"},132+ //{"PATCH", "/repos/:owner/:repo/milestones/:number"},133+ {"DELETE", "/repos/:owner/:repo/milestones/:number"},134+135+ // Miscellaneous136+ {"GET", "/emojis"},137+ {"GET", "/gitignore/templates"},138+ {"GET", "/gitignore/templates/:name"},139+ {"POST", "/markdown"},140+ {"POST", "/markdown/raw"},141+ {"GET", "/meta"},142+ {"GET", "/rate_limit"},143+144+ // Organizations145+ {"GET", "/users/:user/orgs"},146+ {"GET", "/user/orgs"},147+ {"GET", "/orgs/:org"},148+ //{"PATCH", "/orgs/:org"},149+ {"GET", "/orgs/:org/members"},150+ {"GET", "/orgs/:org/members/:user"},151+ {"DELETE", "/orgs/:org/members/:user"},152+ {"GET", "/orgs/:org/public_members"},153+ {"GET", "/orgs/:org/public_members/:user"},154+ {"PUT", "/orgs/:org/public_members/:user"},155+ {"DELETE", "/orgs/:org/public_members/:user"},156+ {"GET", "/orgs/:org/teams"},157+ {"GET", "/teams/:id"},158+ {"POST", "/orgs/:org/teams"},159+ //{"PATCH", "/teams/:id"},160+ {"DELETE", "/teams/:id"},161+ {"GET", "/teams/:id/members"},162+ {"GET", "/teams/:id/members/:user"},163+ {"PUT", "/teams/:id/members/:user"},164+ {"DELETE", "/teams/:id/members/:user"},165+ {"GET", "/teams/:id/repos"},166+ {"GET", "/teams/:id/repos/:owner/:repo"},167+ {"PUT", "/teams/:id/repos/:owner/:repo"},168+ {"DELETE", "/teams/:id/repos/:owner/:repo"},169+ {"GET", "/user/teams"},170+171+ // Pull Requests172+ {"GET", "/repos/:owner/:repo/pulls"},173+ {"GET", "/repos/:owner/:repo/pulls/:number"},174+ {"POST", "/repos/:owner/:repo/pulls"},175+ //{"PATCH", "/repos/:owner/:repo/pulls/:number"},176+ {"GET", "/repos/:owner/:repo/pulls/:number/commits"},177+ {"GET", "/repos/:owner/:repo/pulls/:number/files"},178+ {"GET", "/repos/:owner/:repo/pulls/:number/merge"},179+ {"PUT", "/repos/:owner/:repo/pulls/:number/merge"},180+ {"GET", "/repos/:owner/:repo/pulls/:number/comments"},181+ //{"GET", "/repos/:owner/:repo/pulls/comments"},182+ //{"GET", "/repos/:owner/:repo/pulls/comments/:number"},183+ {"PUT", "/repos/:owner/:repo/pulls/:number/comments"},184+ //{"PATCH", "/repos/:owner/:repo/pulls/comments/:number"},185+ //{"DELETE", "/repos/:owner/:repo/pulls/comments/:number"},186+187+ // Repositories188+ {"GET", "/user/repos"},189+ {"GET", "/users/:user/repos"},190+ {"GET", "/orgs/:org/repos"},191+ {"GET", "/repositories"},192+ {"POST", "/user/repos"},193+ {"POST", "/orgs/:org/repos"},194+ {"GET", "/repos/:owner/:repo"},195+ //{"PATCH", "/repos/:owner/:repo"},196+ {"GET", "/repos/:owner/:repo/contributors"},197+ {"GET", "/repos/:owner/:repo/languages"},198+ {"GET", "/repos/:owner/:repo/teams"},199+ {"GET", "/repos/:owner/:repo/tags"},200+ {"GET", "/repos/:owner/:repo/branches"},201+ {"GET", "/repos/:owner/:repo/branches/:branch"},202+ {"DELETE", "/repos/:owner/:repo"},203+ {"GET", "/repos/:owner/:repo/collaborators"},204+ {"GET", "/repos/:owner/:repo/collaborators/:user"},205+ {"PUT", "/repos/:owner/:repo/collaborators/:user"},206+ {"DELETE", "/repos/:owner/:repo/collaborators/:user"},207+ {"GET", "/repos/:owner/:repo/comments"},208+ {"GET", "/repos/:owner/:repo/commits/:sha/comments"},209+ {"POST", "/repos/:owner/:repo/commits/:sha/comments"},210+ {"GET", "/repos/:owner/:repo/comments/:id"},211+ //{"PATCH", "/repos/:owner/:repo/comments/:id"},212+ {"DELETE", "/repos/:owner/:repo/comments/:id"},213+ {"GET", "/repos/:owner/:repo/commits"},214+ {"GET", "/repos/:owner/:repo/commits/:sha"},215+ {"GET", "/repos/:owner/:repo/readme"},216+ //{"GET", "/repos/:owner/:repo/contents/*path"},217+ //{"PUT", "/repos/:owner/:repo/contents/*path"},218+ //{"DELETE", "/repos/:owner/:repo/contents/*path"},219+ //{"GET", "/repos/:owner/:repo/:archive_format/:ref"},220+ {"GET", "/repos/:owner/:repo/keys"},221+ {"GET", "/repos/:owner/:repo/keys/:id"},222+ {"POST", "/repos/:owner/:repo/keys"},223+ //{"PATCH", "/repos/:owner/:repo/keys/:id"},224+ {"DELETE", "/repos/:owner/:repo/keys/:id"},225+ {"GET", "/repos/:owner/:repo/downloads"},226+ {"GET", "/repos/:owner/:repo/downloads/:id"},227+ {"DELETE", "/repos/:owner/:repo/downloads/:id"},228+ {"GET", "/repos/:owner/:repo/forks"},229+ {"POST", "/repos/:owner/:repo/forks"},230+ {"GET", "/repos/:owner/:repo/hooks"},231+ {"GET", "/repos/:owner/:repo/hooks/:id"},232+ {"POST", "/repos/:owner/:repo/hooks"},233+ //{"PATCH", "/repos/:owner/:repo/hooks/:id"},234+ {"POST", "/repos/:owner/:repo/hooks/:id/tests"},235+ {"DELETE", "/repos/:owner/:repo/hooks/:id"},236+ {"POST", "/repos/:owner/:repo/merges"},237+ {"GET", "/repos/:owner/:repo/releases"},238+ {"GET", "/repos/:owner/:repo/releases/:id"},239+ {"POST", "/repos/:owner/:repo/releases"},240+ //{"PATCH", "/repos/:owner/:repo/releases/:id"},241+ {"DELETE", "/repos/:owner/:repo/releases/:id"},242+ {"GET", "/repos/:owner/:repo/releases/:id/assets"},243+ {"GET", "/repos/:owner/:repo/stats/contributors"},244+ {"GET", "/repos/:owner/:repo/stats/commit_activity"},245+ {"GET", "/repos/:owner/:repo/stats/code_frequency"},246+ {"GET", "/repos/:owner/:repo/stats/participation"},247+ {"GET", "/repos/:owner/:repo/stats/punch_card"},248+ {"GET", "/repos/:owner/:repo/statuses/:ref"},249+ {"POST", "/repos/:owner/:repo/statuses/:ref"},250+251+ // Search252+ {"GET", "/search/repositories"},253+ {"GET", "/search/code"},254+ {"GET", "/search/issues"},255+ {"GET", "/search/users"},256+ {"GET", "/legacy/issues/search/:owner/:repository/:state/:keyword"},257+ {"GET", "/legacy/repos/search/:keyword"},258+ {"GET", "/legacy/user/search/:keyword"},259+ {"GET", "/legacy/user/email/:email"},260+261+ // Users262+ {"GET", "/users/:user"},263+ {"GET", "/user"},264+ //{"PATCH", "/user"},265+ {"GET", "/users"},266+ {"GET", "/user/emails"},267+ {"POST", "/user/emails"},268+ {"DELETE", "/user/emails"},269+ {"GET", "/users/:user/followers"},270+ {"GET", "/user/followers"},271+ {"GET", "/users/:user/following"},272+ {"GET", "/user/following"},273+ {"GET", "/user/following/:user"},274+ {"GET", "/users/:user/following/:target_user"},275+ {"PUT", "/user/following/:user"},276+ {"DELETE", "/user/following/:user"},277+ {"GET", "/users/:user/keys"},278+ {"GET", "/user/keys"},279+ {"GET", "/user/keys/:id"},280+ {"POST", "/user/keys"},281+ //{"PATCH", "/user/keys/:id"},282+ {"DELETE", "/user/keys/:id"},283+}284+285+func TestGithubAPI(t *testing.T) {286+ router := New()287+288+ for _, route := range githubAPI {289+ router.Handle(route.method, route.path, func(c *Context) {290+ output := H{"status": "good"}291+ for _, param := range c.Params {292+ output[param.Key] = param.Value293+ }294+ c.JSON(200, output)295+ })296+ }297+298+ for _, route := range githubAPI {299+ path, values := exampleFromPath(route.path)300+ w := performRequest(router, route.method, path)301+302+ // TEST303+ assert.Contains(t, w.Body.String(), "\"status\":\"good\"")304+ for _, value := range values {305+ str := fmt.Sprintf("\"%s\":\"%s\"", value.Key, value.Value)306+ assert.Contains(t, w.Body.String(), str)307+ }308+ }309+}310+311+func exampleFromPath(path string) (string, Params) {312+ output := new(bytes.Buffer)313+ params := make(Params, 0, 6)314+ start := -1315+ for i, c := range path {316+ if c == ':' {317+ start = i + 1318+ }319+ if start >= 0 {320+ if c == '/' {321+ value := fmt.Sprint(rand.Intn(100000))322+ params = append(params, Param{323+ Key: path[start:i],324+ Value: value,325+ })326+ output.WriteString(value)327+ output.WriteRune(c)328+ start = -1329+ }330+ } else {331+ output.WriteRune(c)332+ }333+ }334+ if start >= 0 {335+ value := fmt.Sprint(rand.Intn(100000))336+ params = append(params, Param{337+ Key: path[start:len(path)],338+ Value: value,339+ })340+ output.WriteString(value)341+ }342+343+ return output.String(), params344+}added:logger_test.go+35 added
1+// Copyright 2014 Manu Martinez-Almeida. All rights reserved.2+// Use of this source code is governed by a MIT style3+// license that can be found in the LICENSE file.4+5+package gin6+7+import (8+ "bytes"9+ "testing"10+11+ "github.com/stretchr/testify/assert"12+)13+14+//TODO15+// func (engine *Engine) LoadHTMLGlob(pattern string) {16+// func (engine *Engine) LoadHTMLFiles(files ...string) {17+// func (engine *Engine) Run(addr string) error {18+// func (engine *Engine) RunTLS(addr string, cert string, key string) error {19+20+func init() {21+ SetMode(TestMode)22+}23+24+func TestLogger(t *testing.T) {25+ buffer := new(bytes.Buffer)26+ router := New()27+ router.Use(LoggerWithWriter(buffer))28+ router.GET("/example", func(c *Context) {})29+30+ performRequest(router, "GET", "/example")31+32+ assert.Contains(t, buffer.String(), "200")33+ assert.Contains(t, buffer.String(), "GET")34+ assert.Contains(t, buffer.String(), "/example")35+}modified:logger.go+28 added-24 removed
3 unmodified lines4 5 package gin6 7 import (8- "github.com/mattn/go-colorable"9- "log"8+ "fmt"9+ "io"10 "time"11 )12 13 var (7 unmodified lines21 reset = string([]byte{27, 91, 48, 109})22 )23 24 func ErrorLogger() HandlerFunc {25- return ErrorLoggerT(ErrorTypeAll)25+ return ErrorLoggerT(ErrorTypeAny)26 }27 28-func ErrorLoggerT(typ uint32) HandlerFunc {28+func ErrorLoggerT(typ int) HandlerFunc {29 return func(c *Context) {30 c.Next()31 32- errs := c.Errors.ByType(typ)33- if len(errs) > 0 {34- // -1 status code = do not change current one35- c.JSON(-1, c.Errors)32+ if !c.Writer.Written() {33+ json := c.Errors.ByType(typ).JSON()34+ if json != nil {35+ c.JSON(-1, json)36+ }37 }38 }39 }40 41 func Logger() HandlerFunc {41- stdlogger := log.New(colorable.NewColorableStdout(), "", 0)42- //errlogger := log.New(os.Stderr, "", 0)42+ return LoggerWithWriter(DefaultWriter)43+}44 45+func LoggerWithWriter(out io.Writer) HandlerFunc {46 return func(c *Context) {47 // Start timer48 start := time.Now()49+ path := c.Request.URL.Path50 51 // Process request52 c.Next()53 5 unmodified lines59 method := c.Request.Method60 statusCode := c.Writer.Status()61 statusColor := colorForStatus(statusCode)62 methodColor := colorForMethod(method)63+ comment := c.Errors.String()64 61- stdlogger.Printf("[GIN] %v |%s %3d %s| %12v | %s |%s %s %-7s %s\n%s",65+ fmt.Fprintf(out, "[GIN] %v |%s %3d %s| %13v | %s |%s %s %-7s %s\n%s",66 end.Format("2006/01/02 - 15:04:05"),67 statusColor, statusCode, reset,68 latency,69 clientIP,70 methodColor, reset, method,67- c.Request.URL.Path,68- c.Errors.String(),71+ path,72+ comment,73 )74 }75 }76 77 func colorForStatus(code int) string {78 switch {75- case code >= 200 && code <= 299:79+ case code >= 200 && code < 300:80 return green77- case code >= 300 && code <= 399:81+ case code >= 300 && code < 400:82 return white79- case code >= 400 && code <= 499:83+ case code >= 400 && code < 500:84 return yellow85 default:86 return red87 }88 }89 90 func colorForMethod(method string) string {87- switch {88- case method == "GET":91+ switch method {92+ case "GET":93 return blue90- case method == "POST":94+ case "POST":95 return cyan92- case method == "PUT":96+ case "PUT":97 return yellow94- case method == "DELETE":98+ case "DELETE":99 return red96- case method == "PATCH":100+ case "PATCH":101 return green98- case method == "HEAD":102+ case "HEAD":103 return magenta100- case method == "OPTIONS":104+ case "OPTIONS":105 return white106 default:107 return reset108 }1 unmodified lineadded:middleware_test.go+217 added
1+// Copyright 2014 Manu Martinez-Almeida. All rights reserved.2+// Use of this source code is governed by a MIT style3+// license that can be found in the LICENSE file.4+5+package gin6+7+import (8+ "errors"9+10+ "testing"11+12+ "github.com/manucorporat/sse"13+ "github.com/stretchr/testify/assert"14+)15+16+func TestMiddlewareGeneralCase(t *testing.T) {17+ signature := ""18+ router := New()19+ router.Use(func(c *Context) {20+ signature += "A"21+ c.Next()22+ signature += "B"23+ })24+ router.Use(func(c *Context) {25+ signature += "C"26+ })27+ router.GET("/", func(c *Context) {28+ signature += "D"29+ })30+ router.NoRoute(func(c *Context) {31+ signature += " X "32+ })33+ router.NoMethod(func(c *Context) {34+ signature += " XX "35+ })36+ // RUN37+ w := performRequest(router, "GET", "/")38+39+ // TEST40+ assert.Equal(t, w.Code, 200)41+ assert.Equal(t, signature, "ACDB")42+}43+44+func TestMiddlewareNoRoute(t *testing.T) {45+ signature := ""46+ router := New()47+ router.Use(func(c *Context) {48+ signature += "A"49+ c.Next()50+ signature += "B"51+ })52+ router.Use(func(c *Context) {53+ signature += "C"54+ c.Next()55+ c.Next()56+ c.Next()57+ c.Next()58+ signature += "D"59+ })60+ router.NoRoute(func(c *Context) {61+ signature += "E"62+ c.Next()63+ signature += "F"64+ }, func(c *Context) {65+ signature += "G"66+ c.Next()67+ signature += "H"68+ })69+ router.NoMethod(func(c *Context) {70+ signature += " X "71+ })72+ // RUN73+ w := performRequest(router, "GET", "/")74+75+ // TEST76+ assert.Equal(t, w.Code, 404)77+ assert.Equal(t, signature, "ACEGHFDB")78+}79+80+func TestMiddlewareNoMethod(t *testing.T) {81+ signature := ""82+ router := New()83+ router.Use(func(c *Context) {84+ signature += "A"85+ c.Next()86+ signature += "B"87+ })88+ router.Use(func(c *Context) {89+ signature += "C"90+ c.Next()91+ signature += "D"92+ })93+ router.NoMethod(func(c *Context) {94+ signature += "E"95+ c.Next()96+ signature += "F"97+ }, func(c *Context) {98+ signature += "G"99+ c.Next()100+ signature += "H"101+ })102+ router.NoRoute(func(c *Context) {103+ signature += " X "104+ })105+ router.POST("/", func(c *Context) {106+ signature += " XX "107+ })108+ // RUN109+ w := performRequest(router, "GET", "/")110+111+ // TEST112+ assert.Equal(t, w.Code, 405)113+ assert.Equal(t, signature, "ACEGHFDB")114+}115+116+func TestMiddlewareAbort(t *testing.T) {117+ signature := ""118+ router := New()119+ router.Use(func(c *Context) {120+ signature += "A"121+ })122+ router.Use(func(c *Context) {123+ signature += "C"124+ c.AbortWithStatus(401)125+ c.Next()126+ signature += "D"127+ })128+ router.GET("/", func(c *Context) {129+ signature += " X "130+ c.Next()131+ signature += " XX "132+ })133+134+ // RUN135+ w := performRequest(router, "GET", "/")136+137+ // TEST138+ assert.Equal(t, w.Code, 401)139+ assert.Equal(t, signature, "ACD")140+}141+142+func TestMiddlewareAbortHandlersChainAndNext(t *testing.T) {143+ signature := ""144+ router := New()145+ router.Use(func(c *Context) {146+ signature += "A"147+ c.Next()148+ c.AbortWithStatus(410)149+ signature += "B"150+151+ })152+ router.GET("/", func(c *Context) {153+ signature += "C"154+ c.Next()155+ })156+ // RUN157+ w := performRequest(router, "GET", "/")158+159+ // TEST160+ assert.Equal(t, w.Code, 410)161+ assert.Equal(t, signature, "ACB")162+}163+164+// TestFailHandlersChain - ensure that Fail interrupt used middlewares in fifo order as165+// as well as Abort166+func TestMiddlewareFailHandlersChain(t *testing.T) {167+ // SETUP168+ signature := ""169+ router := New()170+ router.Use(func(context *Context) {171+ signature += "A"172+ context.AbortWithError(500, errors.New("foo"))173+ })174+ router.Use(func(context *Context) {175+ signature += "B"176+ context.Next()177+ signature += "C"178+ })179+ // RUN180+ w := performRequest(router, "GET", "/")181+182+ // TEST183+ assert.Equal(t, w.Code, 500)184+ assert.Equal(t, signature, "A")185+}186+187+func TestMiddlewareWrite(t *testing.T) {188+ router := New()189+ router.Use(func(c *Context) {190+ c.String(400, "hola\n")191+ })192+ router.Use(func(c *Context) {193+ c.XML(400, H{"foo": "bar"})194+ })195+ router.Use(func(c *Context) {196+ c.JSON(400, H{"foo": "bar"})197+ })198+ router.GET("/", func(c *Context) {199+ c.JSON(400, H{"foo": "bar"})200+ }, func(c *Context) {201+ c.Render(400, sse.Event{202+ Event: "test",203+ Data: "message",204+ })205+ })206+207+ w := performRequest(router, "GET", "/")208+209+ assert.Equal(t, w.Code, 400)210+ assert.Equal(t, w.Body.String(), `hola211+<map><foo>bar</foo></map>{"foo":"bar"}212+{"foo":"bar"}213+event: test214+data: message215+216+`)217+}added:mode_test.go+31 added
1+// Copyright 2014 Manu Martinez-Almeida. All rights reserved.2+// Use of this source code is governed by a MIT style3+// license that can be found in the LICENSE file.4+5+package gin6+7+import (8+ "testing"9+10+ "github.com/stretchr/testify/assert"11+)12+13+func init() {14+ SetMode(TestMode)15+}16+17+func TestSetMode(t *testing.T) {18+ SetMode(DebugMode)19+ assert.Equal(t, ginMode, debugCode)20+ assert.Equal(t, Mode(), DebugMode)21+22+ SetMode(ReleaseMode)23+ assert.Equal(t, ginMode, releaseCode)24+ assert.Equal(t, Mode(), ReleaseMode)25+26+ SetMode(TestMode)27+ assert.Equal(t, ginMode, testCode)28+ assert.Equal(t, Mode(), TestMode)29+30+ assert.Panics(t, func() { SetMode("unknown") })31+}modified:mode.go+15 added-22 removed
3 unmodified lines4 5 package gin6 7 import (8- "fmt"8+ "io"9 "os"10+11+ "github.com/mattn/go-colorable"12 )13 12-const GIN_MODE = "GIN_MODE"14+const ENV_GIN_MODE = "GIN_MODE"15 16 const (17 DebugMode string = "debug"18 ReleaseMode string = "release"4 unmodified lines23 releaseCode = iota24 testCode = iota25 )26 27+var DefaultWriter io.Writer = colorable.NewColorableStdout()25-var gin_mode int = debugCode26-var mode_name string = DebugMode28+var ginMode int = debugCode29+var modeName string = DebugMode30 31 func init() {29- value := os.Getenv(GIN_MODE)30- if len(value) == 0 {32+ mode := os.Getenv(ENV_GIN_MODE)33+ if len(mode) == 0 {34 SetMode(DebugMode)35 } else {33- SetMode(value)36+ SetMode(mode)37 }38 }39 40 func SetMode(value string) {41 switch value {42 case DebugMode:40- gin_mode = debugCode43+ ginMode = debugCode44 case ReleaseMode:42- gin_mode = releaseCode45+ ginMode = releaseCode46 case TestMode:44- gin_mode = testCode47+ ginMode = testCode48 default:49 panic("gin mode unknown: " + value)50 }48- mode_name = value51+ modeName = value52 }53 54 func Mode() string {52- return mode_name55+ return modeName56 }54-55-func IsDebugging() bool {56- return gin_mode == debugCode57-}58-59-func debugPrint(format string, values ...interface{}) {60- if IsDebugging() {61- fmt.Printf("[GIN-debug] "+format, values...)62- }63-}added:path_test.go+88 added
1+// Copyright 2013 Julien Schmidt. All rights reserved.2+// Based on the path package, Copyright 2009 The Go Authors.3+// Use of this source code is governed by a BSD-style license that can be found4+// in the LICENSE file.5+6+package gin7+8+import (9+ "runtime"10+ "testing"11+12+ "github.com/stretchr/testify/assert"13+)14+15+var cleanTests = []struct {16+ path, result string17+}{18+ // Already clean19+ {"/", "/"},20+ {"/abc", "/abc"},21+ {"/a/b/c", "/a/b/c"},22+ {"/abc/", "/abc/"},23+ {"/a/b/c/", "/a/b/c/"},24+25+ // missing root26+ {"", "/"},27+ {"abc", "/abc"},28+ {"abc/def", "/abc/def"},29+ {"a/b/c", "/a/b/c"},30+31+ // Remove doubled slash32+ {"//", "/"},33+ {"/abc//", "/abc/"},34+ {"/abc/def//", "/abc/def/"},35+ {"/a/b/c//", "/a/b/c/"},36+ {"/abc//def//ghi", "/abc/def/ghi"},37+ {"//abc", "/abc"},38+ {"///abc", "/abc"},39+ {"//abc//", "/abc/"},40+41+ // Remove . elements42+ {".", "/"},43+ {"./", "/"},44+ {"/abc/./def", "/abc/def"},45+ {"/./abc/def", "/abc/def"},46+ {"/abc/.", "/abc/"},47+48+ // Remove .. elements49+ {"..", "/"},50+ {"../", "/"},51+ {"../../", "/"},52+ {"../..", "/"},53+ {"../../abc", "/abc"},54+ {"/abc/def/ghi/../jkl", "/abc/def/jkl"},55+ {"/abc/def/../ghi/../jkl", "/abc/jkl"},56+ {"/abc/def/..", "/abc"},57+ {"/abc/def/../..", "/"},58+ {"/abc/def/../../..", "/"},59+ {"/abc/def/../../..", "/"},60+ {"/abc/def/../../../ghi/jkl/../../../mno", "/mno"},61+62+ // Combinations63+ {"abc/./../def", "/def"},64+ {"abc//./../def", "/def"},65+ {"abc/../../././../def", "/def"},66+}67+68+func TestPathClean(t *testing.T) {69+ for _, test := range cleanTests {70+ assert.Equal(t, CleanPath(test.path), test.result)71+ assert.Equal(t, CleanPath(test.result), test.result)72+ }73+}74+75+func TestPathCleanMallocs(t *testing.T) {76+ if testing.Short() {77+ t.Skip("skipping malloc count in short mode")78+ }79+ if runtime.GOMAXPROCS(0) > 1 {80+ t.Log("skipping AllocsPerRun checks; GOMAXPROCS>1")81+ return82+ }83+84+ for _, test := range cleanTests {85+ allocs := testing.AllocsPerRun(100, func() { CleanPath(test.result) })86+ assert.Equal(t, allocs, 0)87+ }88+}added:path.go+123 added
1+// Copyright 2013 Julien Schmidt. All rights reserved.2+// Based on the path package, Copyright 2009 The Go Authors.3+// Use of this source code is governed by a BSD-style license that can be found4+// in the LICENSE file.5+6+package gin7+8+// CleanPath is the URL version of path.Clean, it returns a canonical URL path9+// for p, eliminating . and .. elements.10+//11+// The following rules are applied iteratively until no further processing can12+// be done:13+// 1. Replace multiple slashes with a single slash.14+// 2. Eliminate each . path name element (the current directory).15+// 3. Eliminate each inner .. path name element (the parent directory)16+// along with the non-.. element that precedes it.17+// 4. Eliminate .. elements that begin a rooted path:18+// that is, replace "/.." by "/" at the beginning of a path.19+//20+// If the result of this process is an empty string, "/" is returned21+func CleanPath(p string) string {22+ // Turn empty string into "/"23+ if p == "" {24+ return "/"25+ }26+27+ n := len(p)28+ var buf []byte29+30+ // Invariants:31+ // reading from path; r is index of next byte to process.32+ // writing to buf; w is index of next byte to write.33+34+ // path must start with '/'35+ r := 136+ w := 137+38+ if p[0] != '/' {39+ r = 040+ buf = make([]byte, n+1)41+ buf[0] = '/'42+ }43+44+ trailing := n > 2 && p[n-1] == '/'45+46+ // A bit more clunky without a 'lazybuf' like the path package, but the loop47+ // gets completely inlined (bufApp). So in contrast to the path package this48+ // loop has no expensive function calls (except 1x make)49+50+ for r < n {51+ switch {52+ case p[r] == '/':53+ // empty path element, trailing slash is added after the end54+ r++55+56+ case p[r] == '.' && r+1 == n:57+ trailing = true58+ r++59+60+ case p[r] == '.' && p[r+1] == '/':61+ // . element62+ r++63+64+ case p[r] == '.' && p[r+1] == '.' && (r+2 == n || p[r+2] == '/'):65+ // .. element: remove to last /66+ r += 267+68+ if w > 1 {69+ // can backtrack70+ w--71+72+ if buf == nil {73+ for w > 1 && p[w] != '/' {74+ w--75+ }76+ } else {77+ for w > 1 && buf[w] != '/' {78+ w--79+ }80+ }81+ }82+83+ default:84+ // real path element.85+ // add slash if needed86+ if w > 1 {87+ bufApp(&buf, p, w, '/')88+ w++89+ }90+91+ // copy element92+ for r < n && p[r] != '/' {93+ bufApp(&buf, p, w, p[r])94+ w++95+ r++96+ }97+ }98+ }99+100+ // re-append trailing slash101+ if trailing && w > 1 {102+ bufApp(&buf, p, w, '/')103+ w++104+ }105+106+ if buf == nil {107+ return p[:w]108+ }109+ return string(buf[:w])110+}111+112+// internal helper to lazily create a buffer if necessary113+func bufApp(buf *[]byte, s string, w int, c byte) {114+ if *buf == nil {115+ if s[w] == c {116+ return117+ }118+119+ *buf = make([]byte, len(s))120+ copy(*buf, s[:w])121+ }122+ (*buf)[w] = c123+}modified:README.md+3 added-15 removed
1-#Gin Web Framework [](https://godoc.org/github.com/gin-gonic/gin) [](https://travis-ci.org/gin-gonic/gin)1+#Gin Web Framework [](https://travis-ci.org/gin-gonic/gin) [](https://coveralls.io/r/gin-gonic/gin?branch=develop)2 3-[](https://gitter.im/gin-gonic/gin?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)3+ [](https://godoc.org/github.com/gin-gonic/gin) [](https://gitter.im/gin-gonic/gin?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)4 5 Gin is a web framework written in Golang. It features a martini-like API with much better performance, up to 40 times faster thanks to [httprouter](https://github.com/julienschmidt/httprouter). If you need performance and good productivity, you will love Gin. 6 7 20 unmodified lines28 router.POST("/submit", func(c *gin.Context) {29 c.String(http.StatusUnauthorized, "not authorized")30 })31 router.PUT("/error", func(c *gin.Context) {32- c.String(http.StatusInternalServerError, "and error happened :(")32+ c.String(http.StatusInternalServerError, "an error happened :(")33 })34 router.Run(":8080")35 }36 ```34 unmodified lines71 ```72 import "github.com/gin-gonic/gin"73 ```74 75-76-##Community77-If you'd like to help out with the project, there's a mailing list and IRC channel where Gin discussions normally happen.78-79-* IRC80- * [irc.freenode.net #getgin](irc://irc.freenode.net:6667/getgin)81- * [Webchat](http://webchat.freenode.net?randomnick=1&channels=%23getgin)82-* Mailing List83- * Subscribe: [getgin@librelist.org](mailto:getgin@librelist.org)84- * [Archives](http://librelist.com/browser/getgin/)85-86-75 ##API Examples76 77 #### Create most basic PING/PONG HTTP endpoint78 ```go 528 unmodified linesmodified:recovery_test.go+16 added-30 removed
4 unmodified lines5 package gin6 7 import (8 "bytes"9- "log"10- "os"9 "testing"10+11+ "github.com/stretchr/testify/assert"12 )13 14 // TestPanicInHandler assert that panic has been recovered.15 func TestPanicInHandler(t *testing.T) {16- // SETUP17- log.SetOutput(bytes.NewBuffer(nil)) // Disable panic logs for testing18- r := New()19- r.Use(Recovery())20- r.GET("/recovery", func(_ *Context) {16+ buffer := new(bytes.Buffer)17+ router := New()18+ router.Use(RecoveryWithWriter(buffer))19+ router.GET("/recovery", func(_ *Context) {20 panic("Oupps, Houston, we have a problem")21 })23-22 // RUN25- w := PerformRequest(r, "GET", "/recovery")26-27- // restore logging28- log.SetOutput(os.Stderr)29-30- if w.Code != 500 {31- t.Errorf("Response code should be Internal Server Error, was: %s", w.Code)32- }23+ w := performRequest(router, "GET", "/recovery")24+ // TEST25+ assert.Equal(t, w.Code, 500)26+ assert.Contains(t, buffer.String(), "Panic recovery -> Oupps, Houston, we have a problem")27+ assert.Contains(t, buffer.String(), "TestPanicInHandler")28 }29 30 // TestPanicWithAbort assert that panic has been recovered even if context.Abort was used.31 func TestPanicWithAbort(t *testing.T) {37- // SETUP38- log.SetOutput(bytes.NewBuffer(nil))39- r := New()40- r.Use(Recovery())41- r.GET("/recovery", func(c *Context) {32+ router := New()33+ router.Use(RecoveryWithWriter(nil))34+ router.GET("/recovery", func(c *Context) {35 c.AbortWithStatus(400)36 panic("Oupps, Houston, we have a problem")37 })45-38 // RUN47- w := PerformRequest(r, "GET", "/recovery")48-49- // restore logging50- log.SetOutput(os.Stderr)51-39+ w := performRequest(router, "GET", "/recovery")40 // TEST53- if w.Code != 500 {54- t.Errorf("Response code should be Bad request, was: %s", w.Code)55- }41+ assert.Equal(t, w.Code, 500) // NOT SURE42 }modified:recovery.go+25 added-17 removed
5 unmodified lines6 7 import (8 "bytes"9 "fmt"10+ "io"11 "io/ioutil"12 "log"12- "net/http"13 "runtime"14 )15 16 var (2 unmodified lines19 dot = []byte(".")20 slash = []byte("/")21 )22 23+// Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.24+func Recovery() HandlerFunc {25+ return RecoveryWithWriter(DefaultWriter)26+}27+28+func RecoveryWithWriter(out io.Writer) HandlerFunc {29+ var logger *log.Logger30+ if out != nil {31+ logger = log.New(out, "", log.LstdFlags)32+ }33+ return func(c *Context) {34+ defer func() {35+ if err := recover(); err != nil {36+ if logger != nil {37+ stack := stack(3)38+ logger.Printf("Panic recovery -> %s\n%s\n", err, stack)39+ }40+ c.AbortWithStatus(500)41+ }42+ }()43+ c.Next()44+ }45+}46+47 // stack returns a nicely formated stack frame, skipping skip frames48 func stack(skip int) []byte {49 buf := new(bytes.Buffer) // the returned data50 // As we loop, we open files and read them. These variables record the currently52 unmodified lines103 }104 name = bytes.Replace(name, centerDot, dot, -1)105 return name106 }83-84-// Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.85-// While Gin is in development mode, Recovery will also output the panic as HTML.86-func Recovery() HandlerFunc {87- return func(c *Context) {88- defer func() {89- if err := recover(); err != nil {90- stack := stack(3)91- log.Printf("PANIC: %s\n%s", err, stack)92- c.Writer.WriteHeader(http.StatusInternalServerError)93- }94- }()95-96- c.Next()97- }98-}added:response_writer_test.go+115 added
1+// Copyright 2014 Manu Martinez-Almeida. All rights reserved.2+// Use of this source code is governed by a MIT style3+// license that can be found in the LICENSE file.4+5+package gin6+7+import (8+ "net/http"9+ "net/http/httptest"10+ "testing"11+12+ "github.com/stretchr/testify/assert"13+)14+15+// TODO16+// func (w *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {17+// func (w *responseWriter) CloseNotify() <-chan bool {18+// func (w *responseWriter) Flush() {19+20+var _ ResponseWriter = &responseWriter{}21+var _ http.ResponseWriter = &responseWriter{}22+var _ http.ResponseWriter = ResponseWriter(&responseWriter{})23+var _ http.Hijacker = ResponseWriter(&responseWriter{})24+var _ http.Flusher = ResponseWriter(&responseWriter{})25+var _ http.CloseNotifier = ResponseWriter(&responseWriter{})26+27+func init() {28+ SetMode(TestMode)29+}30+31+func TestResponseWriterReset(t *testing.T) {32+ testWritter := httptest.NewRecorder()33+ writer := &responseWriter{}34+ var w ResponseWriter = writer35+36+ writer.reset(testWritter)37+ assert.Equal(t, writer.size, -1)38+ assert.Equal(t, writer.status, 200)39+ assert.Equal(t, writer.ResponseWriter, testWritter)40+ assert.Equal(t, w.Size(), -1)41+ assert.Equal(t, w.Status(), 200)42+ assert.False(t, w.Written())43+}44+45+func TestResponseWriterWriteHeader(t *testing.T) {46+ testWritter := httptest.NewRecorder()47+ writer := &responseWriter{}48+ writer.reset(testWritter)49+ w := ResponseWriter(writer)50+51+ w.WriteHeader(300)52+ assert.False(t, w.Written())53+ assert.Equal(t, w.Status(), 300)54+ assert.NotEqual(t, testWritter.Code, 300)55+56+ w.WriteHeader(-1)57+ assert.Equal(t, w.Status(), 300)58+}59+60+func TestResponseWriterWriteHeadersNow(t *testing.T) {61+ testWritter := httptest.NewRecorder()62+ writer := &responseWriter{}63+ writer.reset(testWritter)64+ w := ResponseWriter(writer)65+66+ w.WriteHeader(300)67+ w.WriteHeaderNow()68+69+ assert.True(t, w.Written())70+ assert.Equal(t, w.Size(), 0)71+ assert.Equal(t, testWritter.Code, 300)72+73+ writer.size = 1074+ w.WriteHeaderNow()75+ assert.Equal(t, w.Size(), 10)76+}77+78+func TestResponseWriterWrite(t *testing.T) {79+ testWritter := httptest.NewRecorder()80+ writer := &responseWriter{}81+ writer.reset(testWritter)82+ w := ResponseWriter(writer)83+84+ n, err := w.Write([]byte("hola"))85+ assert.Equal(t, n, 4)86+ assert.Equal(t, w.Size(), 4)87+ assert.Equal(t, w.Status(), 200)88+ assert.Equal(t, testWritter.Code, 200)89+ assert.Equal(t, testWritter.Body.String(), "hola")90+ assert.NoError(t, err)91+92+ n, err = w.Write([]byte(" adios"))93+ assert.Equal(t, n, 6)94+ assert.Equal(t, w.Size(), 10)95+ assert.Equal(t, testWritter.Body.String(), "hola adios")96+ assert.NoError(t, err)97+}98+99+func TestResponseWriterHijack(t *testing.T) {100+ testWritter := httptest.NewRecorder()101+ writer := &responseWriter{}102+ writer.reset(testWritter)103+ w := ResponseWriter(writer)104+105+ assert.Panics(t, func() {106+ w.Hijack()107+ })108+ assert.True(t, w.Written())109+110+ assert.Panics(t, func() {111+ w.CloseNotify()112+ })113+114+ w.Flush()115+}modified:response_writer.go+13 added-18 removed
4 unmodified lines5 package gin6 7 import (8 "bufio"9- "errors"10- "log"9 "net"10 "net/http"11 )12 13 const (16- NoWritten = -114+ noWritten = -115+ defaultStatus = 20016 )17 18 type (19 ResponseWriter interface {9 unmodified lines29 }30 31 responseWriter struct {32 http.ResponseWriter34- status int33 size int34+ status int35 }36 )37 38 func (w *responseWriter) reset(writer http.ResponseWriter) {39 w.ResponseWriter = writer41- w.status = 20042- w.size = NoWritten40+ w.size = noWritten41+ w.status = defaultStatus42 }43 44 func (w *responseWriter) WriteHeader(code int) {46- if code > 0 {47- w.status = code45+ if code > 0 && w.status != code {46 if w.Written() {49- log.Println("[GIN] WARNING. Headers were already written!")47+ debugPrint("[WARNING] Headers were already written. Wanted to override status code %d with %d", w.status, code)48 }49+ w.status = code50 }51 }52 53 func (w *responseWriter) WriteHeaderNow() {18 unmodified lines72 return w.size73 }74 75 func (w *responseWriter) Written() bool {77- return w.size != NoWritten76+ return w.size != noWritten77 }78 79 // Implements the http.Hijacker interface80 func (w *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {82- hijacker, ok := w.ResponseWriter.(http.Hijacker)83- if !ok {84- return nil, nil, errors.New("the ResponseWriter doesn't support the Hijacker interface")81+ if w.size < 0 {82+ w.size = 083 }86- return hijacker.Hijack()84+ return w.ResponseWriter.(http.Hijacker).Hijack()85 }86 87 // Implements the http.CloseNotify interface88 func (w *responseWriter) CloseNotify() <-chan bool {1 unmodified line90 }91 92 // Implements the http.Flush interface93 func (w *responseWriter) Flush() {96- flusher, ok := w.ResponseWriter.(http.Flusher)97- if ok {98- flusher.Flush()99- }94+ w.ResponseWriter.(http.Flusher).Flush()95 }added:routergroup_test.go+111 added
1+// Copyright 2014 Manu Martinez-Almeida. All rights reserved.2+// Use of this source code is governed by a MIT style3+// license that can be found in the LICENSE file.4+5+package gin6+7+import (8+ "testing"9+10+ "github.com/stretchr/testify/assert"11+)12+13+func init() {14+ SetMode(TestMode)15+}16+17+func TestRouterGroupBasic(t *testing.T) {18+ router := New()19+ group := router.Group("/hola", func(c *Context) {})20+ group.Use(func(c *Context) {})21+22+ assert.Len(t, group.Handlers, 2)23+ assert.Equal(t, group.BasePath, "/hola")24+ assert.Equal(t, group.engine, router)25+26+ group2 := group.Group("manu")27+ group2.Use(func(c *Context) {}, func(c *Context) {})28+29+ assert.Len(t, group2.Handlers, 4)30+ assert.Equal(t, group2.BasePath, "/hola/manu")31+ assert.Equal(t, group2.engine, router)32+}33+34+func TestRouterGroupBasicHandle(t *testing.T) {35+ performRequestInGroup(t, "GET")36+ performRequestInGroup(t, "POST")37+ performRequestInGroup(t, "PUT")38+ performRequestInGroup(t, "PATCH")39+ performRequestInGroup(t, "DELETE")40+ performRequestInGroup(t, "HEAD")41+ performRequestInGroup(t, "OPTIONS")42+}43+44+func performRequestInGroup(t *testing.T, method string) {45+ router := New()46+ v1 := router.Group("v1", func(c *Context) {})47+ assert.Equal(t, v1.BasePath, "/v1")48+49+ login := v1.Group("/login/", func(c *Context) {}, func(c *Context) {})50+ assert.Equal(t, login.BasePath, "/v1/login/")51+52+ handler := func(c *Context) {53+ c.String(400, "the method was %s and index %d", c.Request.Method, c.index)54+ }55+56+ switch method {57+ case "GET":58+ v1.GET("/test", handler)59+ login.GET("/test", handler)60+ case "POST":61+ v1.POST("/test", handler)62+ login.POST("/test", handler)63+ case "PUT":64+ v1.PUT("/test", handler)65+ login.PUT("/test", handler)66+ case "PATCH":67+ v1.PATCH("/test", handler)68+ login.PATCH("/test", handler)69+ case "DELETE":70+ v1.DELETE("/test", handler)71+ login.DELETE("/test", handler)72+ case "HEAD":73+ v1.HEAD("/test", handler)74+ login.HEAD("/test", handler)75+ case "OPTIONS":76+ v1.OPTIONS("/test", handler)77+ login.OPTIONS("/test", handler)78+ default:79+ panic("unknown method")80+ }81+82+ w := performRequest(router, method, "/v1/login/test")83+ assert.Equal(t, w.Code, 400)84+ assert.Equal(t, w.Body.String(), "the method was "+method+" and index 3")85+86+ w = performRequest(router, method, "/v1/test")87+ assert.Equal(t, w.Code, 400)88+ assert.Equal(t, w.Body.String(), "the method was "+method+" and index 1")89+}90+91+func TestRouterGroupInvalidStatic(t *testing.T) {92+ router := New()93+ assert.Panics(t, func() {94+ router.Static("/path/:param", "/")95+ })96+97+ assert.Panics(t, func() {98+ router.Static("/path/*param", "/")99+ })100+}101+102+func TestRouterGroupInvalidStaticFile(t *testing.T) {103+ router := New()104+ assert.Panics(t, func() {105+ router.StaticFile("/path/:param", "favicon.ico")106+ })107+108+ assert.Panics(t, func() {109+ router.StaticFile("/path/*param", "favicon.ico")110+ })111+}modified:routergroup.go+63 added-52 removed
3 unmodified lines4 5 package gin6 7 import (8- "github.com/julienschmidt/httprouter"8 "net/http"9 "path"10+ "strings"11 )12 13 // Used internally to configure router, a RouterGroup is associated with a prefix14 // and an array of handlers (middlewares)15 type RouterGroup struct {16- Handlers []HandlerFunc17- absolutePath string18- engine *Engine16+ Handlers HandlersChain17+ BasePath string18+ engine *Engine19 }20 21 // Adds middlewares to the group, see example code in github.22 func (group *RouterGroup) Use(middlewares ...HandlerFunc) {3 unmodified lines26 // Creates a new router group. You should add all the routes that have common middlwares or the same path prefix.27 // For example, all the routes that use a common middlware for authorization could be grouped.28 func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup {29 return &RouterGroup{30- Handlers: group.combineHandlers(handlers),31- absolutePath: group.calculateAbsolutePath(relativePath),32- engine: group.engine,30+ Handlers: group.combineHandlers(handlers),31+ BasePath: group.calculateAbsolutePath(relativePath),32+ engine: group.engine,33 }34 }35 36 // Handle registers a new request handle and middlewares with the given path and method.5 unmodified lines42 //43 // This function is intended for bulk loading and to allow the usage of less44 // frequently used, non-standardized or custom methods (e.g. for internal45 // communication with a proxy).46-func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers []HandlerFunc) {46+func (group *RouterGroup) handle(httpMethod, relativePath string, handlers HandlersChain) {47 absolutePath := group.calculateAbsolutePath(relativePath)48 handlers = group.combineHandlers(handlers)49- if IsDebugging() {50- nuHandlers := len(handlers)51- handlerName := nameOfFunction(handlers[nuHandlers-1])52- debugPrint("%-5s %-25s --> %s (%d handlers)\n", httpMethod, absolutePath, handlerName, nuHandlers)53- }49+ group.engine.addRoute(httpMethod, absolutePath, handlers)50+}51 55- group.engine.router.Handle(httpMethod, absolutePath, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {56- context := group.engine.createContext(w, req, params, handlers)57- context.Next()58- context.Writer.WriteHeaderNow()59- group.engine.reuseContext(context)60- })52+func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) {53+ group.handle(httpMethod, relativePath, handlers)54 }55 56 // POST is a shortcut for router.Handle("POST", path, handle)57 func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) {65- group.Handle("POST", relativePath, handlers)58+ group.handle("POST", relativePath, handlers)59 }60 61 // GET is a shortcut for router.Handle("GET", path, handle)62 func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) {70- group.Handle("GET", relativePath, handlers)63+ group.handle("GET", relativePath, handlers)64 }65 66 // DELETE is a shortcut for router.Handle("DELETE", path, handle)67 func (group *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) {75- group.Handle("DELETE", relativePath, handlers)68+ group.handle("DELETE", relativePath, handlers)69 }70 71 // PATCH is a shortcut for router.Handle("PATCH", path, handle)72 func (group *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc) {80- group.Handle("PATCH", relativePath, handlers)73+ group.handle("PATCH", relativePath, handlers)74 }75 76 // PUT is a shortcut for router.Handle("PUT", path, handle)77 func (group *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) {85- group.Handle("PUT", relativePath, handlers)78+ group.handle("PUT", relativePath, handlers)79 }80 81 // OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle)82 func (group *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc) {90- group.Handle("OPTIONS", relativePath, handlers)83+ group.handle("OPTIONS", relativePath, handlers)84 }85 86 // HEAD is a shortcut for router.Handle("HEAD", path, handle)87 func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) {95- group.Handle("HEAD", relativePath, handlers)88+ group.handle("HEAD", relativePath, handlers)89 }90 98-// LINK is a shortcut for router.Handle("LINK", path, handle)99-func (group *RouterGroup) LINK(relativePath string, handlers ...HandlerFunc) {100- group.Handle("LINK", relativePath, handlers)91+func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) {92+ // GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE93+ group.handle("GET", relativePath, handlers)94+ group.handle("POST", relativePath, handlers)95+ group.handle("PUT", relativePath, handlers)96+ group.handle("PATCH", relativePath, handlers)97+ group.handle("HEAD", relativePath, handlers)98+ group.handle("OPTIONS", relativePath, handlers)99+ group.handle("DELETE", relativePath, handlers)100+ group.handle("CONNECT", relativePath, handlers)101+ group.handle("TRACE", relativePath, handlers)102 }103 103-// UNLINK is a shortcut for router.Handle("UNLINK", path, handle)104-func (group *RouterGroup) UNLINK(relativePath string, handlers ...HandlerFunc) {105- group.Handle("UNLINK", relativePath, handlers)104+func (group *RouterGroup) StaticFile(relativePath, filepath string) {105+ if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") {106+ panic("URL parameters can not be used when serving a static file")107+ }108+ handler := func(c *Context) {109+ c.File(filepath)110+ }111+ group.GET(relativePath, handler)112+ group.HEAD(relativePath, handler)113 }114 115 // Static serves files from the given file system root.116 // Internally a http.FileServer is used, therefore http.NotFound is used instead1 unmodified line118 // To use the operating system's file system implementation,119 // use :120 // router.Static("/static", "/var/www")121 func (group *RouterGroup) Static(relativePath, root string) {115- absolutePath := group.calculateAbsolutePath(relativePath)116- handler := group.createStaticHandler(absolutePath, root)117- absolutePath = path.Join(absolutePath, "/*filepath")122+ group.StaticFS(relativePath, http.Dir(root), false)123+}124 125+func (group *RouterGroup) StaticFS(relativePath string, fs http.FileSystem, listDirectory bool) {126+ if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") {127+ panic("URL parameters can not be used when serving a static folder")128+ }129+ handler := group.createStaticHandler(relativePath, fs, listDirectory)130+ relativePath = path.Join(relativePath, "/*filepath")131+132 // Register GET and HEAD handlers120- group.GET(absolutePath, handler)121- group.HEAD(absolutePath, handler)133+ group.GET(relativePath, handler)134+ group.HEAD(relativePath, handler)135 }136 124-func (group *RouterGroup) createStaticHandler(absolutePath, root string) func(*Context) {125- fileServer := http.StripPrefix(absolutePath, http.FileServer(http.Dir(root)))137+func (group *RouterGroup) createStaticHandler(relativePath string, fs http.FileSystem, listDirectory bool) HandlerFunc {138+ absolutePath := group.calculateAbsolutePath(relativePath)139+ fileServer := http.StripPrefix(absolutePath, http.FileServer(fs))140 return func(c *Context) {141+ if !listDirectory && lastChar(c.Request.URL.Path) == '/' {142+ http.NotFound(c.Writer, c.Request)143+ return144+ }145 fileServer.ServeHTTP(c.Writer, c.Request)146 }147 }148 131-func (group *RouterGroup) combineHandlers(handlers []HandlerFunc) []HandlerFunc {149+func (group *RouterGroup) combineHandlers(handlers HandlersChain) HandlersChain {150 finalSize := len(group.Handlers) + len(handlers)133- mergedHandlers := make([]HandlerFunc, 0, finalSize)134- mergedHandlers = append(mergedHandlers, group.Handlers...)135- return append(mergedHandlers, handlers...)151+ mergedHandlers := make(HandlersChain, finalSize)152+ copy(mergedHandlers, group.Handlers)153+ copy(mergedHandlers[len(group.Handlers):], handlers)154+ return mergedHandlers155 }156 157 func (group *RouterGroup) calculateAbsolutePath(relativePath string) string {139- if len(relativePath) == 0 {140- return group.absolutePath141- }142- absolutePath := path.Join(group.absolutePath, relativePath)143- appendSlash := lastChar(relativePath) == '/' && lastChar(absolutePath) != '/'144- if appendSlash {145- return absolutePath + "/"146- }147- return absolutePath158+ return joinPaths(group.BasePath, relativePath)159 }added:routes_test.go+286 added
1+// Copyright 2014 Manu Martinez-Almeida. All rights reserved.2+// Use of this source code is governed by a MIT style3+// license that can be found in the LICENSE file.4+5+package gin6+7+import (8+ "fmt"9+ "io/ioutil"10+ "net/http"11+ "net/http/httptest"12+ "os"13+ "path"14+ "testing"15+16+ "github.com/stretchr/testify/assert"17+)18+19+func performRequest(r http.Handler, method, path string) *httptest.ResponseRecorder {20+ req, _ := http.NewRequest(method, path, nil)21+ w := httptest.NewRecorder()22+ r.ServeHTTP(w, req)23+ return w24+}25+26+func testRouteOK(method string, t *testing.T) {27+ passed := false28+ passedAny := false29+ r := New()30+ r.Any("/test2", func(c *Context) {31+ passedAny = true32+ })33+ r.Handle(method, "/test", func(c *Context) {34+ passed = true35+ })36+37+ w := performRequest(r, method, "/test")38+ assert.True(t, passed)39+ assert.Equal(t, w.Code, http.StatusOK)40+41+ performRequest(r, method, "/test2")42+ assert.True(t, passedAny)43+44+}45+46+// TestSingleRouteOK tests that POST route is correctly invoked.47+func testRouteNotOK(method string, t *testing.T) {48+ passed := false49+ router := New()50+ router.Handle(method, "/test_2", func(c *Context) {51+ passed = true52+ })53+54+ w := performRequest(router, method, "/test")55+56+ assert.False(t, passed)57+ assert.Equal(t, w.Code, http.StatusNotFound)58+}59+60+// TestSingleRouteOK tests that POST route is correctly invoked.61+func testRouteNotOK2(method string, t *testing.T) {62+ passed := false63+ router := New()64+ var methodRoute string65+ if method == "POST" {66+ methodRoute = "GET"67+ } else {68+ methodRoute = "POST"69+ }70+ router.Handle(methodRoute, "/test", func(c *Context) {71+ passed = true72+ })73+74+ w := performRequest(router, method, "/test")75+76+ assert.False(t, passed)77+ assert.Equal(t, w.Code, http.StatusMethodNotAllowed)78+}79+80+func TestRouterGroupRouteOK(t *testing.T) {81+ testRouteOK("GET", t)82+ testRouteOK("POST", t)83+ testRouteOK("PUT", t)84+ testRouteOK("PATCH", t)85+ testRouteOK("HEAD", t)86+ testRouteOK("OPTIONS", t)87+ testRouteOK("DELETE", t)88+ testRouteOK("CONNECT", t)89+ testRouteOK("TRACE", t)90+}91+92+// TestSingleRouteOK tests that POST route is correctly invoked.93+func TestRouteNotOK(t *testing.T) {94+ testRouteNotOK("GET", t)95+ testRouteNotOK("POST", t)96+ testRouteNotOK("PUT", t)97+ testRouteNotOK("PATCH", t)98+ testRouteNotOK("HEAD", t)99+ testRouteNotOK("OPTIONS", t)100+ testRouteNotOK("DELETE", t)101+ testRouteNotOK("CONNECT", t)102+ testRouteNotOK("TRACE", t)103+}104+105+// TestSingleRouteOK tests that POST route is correctly invoked.106+func TestRouteNotOK2(t *testing.T) {107+ testRouteNotOK2("GET", t)108+ testRouteNotOK2("POST", t)109+ testRouteNotOK2("PUT", t)110+ testRouteNotOK2("PATCH", t)111+ testRouteNotOK2("HEAD", t)112+ testRouteNotOK2("OPTIONS", t)113+ testRouteNotOK2("DELETE", t)114+ testRouteNotOK2("CONNECT", t)115+ testRouteNotOK2("TRACE", t)116+}117+118+// TestContextParamsGet tests that a parameter can be parsed from the URL.119+func TestRouteParamsByName(t *testing.T) {120+ name := ""121+ lastName := ""122+ wild := ""123+ router := New()124+ router.GET("/test/:name/:last_name/*wild", func(c *Context) {125+ name = c.Params.ByName("name")126+ lastName = c.Params.ByName("last_name")127+ wild = c.Params.ByName("wild")128+129+ assert.Equal(t, name, c.ParamValue("name"))130+ assert.Equal(t, lastName, c.ParamValue("last_name"))131+132+ assert.Equal(t, name, c.DefaultParamValue("name", "nothing"))133+ assert.Equal(t, lastName, c.DefaultParamValue("last_name", "nothing"))134+ assert.Equal(t, c.DefaultParamValue("noKey", "default"), "default")135+ })136+137+ w := performRequest(router, "GET", "/test/john/smith/is/super/great")138+139+ assert.Equal(t, w.Code, 200)140+ assert.Equal(t, name, "john")141+ assert.Equal(t, lastName, "smith")142+ assert.Equal(t, wild, "/is/super/great")143+}144+145+// TestHandleStaticFile - ensure the static file handles properly146+func TestRouteStaticFile(t *testing.T) {147+ // SETUP file148+ testRoot, _ := os.Getwd()149+ f, err := ioutil.TempFile(testRoot, "")150+ if err != nil {151+ t.Error(err)152+ }153+ defer os.Remove(f.Name())154+ f.WriteString("Gin Web Framework")155+ f.Close()156+157+ dir, filename := path.Split(f.Name())158+159+ // SETUP gin160+ router := New()161+ router.Static("/using_static", dir)162+ router.StaticFile("/result", f.Name())163+164+ w := performRequest(router, "GET", "/using_static/"+filename)165+ w2 := performRequest(router, "GET", "/result")166+167+ assert.Equal(t, w, w2)168+ assert.Equal(t, w.Code, 200)169+ assert.Equal(t, w.Body.String(), "Gin Web Framework")170+ assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8")171+172+ w3 := performRequest(router, "HEAD", "/using_static/"+filename)173+ w4 := performRequest(router, "HEAD", "/result")174+175+ assert.Equal(t, w3, w4)176+ assert.Equal(t, w3.Code, 200)177+}178+179+// TestHandleStaticDir - ensure the root/sub dir handles properly180+func TestRouteStaticListingDir(t *testing.T) {181+ router := New()182+ router.StaticFS("/", http.Dir("./"), true)183+184+ w := performRequest(router, "GET", "/")185+186+ assert.Equal(t, w.Code, 200)187+ assert.Contains(t, w.Body.String(), "gin.go")188+ assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8")189+}190+191+// TestHandleHeadToDir - ensure the root/sub dir handles properly192+func TestRouteStaticNoListing(t *testing.T) {193+ router := New()194+ router.Static("/", "./")195+196+ w := performRequest(router, "GET", "/")197+198+ assert.Equal(t, w.Code, 404)199+ assert.NotContains(t, w.Body.String(), "gin.go")200+}201+202+func TestRouterMiddlewareAndStatic(t *testing.T) {203+ router := New()204+ static := router.Group("/", func(c *Context) {205+ c.Writer.Header().Add("Last-Modified", "Mon, 02 Jan 2006 15:04:05 MST")206+ c.Writer.Header().Add("Expires", "Mon, 02 Jan 2006 15:04:05 MST")207+ c.Writer.Header().Add("X-GIN", "Gin Framework")208+ })209+ static.Static("/", "./")210+211+ w := performRequest(router, "GET", "/gin.go")212+213+ assert.Equal(t, w.Code, 200)214+ assert.Contains(t, w.Body.String(), "package gin")215+ assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8")216+ assert.NotEqual(t, w.HeaderMap.Get("Last-Modified"), "Mon, 02 Jan 2006 15:04:05 MST")217+ assert.Equal(t, w.HeaderMap.Get("Expires"), "Mon, 02 Jan 2006 15:04:05 MST")218+ assert.Equal(t, w.HeaderMap.Get("x-GIN"), "Gin Framework")219+}220+221+func TestRouteNotAllowed(t *testing.T) {222+ router := New()223+224+ router.POST("/path", func(c *Context) {})225+ w := performRequest(router, "GET", "/path")226+ assert.Equal(t, w.Code, http.StatusMethodNotAllowed)227+228+ router.NoMethod(func(c *Context) {229+ c.String(http.StatusTeapot, "responseText")230+ })231+ w = performRequest(router, "GET", "/path")232+ assert.Equal(t, w.Body.String(), "responseText")233+ assert.Equal(t, w.Code, http.StatusTeapot)234+}235+236+func TestRouterNotFound(t *testing.T) {237+ router := New()238+ router.GET("/path", func(c *Context) {})239+ router.GET("/dir/", func(c *Context) {})240+ router.GET("/", func(c *Context) {})241+242+ testRoutes := []struct {243+ route string244+ code int245+ header string246+ }{247+ {"/path/", 301, "map[Location:[/path]]"}, // TSR -/248+ {"/dir", 301, "map[Location:[/dir/]]"}, // TSR +/249+ {"", 301, "map[Location:[/]]"}, // TSR +/250+ {"/PATH", 301, "map[Location:[/path]]"}, // Fixed Case251+ {"/DIR/", 301, "map[Location:[/dir/]]"}, // Fixed Case252+ {"/PATH/", 301, "map[Location:[/path]]"}, // Fixed Case -/253+ {"/DIR", 301, "map[Location:[/dir/]]"}, // Fixed Case +/254+ {"/../path", 301, "map[Location:[/path]]"}, // CleanPath255+ {"/nope", 404, ""}, // NotFound256+ }257+ for _, tr := range testRoutes {258+ w := performRequest(router, "GET", tr.route)259+ assert.Equal(t, w.Code, tr.code)260+ if w.Code != 404 {261+ assert.Equal(t, fmt.Sprint(w.Header()), tr.header)262+ }263+ }264+265+ // Test custom not found handler266+ var notFound bool267+ router.NoRoute(func(c *Context) {268+ c.AbortWithStatus(404)269+ notFound = true270+ })271+ w := performRequest(router, "GET", "/nope")272+ assert.Equal(t, w.Code, 404)273+ assert.True(t, notFound)274+275+ // Test other method than GET (want 307 instead of 301)276+ router.PATCH("/path", func(c *Context) {})277+ w = performRequest(router, "PATCH", "/path/")278+ assert.Equal(t, w.Code, 307)279+ assert.Equal(t, fmt.Sprint(w.Header()), "map[Location:[/path]]")280+281+ // Test special case where no node for the prefix "/" exists282+ router = New()283+ router.GET("/a", func(c *Context) {})284+ w = performRequest(router, "GET", "/")285+ assert.Equal(t, w.Code, 404)286+}added:tree_test.go+608 added
1+// Copyright 2013 Julien Schmidt. All rights reserved.2+// Use of this source code is governed by a BSD-style license that can be found3+// in the LICENSE file.4+5+package gin6+7+import (8+ "fmt"9+ "reflect"10+ "strings"11+ "testing"12+)13+14+func printChildren(n *node, prefix string) {15+ fmt.Printf(" %02d:%02d %s%s[%d] %v %t %d \r\n", n.priority, n.maxParams, prefix, n.path, len(n.children), n.handlers, n.wildChild, n.nType)16+ for l := len(n.path); l > 0; l-- {17+ prefix += " "18+ }19+ for _, child := range n.children {20+ printChildren(child, prefix)21+ }22+}23+24+// Used as a workaround since we can't compare functions or their adresses25+var fakeHandlerValue string26+27+func fakeHandler(val string) HandlersChain {28+ return HandlersChain{func(c *Context) {29+ fakeHandlerValue = val30+ }}31+}32+33+type testRequests []struct {34+ path string35+ nilHandler bool36+ route string37+ ps Params38+}39+40+func checkRequests(t *testing.T, tree *node, requests testRequests) {41+ for _, request := range requests {42+ handler, ps, _ := tree.getValue(request.path, nil)43+44+ if handler == nil {45+ if !request.nilHandler {46+ t.Errorf("handle mismatch for route '%s': Expected non-nil handle", request.path)47+ }48+ } else if request.nilHandler {49+ t.Errorf("handle mismatch for route '%s': Expected nil handle", request.path)50+ } else {51+ handler[0](nil)52+ if fakeHandlerValue != request.route {53+ t.Errorf("handle mismatch for route '%s': Wrong handle (%s != %s)", request.path, fakeHandlerValue, request.route)54+ }55+ }56+57+ if !reflect.DeepEqual(ps, request.ps) {58+ t.Errorf("Params mismatch for route '%s'", request.path)59+ }60+ }61+}62+63+func checkPriorities(t *testing.T, n *node) uint32 {64+ var prio uint3265+ for i := range n.children {66+ prio += checkPriorities(t, n.children[i])67+ }68+69+ if n.handlers != nil {70+ prio++71+ }72+73+ if n.priority != prio {74+ t.Errorf(75+ "priority mismatch for node '%s': is %d, should be %d",76+ n.path, n.priority, prio,77+ )78+ }79+80+ return prio81+}82+83+func checkMaxParams(t *testing.T, n *node) uint8 {84+ var maxParams uint885+ for i := range n.children {86+ params := checkMaxParams(t, n.children[i])87+ if params > maxParams {88+ maxParams = params89+ }90+ }91+ if n.nType != static && !n.wildChild {92+ maxParams++93+ }94+95+ if n.maxParams != maxParams {96+ t.Errorf(97+ "maxParams mismatch for node '%s': is %d, should be %d",98+ n.path, n.maxParams, maxParams,99+ )100+ }101+102+ return maxParams103+}104+105+func TestCountParams(t *testing.T) {106+ if countParams("/path/:param1/static/*catch-all") != 2 {107+ t.Fail()108+ }109+ if countParams(strings.Repeat("/:param", 256)) != 255 {110+ t.Fail()111+ }112+}113+114+func TestTreeAddAndGet(t *testing.T) {115+ tree := &node{}116+117+ routes := [...]string{118+ "/hi",119+ "/contact",120+ "/co",121+ "/c",122+ "/a",123+ "/ab",124+ "/doc/",125+ "/doc/go_faq.html",126+ "/doc/go1.html",127+ "/α",128+ "/β",129+ }130+ for _, route := range routes {131+ tree.addRoute(route, fakeHandler(route))132+ }133+134+ //printChildren(tree, "")135+136+ checkRequests(t, tree, testRequests{137+ {"/a", false, "/a", nil},138+ {"/", true, "", nil},139+ {"/hi", false, "/hi", nil},140+ {"/contact", false, "/contact", nil},141+ {"/co", false, "/co", nil},142+ {"/con", true, "", nil}, // key mismatch143+ {"/cona", true, "", nil}, // key mismatch144+ {"/no", true, "", nil}, // no matching child145+ {"/ab", false, "/ab", nil},146+ {"/α", false, "/α", nil},147+ {"/β", false, "/β", nil},148+ })149+150+ checkPriorities(t, tree)151+ checkMaxParams(t, tree)152+}153+154+func TestTreeWildcard(t *testing.T) {155+ tree := &node{}156+157+ routes := [...]string{158+ "/",159+ "/cmd/:tool/:sub",160+ "/cmd/:tool/",161+ "/src/*filepath",162+ "/search/",163+ "/search/:query",164+ "/user_:name",165+ "/user_:name/about",166+ "/files/:dir/*filepath",167+ "/doc/",168+ "/doc/go_faq.html",169+ "/doc/go1.html",170+ "/info/:user/public",171+ "/info/:user/project/:project",172+ }173+ for _, route := range routes {174+ tree.addRoute(route, fakeHandler(route))175+ }176+177+ //printChildren(tree, "")178+179+ checkRequests(t, tree, testRequests{180+ {"/", false, "/", nil},181+ {"/cmd/test/", false, "/cmd/:tool/", Params{Param{"tool", "test"}}},182+ {"/cmd/test", true, "", Params{Param{"tool", "test"}}},183+ {"/cmd/test/3", false, "/cmd/:tool/:sub", Params{Param{"tool", "test"}, Param{"sub", "3"}}},184+ {"/src/", false, "/src/*filepath", Params{Param{"filepath", "/"}}},185+ {"/src/some/file.png", false, "/src/*filepath", Params{Param{"filepath", "/some/file.png"}}},186+ {"/search/", false, "/search/", nil},187+ {"/search/someth!ng+in+ünìcodé", false, "/search/:query", Params{Param{"query", "someth!ng+in+ünìcodé"}}},188+ {"/search/someth!ng+in+ünìcodé/", true, "", Params{Param{"query", "someth!ng+in+ünìcodé"}}},189+ {"/user_gopher", false, "/user_:name", Params{Param{"name", "gopher"}}},190+ {"/user_gopher/about", false, "/user_:name/about", Params{Param{"name", "gopher"}}},191+ {"/files/js/inc/framework.js", false, "/files/:dir/*filepath", Params{Param{"dir", "js"}, Param{"filepath", "/inc/framework.js"}}},192+ {"/info/gordon/public", false, "/info/:user/public", Params{Param{"user", "gordon"}}},193+ {"/info/gordon/project/go", false, "/info/:user/project/:project", Params{Param{"user", "gordon"}, Param{"project", "go"}}},194+ })195+196+ checkPriorities(t, tree)197+ checkMaxParams(t, tree)198+}199+200+func catchPanic(testFunc func()) (recv interface{}) {201+ defer func() {202+ recv = recover()203+ }()204+205+ testFunc()206+ return207+}208+209+type testRoute struct {210+ path string211+ conflict bool212+}213+214+func testRoutes(t *testing.T, routes []testRoute) {215+ tree := &node{}216+217+ for _, route := range routes {218+ recv := catchPanic(func() {219+ tree.addRoute(route.path, nil)220+ })221+222+ if route.conflict {223+ if recv == nil {224+ t.Errorf("no panic for conflicting route '%s'", route.path)225+ }226+ } else if recv != nil {227+ t.Errorf("unexpected panic for route '%s': %v", route.path, recv)228+ }229+ }230+231+ //printChildren(tree, "")232+}233+234+func TestTreeWildcardConflict(t *testing.T) {235+ routes := []testRoute{236+ {"/cmd/:tool/:sub", false},237+ {"/cmd/vet", true},238+ {"/src/*filepath", false},239+ {"/src/*filepathx", true},240+ {"/src/", true},241+ {"/src1/", false},242+ {"/src1/*filepath", true},243+ {"/src2*filepath", true},244+ {"/search/:query", false},245+ {"/search/invalid", true},246+ {"/user_:name", false},247+ {"/user_x", true},248+ {"/user_:name", false},249+ {"/id:id", false},250+ {"/id/:id", true},251+ }252+ testRoutes(t, routes)253+}254+255+func TestTreeChildConflict(t *testing.T) {256+ routes := []testRoute{257+ {"/cmd/vet", false},258+ {"/cmd/:tool/:sub", true},259+ {"/src/AUTHORS", false},260+ {"/src/*filepath", true},261+ {"/user_x", false},262+ {"/user_:name", true},263+ {"/id/:id", false},264+ {"/id:id", true},265+ {"/:id", true},266+ {"/*filepath", true},267+ }268+ testRoutes(t, routes)269+}270+271+func TestTreeDupliatePath(t *testing.T) {272+ tree := &node{}273+274+ routes := [...]string{275+ "/",276+ "/doc/",277+ "/src/*filepath",278+ "/search/:query",279+ "/user_:name",280+ }281+ for _, route := range routes {282+ recv := catchPanic(func() {283+ tree.addRoute(route, fakeHandler(route))284+ })285+ if recv != nil {286+ t.Fatalf("panic inserting route '%s': %v", route, recv)287+ }288+289+ // Add again290+ recv = catchPanic(func() {291+ tree.addRoute(route, nil)292+ })293+ if recv == nil {294+ t.Fatalf("no panic while inserting duplicate route '%s", route)295+ }296+ }297+298+ //printChildren(tree, "")299+300+ checkRequests(t, tree, testRequests{301+ {"/", false, "/", nil},302+ {"/doc/", false, "/doc/", nil},303+ {"/src/some/file.png", false, "/src/*filepath", Params{Param{"filepath", "/some/file.png"}}},304+ {"/search/someth!ng+in+ünìcodé", false, "/search/:query", Params{Param{"query", "someth!ng+in+ünìcodé"}}},305+ {"/user_gopher", false, "/user_:name", Params{Param{"name", "gopher"}}},306+ })307+}308+309+func TestEmptyWildcardName(t *testing.T) {310+ tree := &node{}311+312+ routes := [...]string{313+ "/user:",314+ "/user:/",315+ "/cmd/:/",316+ "/src/*",317+ }318+ for _, route := range routes {319+ recv := catchPanic(func() {320+ tree.addRoute(route, nil)321+ })322+ if recv == nil {323+ t.Fatalf("no panic while inserting route with empty wildcard name '%s", route)324+ }325+ }326+}327+328+func TestTreeCatchAllConflict(t *testing.T) {329+ routes := []testRoute{330+ {"/src/*filepath/x", true},331+ {"/src2/", false},332+ {"/src2/*filepath/x", true},333+ }334+ testRoutes(t, routes)335+}336+337+func TestTreeCatchAllConflictRoot(t *testing.T) {338+ routes := []testRoute{339+ {"/", false},340+ {"/*filepath", true},341+ }342+ testRoutes(t, routes)343+}344+345+func TestTreeDoubleWildcard(t *testing.T) {346+ const panicMsg = "only one wildcard per path segment is allowed"347+348+ routes := [...]string{349+ "/:foo:bar",350+ "/:foo:bar/",351+ "/:foo*bar",352+ }353+354+ for _, route := range routes {355+ tree := &node{}356+ recv := catchPanic(func() {357+ tree.addRoute(route, nil)358+ })359+360+ if rs, ok := recv.(string); !ok || !strings.HasPrefix(rs, panicMsg) {361+ t.Fatalf(`"Expected panic "%s" for route '%s', got "%v"`, panicMsg, route, recv)362+ }363+ }364+}365+366+/*func TestTreeDuplicateWildcard(t *testing.T) {367+ tree := &node{}368+369+ routes := [...]string{370+ "/:id/:name/:id",371+ }372+ for _, route := range routes {373+ ...374+ }375+}*/376+377+func TestTreeTrailingSlashRedirect(t *testing.T) {378+ tree := &node{}379+380+ routes := [...]string{381+ "/hi",382+ "/b/",383+ "/search/:query",384+ "/cmd/:tool/",385+ "/src/*filepath",386+ "/x",387+ "/x/y",388+ "/y/",389+ "/y/z",390+ "/0/:id",391+ "/0/:id/1",392+ "/1/:id/",393+ "/1/:id/2",394+ "/aa",395+ "/a/",396+ "/doc",397+ "/doc/go_faq.html",398+ "/doc/go1.html",399+ "/no/a",400+ "/no/b",401+ "/api/hello/:name",402+ }403+ for _, route := range routes {404+ recv := catchPanic(func() {405+ tree.addRoute(route, fakeHandler(route))406+ })407+ if recv != nil {408+ t.Fatalf("panic inserting route '%s': %v", route, recv)409+ }410+ }411+412+ //printChildren(tree, "")413+414+ tsrRoutes := [...]string{415+ "/hi/",416+ "/b",417+ "/search/gopher/",418+ "/cmd/vet",419+ "/src",420+ "/x/",421+ "/y",422+ "/0/go/",423+ "/1/go",424+ "/a",425+ "/doc/",426+ }427+ for _, route := range tsrRoutes {428+ handler, _, tsr := tree.getValue(route, nil)429+ if handler != nil {430+ t.Fatalf("non-nil handler for TSR route '%s", route)431+ } else if !tsr {432+ t.Errorf("expected TSR recommendation for route '%s'", route)433+ }434+ }435+436+ noTsrRoutes := [...]string{437+ "/",438+ "/no",439+ "/no/",440+ "/_",441+ "/_/",442+ "/api/world/abc",443+ }444+ for _, route := range noTsrRoutes {445+ handler, _, tsr := tree.getValue(route, nil)446+ if handler != nil {447+ t.Fatalf("non-nil handler for No-TSR route '%s", route)448+ } else if tsr {449+ t.Errorf("expected no TSR recommendation for route '%s'", route)450+ }451+ }452+}453+454+func TestTreeFindCaseInsensitivePath(t *testing.T) {455+ tree := &node{}456+457+ routes := [...]string{458+ "/hi",459+ "/b/",460+ "/ABC/",461+ "/search/:query",462+ "/cmd/:tool/",463+ "/src/*filepath",464+ "/x",465+ "/x/y",466+ "/y/",467+ "/y/z",468+ "/0/:id",469+ "/0/:id/1",470+ "/1/:id/",471+ "/1/:id/2",472+ "/aa",473+ "/a/",474+ "/doc",475+ "/doc/go_faq.html",476+ "/doc/go1.html",477+ "/doc/go/away",478+ "/no/a",479+ "/no/b",480+ }481+482+ for _, route := range routes {483+ recv := catchPanic(func() {484+ tree.addRoute(route, fakeHandler(route))485+ })486+ if recv != nil {487+ t.Fatalf("panic inserting route '%s': %v", route, recv)488+ }489+ }490+491+ // Check out == in for all registered routes492+ // With fixTrailingSlash = true493+ for _, route := range routes {494+ out, found := tree.findCaseInsensitivePath(route, true)495+ if !found {496+ t.Errorf("Route '%s' not found!", route)497+ } else if string(out) != route {498+ t.Errorf("Wrong result for route '%s': %s", route, string(out))499+ }500+ }501+ // With fixTrailingSlash = false502+ for _, route := range routes {503+ out, found := tree.findCaseInsensitivePath(route, false)504+ if !found {505+ t.Errorf("Route '%s' not found!", route)506+ } else if string(out) != route {507+ t.Errorf("Wrong result for route '%s': %s", route, string(out))508+ }509+ }510+511+ tests := []struct {512+ in string513+ out string514+ found bool515+ slash bool516+ }{517+ {"/HI", "/hi", true, false},518+ {"/HI/", "/hi", true, true},519+ {"/B", "/b/", true, true},520+ {"/B/", "/b/", true, false},521+ {"/abc", "/ABC/", true, true},522+ {"/abc/", "/ABC/", true, false},523+ {"/aBc", "/ABC/", true, true},524+ {"/aBc/", "/ABC/", true, false},525+ {"/abC", "/ABC/", true, true},526+ {"/abC/", "/ABC/", true, false},527+ {"/SEARCH/QUERY", "/search/QUERY", true, false},528+ {"/SEARCH/QUERY/", "/search/QUERY", true, true},529+ {"/CMD/TOOL/", "/cmd/TOOL/", true, false},530+ {"/CMD/TOOL", "/cmd/TOOL/", true, true},531+ {"/SRC/FILE/PATH", "/src/FILE/PATH", true, false},532+ {"/x/Y", "/x/y", true, false},533+ {"/x/Y/", "/x/y", true, true},534+ {"/X/y", "/x/y", true, false},535+ {"/X/y/", "/x/y", true, true},536+ {"/X/Y", "/x/y", true, false},537+ {"/X/Y/", "/x/y", true, true},538+ {"/Y/", "/y/", true, false},539+ {"/Y", "/y/", true, true},540+ {"/Y/z", "/y/z", true, false},541+ {"/Y/z/", "/y/z", true, true},542+ {"/Y/Z", "/y/z", true, false},543+ {"/Y/Z/", "/y/z", true, true},544+ {"/y/Z", "/y/z", true, false},545+ {"/y/Z/", "/y/z", true, true},546+ {"/Aa", "/aa", true, false},547+ {"/Aa/", "/aa", true, true},548+ {"/AA", "/aa", true, false},549+ {"/AA/", "/aa", true, true},550+ {"/aA", "/aa", true, false},551+ {"/aA/", "/aa", true, true},552+ {"/A/", "/a/", true, false},553+ {"/A", "/a/", true, true},554+ {"/DOC", "/doc", true, false},555+ {"/DOC/", "/doc", true, true},556+ {"/NO", "", false, true},557+ {"/DOC/GO", "", false, true},558+ }559+ // With fixTrailingSlash = true560+ for _, test := range tests {561+ out, found := tree.findCaseInsensitivePath(test.in, true)562+ if found != test.found || (found && (string(out) != test.out)) {563+ t.Errorf("Wrong result for '%s': got %s, %t; want %s, %t",564+ test.in, string(out), found, test.out, test.found)565+ return566+ }567+ }568+ // With fixTrailingSlash = false569+ for _, test := range tests {570+ out, found := tree.findCaseInsensitivePath(test.in, false)571+ if test.slash {572+ if found { // test needs a trailingSlash fix. It must not be found!573+ t.Errorf("Found without fixTrailingSlash: %s; got %s", test.in, string(out))574+ }575+ } else {576+ if found != test.found || (found && (string(out) != test.out)) {577+ t.Errorf("Wrong result for '%s': got %s, %t; want %s, %t",578+ test.in, string(out), found, test.out, test.found)579+ return580+ }581+ }582+ }583+}584+585+func TestTreeInvalidNodeType(t *testing.T) {586+ tree := &node{}587+ tree.addRoute("/", fakeHandler("/"))588+ tree.addRoute("/:page", fakeHandler("/:page"))589+590+ // set invalid node type591+ tree.children[0].nType = 42592+593+ // normal lookup594+ recv := catchPanic(func() {595+ tree.getValue("/test", nil)596+ })597+ if rs, ok := recv.(string); !ok || rs != "invalid node type" {598+ t.Fatalf(`Expected panic "invalid node type", got "%v"`, recv)599+ }600+601+ // case-insensitive lookup602+ recv = catchPanic(func() {603+ tree.findCaseInsensitivePath("/test", true)604+ })605+ if rs, ok := recv.(string); !ok || rs != "invalid node type" {606+ t.Fatalf(`Expected panic "invalid node type", got "%v"`, recv)607+ }608+}added:tree.go+553 added
1+// Copyright 2013 Julien Schmidt. All rights reserved.2+// Use of this source code is governed by a BSD-style license that can be found3+// in the LICENSE file.4+5+package gin6+7+import (8+ "strings"9+ "unicode"10+)11+12+func min(a, b int) int {13+ if a <= b {14+ return a15+ }16+ return b17+}18+19+func countParams(path string) uint8 {20+ var n uint21+ for i := 0; i < len(path); i++ {22+ if path[i] != ':' && path[i] != '*' {23+ continue24+ }25+ n++26+ }27+ if n >= 255 {28+ return 25529+ }30+ return uint8(n)31+}32+33+type nodeType uint834+35+const (36+ static nodeType = 037+ param nodeType = 138+ catchAll nodeType = 239+)40+41+type node struct {42+ path string43+ wildChild bool44+ nType nodeType45+ maxParams uint846+ indices string47+ children []*node48+ handlers HandlersChain49+ priority uint3250+}51+52+// increments priority of the given child and reorders if necessary53+func (n *node) incrementChildPrio(pos int) int {54+ n.children[pos].priority++55+ prio := n.children[pos].priority56+57+ // adjust position (move to front)58+ newPos := pos59+ for newPos > 0 && n.children[newPos-1].priority < prio {60+ // swap node positions61+ tmpN := n.children[newPos-1]62+ n.children[newPos-1] = n.children[newPos]63+ n.children[newPos] = tmpN64+65+ newPos--66+ }67+68+ // build new index char string69+ if newPos != pos {70+ n.indices = n.indices[:newPos] + // unchanged prefix, might be empty71+ n.indices[pos:pos+1] + // the index char we move72+ n.indices[newPos:pos] + n.indices[pos+1:] // rest without char at 'pos'73+ }74+75+ return newPos76+}77+78+// addRoute adds a node with the given handle to the path.79+// Not concurrency-safe!80+func (n *node) addRoute(path string, handlers HandlersChain) {81+ fullPath := path82+ n.priority++83+ numParams := countParams(path)84+85+ // non-empty tree86+ if len(n.path) > 0 || len(n.children) > 0 {87+ walk:88+ for {89+ // Update maxParams of the current node90+ if numParams > n.maxParams {91+ n.maxParams = numParams92+ }93+94+ // Find the longest common prefix.95+ // This also implies that the common prefix contains no ':' or '*'96+ // since the existing key can't contain those chars.97+ i := 098+ max := min(len(path), len(n.path))99+ for i < max && path[i] == n.path[i] {100+ i++101+ }102+103+ // Split edge104+ if i < len(n.path) {105+ child := node{106+ path: n.path[i:],107+ wildChild: n.wildChild,108+ indices: n.indices,109+ children: n.children,110+ handlers: n.handlers,111+ priority: n.priority - 1,112+ }113+114+ // Update maxParams (max of all children)115+ for i := range child.children {116+ if child.children[i].maxParams > child.maxParams {117+ child.maxParams = child.children[i].maxParams118+ }119+ }120+121+ n.children = []*node{&child}122+ // []byte for proper unicode char conversion, see #65123+ n.indices = string([]byte{n.path[i]})124+ n.path = path[:i]125+ n.handlers = nil126+ n.wildChild = false127+ }128+129+ // Make new node a child of this node130+ if i < len(path) {131+ path = path[i:]132+133+ if n.wildChild {134+ n = n.children[0]135+ n.priority++136+137+ // Update maxParams of the child node138+ if numParams > n.maxParams {139+ n.maxParams = numParams140+ }141+ numParams--142+143+ // Check if the wildcard matches144+ if len(path) >= len(n.path) && n.path == path[:len(n.path)] {145+ // check for longer wildcard, e.g. :name and :names146+ if len(n.path) >= len(path) || path[len(n.path)] == '/' {147+ continue walk148+ }149+ }150+151+ panic("path segment '" + path +152+ "' conflicts with existing wildcard '" + n.path +153+ "' in path '" + fullPath + "'")154+ }155+156+ c := path[0]157+158+ // slash after param159+ if n.nType == param && c == '/' && len(n.children) == 1 {160+ n = n.children[0]161+ n.priority++162+ continue walk163+ }164+165+ // Check if a child with the next path byte exists166+ for i := 0; i < len(n.indices); i++ {167+ if c == n.indices[i] {168+ i = n.incrementChildPrio(i)169+ n = n.children[i]170+ continue walk171+ }172+ }173+174+ // Otherwise insert it175+ if c != ':' && c != '*' {176+ // []byte for proper unicode char conversion, see #65177+ n.indices += string([]byte{c})178+ child := &node{179+ maxParams: numParams,180+ }181+ n.children = append(n.children, child)182+ n.incrementChildPrio(len(n.indices) - 1)183+ n = child184+ }185+ n.insertChild(numParams, path, fullPath, handlers)186+ return187+188+ } else if i == len(path) { // Make node a (in-path) leaf189+ if n.handlers != nil {190+ panic("handlers are already registered for path ''" + fullPath + "'")191+ }192+ n.handlers = handlers193+ }194+ return195+ }196+ } else { // Empty tree197+ n.insertChild(numParams, path, fullPath, handlers)198+ }199+}200+201+func (n *node) insertChild(numParams uint8, path string, fullPath string, handlers HandlersChain) {202+ var offset int // already handled bytes of the path203+204+ // find prefix until first wildcard (beginning with ':'' or '*'')205+ for i, max := 0, len(path); numParams > 0; i++ {206+ c := path[i]207+ if c != ':' && c != '*' {208+ continue209+ }210+211+ // find wildcard end (either '/' or path end)212+ end := i + 1213+ for end < max && path[end] != '/' {214+ switch path[end] {215+ // the wildcard name must not contain ':' and '*'216+ case ':', '*':217+ panic("only one wildcard per path segment is allowed, has: '" +218+ path[i:] + "' in path '" + fullPath + "'")219+ default:220+ end++221+ }222+ }223+224+ // check if this Node existing children which would be225+ // unreachable if we insert the wildcard here226+ if len(n.children) > 0 {227+ panic("wildcard route '" + path[i:end] +228+ "' conflicts with existing children in path '" + fullPath + "'")229+ }230+231+ // check if the wildcard has a name232+ if end-i < 2 {233+ panic("wildcards must be named with a non-empty name in path '" + fullPath + "'")234+ }235+236+ if c == ':' { // param237+ // split path at the beginning of the wildcard238+ if i > 0 {239+ n.path = path[offset:i]240+ offset = i241+ }242+243+ child := &node{244+ nType: param,245+ maxParams: numParams,246+ }247+ n.children = []*node{child}248+ n.wildChild = true249+ n = child250+ n.priority++251+ numParams--252+253+ // if the path doesn't end with the wildcard, then there254+ // will be another non-wildcard subpath starting with '/'255+ if end < max {256+ n.path = path[offset:end]257+ offset = end258+259+ child := &node{260+ maxParams: numParams,261+ priority: 1,262+ }263+ n.children = []*node{child}264+ n = child265+ }266+267+ } else { // catchAll268+ if end != max || numParams > 1 {269+ panic("catch-all routes are only allowed at the end of the path in path '" + fullPath + "'")270+ }271+272+ if len(n.path) > 0 && n.path[len(n.path)-1] == '/' {273+ panic("catch-all conflicts with existing handle for the path segment root in path '" + fullPath + "'")274+ }275+276+ // currently fixed width 1 for '/'277+ i--278+ if path[i] != '/' {279+ panic("no / before catch-all in path '" + fullPath + "'")280+ }281+282+ n.path = path[offset:i]283+284+ // first node: catchAll node with empty path285+ child := &node{286+ wildChild: true,287+ nType: catchAll,288+ maxParams: 1,289+ }290+ n.children = []*node{child}291+ n.indices = string(path[i])292+ n = child293+ n.priority++294+295+ // second node: node holding the variable296+ child = &node{297+ path: path[i:],298+ nType: catchAll,299+ maxParams: 1,300+ handlers: handlers,301+ priority: 1,302+ }303+ n.children = []*node{child}304+305+ return306+ }307+ }308+309+ // insert remaining path part and handle to the leaf310+ n.path = path[offset:]311+ n.handlers = handlers312+}313+314+// Returns the handle registered with the given path (key). The values of315+// wildcards are saved to a map.316+// If no handle can be found, a TSR (trailing slash redirect) recommendation is317+// made if a handle exists with an extra (without the) trailing slash for the318+// given path.319+func (n *node) getValue(path string, po Params) (handlers HandlersChain, p Params, tsr bool) {320+ p = po321+walk: // Outer loop for walking the tree322+ for {323+ if len(path) > len(n.path) {324+ if path[:len(n.path)] == n.path {325+ path = path[len(n.path):]326+ // If this node does not have a wildcard (param or catchAll)327+ // child, we can just look up the next child node and continue328+ // to walk down the tree329+ if !n.wildChild {330+ c := path[0]331+ for i := 0; i < len(n.indices); i++ {332+ if c == n.indices[i] {333+ n = n.children[i]334+ continue walk335+ }336+ }337+338+ // Nothing found.339+ // We can recommend to redirect to the same URL without a340+ // trailing slash if a leaf exists for that path.341+ tsr = (path == "/" && n.handlers != nil)342+ return343+ }344+345+ // handle wildcard child346+ n = n.children[0]347+ switch n.nType {348+ case param:349+ // find param end (either '/' or path end)350+ end := 0351+ for end < len(path) && path[end] != '/' {352+ end++353+ }354+355+ // save param value356+ if cap(p) < int(n.maxParams) {357+ p = make(Params, 0, n.maxParams)358+ }359+ i := len(p)360+ p = p[:i+1] // expand slice within preallocated capacity361+ p[i].Key = n.path[1:]362+ p[i].Value = path[:end]363+364+ // we need to go deeper!365+ if end < len(path) {366+ if len(n.children) > 0 {367+ path = path[end:]368+ n = n.children[0]369+ continue walk370+ }371+372+ // ... but we can't373+ tsr = (len(path) == end+1)374+ return375+ }376+377+ if handlers = n.handlers; handlers != nil {378+ return379+ } else if len(n.children) == 1 {380+ // No handle found. Check if a handle for this path + a381+ // trailing slash exists for TSR recommendation382+ n = n.children[0]383+ tsr = (n.path == "/" && n.handlers != nil)384+ }385+386+ return387+388+ case catchAll:389+ // save param value390+ if cap(p) < int(n.maxParams) {391+ p = make(Params, 0, n.maxParams)392+ }393+ i := len(p)394+ p = p[:i+1] // expand slice within preallocated capacity395+ p[i].Key = n.path[2:]396+ p[i].Value = path397+398+ handlers = n.handlers399+ return400+401+ default:402+ panic("invalid node type")403+ }404+ }405+ } else if path == n.path {406+ // We should have reached the node containing the handle.407+ // Check if this node has a handle registered.408+ if handlers = n.handlers; handlers != nil {409+ return410+ }411+412+ // No handle found. Check if a handle for this path + a413+ // trailing slash exists for trailing slash recommendation414+ for i := 0; i < len(n.indices); i++ {415+ if n.indices[i] == '/' {416+ n = n.children[i]417+ tsr = (len(n.path) == 1 && n.handlers != nil) ||418+ (n.nType == catchAll && n.children[0].handlers != nil)419+ return420+ }421+ }422+423+ return424+ }425+426+ // Nothing found. We can recommend to redirect to the same URL with an427+ // extra trailing slash if a leaf exists for that path428+ tsr = (path == "/") ||429+ (len(n.path) == len(path)+1 && n.path[len(path)] == '/' &&430+ path == n.path[:len(n.path)-1] && n.handlers != nil)431+ return432+ }433+}434+435+// Makes a case-insensitive lookup of the given path and tries to find a handler.436+// It can optionally also fix trailing slashes.437+// It returns the case-corrected path and a bool indicating whether the lookup438+// was successful.439+func (n *node) findCaseInsensitivePath(path string, fixTrailingSlash bool) (ciPath []byte, found bool) {440+ ciPath = make([]byte, 0, len(path)+1) // preallocate enough memory441+442+ // Outer loop for walking the tree443+ for len(path) >= len(n.path) && strings.ToLower(path[:len(n.path)]) == strings.ToLower(n.path) {444+ path = path[len(n.path):]445+ ciPath = append(ciPath, n.path...)446+447+ if len(path) > 0 {448+ // If this node does not have a wildcard (param or catchAll) child,449+ // we can just look up the next child node and continue to walk down450+ // the tree451+ if !n.wildChild {452+ r := unicode.ToLower(rune(path[0]))453+ for i, index := range n.indices {454+ // must use recursive approach since both index and455+ // ToLower(index) could exist. We must check both.456+ if r == unicode.ToLower(index) {457+ out, found := n.children[i].findCaseInsensitivePath(path, fixTrailingSlash)458+ if found {459+ return append(ciPath, out...), true460+ }461+ }462+ }463+464+ // Nothing found. We can recommend to redirect to the same URL465+ // without a trailing slash if a leaf exists for that path466+ found = (fixTrailingSlash && path == "/" && n.handlers != nil)467+ return468+ }469+470+ n = n.children[0]471+ switch n.nType {472+ case param:473+ // find param end (either '/' or path end)474+ k := 0475+ for k < len(path) && path[k] != '/' {476+ k++477+ }478+479+ // add param value to case insensitive path480+ ciPath = append(ciPath, path[:k]...)481+482+ // we need to go deeper!483+ if k < len(path) {484+ if len(n.children) > 0 {485+ path = path[k:]486+ n = n.children[0]487+ continue488+ }489+490+ // ... but we can't491+ if fixTrailingSlash && len(path) == k+1 {492+ return ciPath, true493+ }494+ return495+ }496+497+ if n.handlers != nil {498+ return ciPath, true499+ } else if fixTrailingSlash && len(n.children) == 1 {500+ // No handle found. Check if a handle for this path + a501+ // trailing slash exists502+ n = n.children[0]503+ if n.path == "/" && n.handlers != nil {504+ return append(ciPath, '/'), true505+ }506+ }507+ return508+509+ case catchAll:510+ return append(ciPath, path...), true511+512+ default:513+ panic("invalid node type")514+ }515+ } else {516+ // We should have reached the node containing the handle.517+ // Check if this node has a handle registered.518+ if n.handlers != nil {519+ return ciPath, true520+ }521+522+ // No handle found.523+ // Try to fix the path by adding a trailing slash524+ if fixTrailingSlash {525+ for i := 0; i < len(n.indices); i++ {526+ if n.indices[i] == '/' {527+ n = n.children[i]528+ if (len(n.path) == 1 && n.handlers != nil) ||529+ (n.nType == catchAll && n.children[0].handlers != nil) {530+ return append(ciPath, '/'), true531+ }532+ return533+ }534+ }535+ }536+ return537+ }538+ }539+540+ // Nothing found.541+ // Try to fix the path by adding / removing a trailing slash542+ if fixTrailingSlash {543+ if path == "/" {544+ return ciPath, true545+ }546+ if len(path)+1 == len(n.path) && n.path[len(path)] == '/' &&547+ strings.ToLower(path) == strings.ToLower(n.path[:len(path)]) &&548+ n.handlers != nil {549+ return append(ciPath, n.path...), true550+ }551+ }552+ return553+}added:utils_test.go+99 added
1+// Copyright 2014 Manu Martinez-Almeida. All rights reserved.2+// Use of this source code is governed by a MIT style3+// license that can be found in the LICENSE file.4+5+package gin6+7+import (8+ "fmt"9+ "net/http"10+ "testing"11+12+ "github.com/stretchr/testify/assert"13+)14+15+func init() {16+ SetMode(TestMode)17+}18+19+type testStruct struct {20+ T *testing.T21+}22+23+func (t *testStruct) ServeHTTP(w http.ResponseWriter, req *http.Request) {24+ assert.Equal(t.T, req.Method, "POST")25+ assert.Equal(t.T, req.URL.Path, "/path")26+ w.WriteHeader(500)27+ fmt.Fprint(w, "hello")28+}29+30+func TestWrap(t *testing.T) {31+ router := New()32+ router.POST("/path", WrapH(&testStruct{t}))33+ router.GET("/path2", WrapF(func(w http.ResponseWriter, req *http.Request) {34+ assert.Equal(t, req.Method, "GET")35+ assert.Equal(t, req.URL.Path, "/path2")36+ w.WriteHeader(400)37+ fmt.Fprint(w, "hola!")38+ }))39+40+ w := performRequest(router, "POST", "/path")41+ assert.Equal(t, w.Code, 500)42+ assert.Equal(t, w.Body.String(), "hello")43+44+ w = performRequest(router, "GET", "/path2")45+ assert.Equal(t, w.Code, 400)46+ assert.Equal(t, w.Body.String(), "hola!")47+}48+49+func TestLastChar(t *testing.T) {50+ assert.Equal(t, lastChar("hola"), uint8('a'))51+ assert.Equal(t, lastChar("adios"), uint8('s'))52+ assert.Panics(t, func() { lastChar("") })53+}54+55+func TestParseAccept(t *testing.T) {56+ parts := parseAccept("text/html , application/xhtml+xml,application/xml;q=0.9, */* ;q=0.8")57+ assert.Len(t, parts, 4)58+ assert.Equal(t, parts[0], "text/html")59+ assert.Equal(t, parts[1], "application/xhtml+xml")60+ assert.Equal(t, parts[2], "application/xml")61+ assert.Equal(t, parts[3], "*/*")62+}63+64+func TestChooseData(t *testing.T) {65+ A := "a"66+ B := "b"67+ assert.Equal(t, chooseData(A, B), A)68+ assert.Equal(t, chooseData(nil, B), B)69+ assert.Panics(t, func() { chooseData(nil, nil) })70+}71+72+func TestFilterFlags(t *testing.T) {73+ result := filterFlags("text/html ")74+ assert.Equal(t, result, "text/html")75+76+ result = filterFlags("text/html;")77+ assert.Equal(t, result, "text/html")78+}79+80+func TestFunctionName(t *testing.T) {81+ assert.Equal(t, nameOfFunction(somefunction), "github.com/gin-gonic/gin.somefunction")82+}83+84+func somefunction() {85+ // this empty function is used by TestFunctionName()86+}87+88+func TestJoinPaths(t *testing.T) {89+ assert.Equal(t, joinPaths("", ""), "")90+ assert.Equal(t, joinPaths("", "/"), "/")91+ assert.Equal(t, joinPaths("/a", ""), "/a")92+ assert.Equal(t, joinPaths("/a/", ""), "/a/")93+ assert.Equal(t, joinPaths("/a/", "/"), "/a/")94+ assert.Equal(t, joinPaths("/a", "/"), "/a/")95+ assert.Equal(t, joinPaths("/a", "/hola"), "/a/hola")96+ assert.Equal(t, joinPaths("/a/", "/hola"), "/a/hola")97+ assert.Equal(t, joinPaths("/a/", "/hola/"), "/a/hola/")98+ assert.Equal(t, joinPaths("/a/", "/hola//"), "/a/hola/")99+}modified:utils.go+35 added-5 removed
4 unmodified lines5 package gin6 7 import (8 "encoding/xml"9+ "net/http"10+ "path"11 "reflect"12 "runtime"13 "strings"14 )15 16+func WrapF(f http.HandlerFunc) HandlerFunc {17+ return func(c *Context) {18+ f(c.Writer, c.Request)19+ }20+}21+22+func WrapH(h http.Handler) HandlerFunc {23+ return func(c *Context) {24+ h.ServeHTTP(c.Writer, c.Request)25+ }26+}27+28 type H map[string]interface{}29 30 // Allows type H to be used with xml.Marshal31 func (h H) MarshalXML(e *xml.Encoder, start xml.StartElement) error {37 unmodified lines69 }70 return custom71 }72 59-func parseAccept(accept string) []string {60- parts := strings.Split(accept, ",")61- for i, part := range parts {73+func parseAccept(acceptHeader string) []string {74+ parts := strings.Split(acceptHeader, ",")75+ out := make([]string, 0, len(parts))76+ for _, part := range parts {77 index := strings.IndexByte(part, ';')78 if index >= 0 {79 part = part[0:index]80 }81 part = strings.TrimSpace(part)67- parts[i] = part82+ if len(part) > 0 {83+ out = append(out, part)84+ }85 }69- return parts86+ return out87 }88 89 func lastChar(str string) uint8 {90 size := len(str)5 unmodified lines96 97 func nameOfFunction(f interface{}) string {98 return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()99 }100+101+func joinPaths(absolutePath, relativePath string) string {102+ if len(relativePath) == 0 {103+ return absolutePath104+ }105+106+ finalPath := path.Join(absolutePath, relativePath)107+ appendSlash := lastChar(relativePath) == '/' && lastChar(finalPath) != '/'108+ if appendSlash {109+ return finalPath + "/"110+ }111+ return finalPath112+}added:wercker.yml+1 added
1+box: wercker/default