Merge branch 'develop' | Update AUTHORS and CHANGELOG
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Javier Provecho Fernandez · committed by Javier Provecho Fernandez · parents 28b9ff9, d936320 · Browse files · 21 files·+839 added−331 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
21 files+839 added−331 removed
- other:+839 added−331 removed
Provenance
- Commit
5cfe2c5- Tree
aa68dfc- Author
Javier Provecho Fernandez <javiertitan@gmail.com>- Committer
Javier Provecho Fernandez <javiertitan@gmail.com>- Parent 1
28b9ff9- Parent 2
d936320
21 files changed+839 added−331 removed
modified:binding/binding.go+3 added-3 removed
85 unmodified lines86 if err := setWithProperType(sliceOf, inputValue[i], slice.Index(i)); err != nil {87 return err88 }89 }90- formStruct.Elem().Field(i).Set(slice)90+ formStruct.Field(i).Set(slice)91 } else {92 if err := setWithProperType(typeField.Type.Kind(), inputValue[0], structField); err != nil {93 return err94 }73 unmodified lines168 case reflect.Struct:169 for i := 0; i < typ.NumField(); i++ {170 field := typ.Field(i)171 172- // Allow ignored fields in the struct173- if field.Tag.Get("form") == "-" {172+ // Allow ignored and unexported fields in the struct173+ if field.Tag.Get("form") == "-" || field.PkgPath != "" {174 continue175 }176 177 fieldValue := val.Field(i).Interface()39 unmodified linesadded:examples/pluggable_renderer/example_pongo2.go+58 added
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+}added:examples/pluggable_renderer/index.html+12 added
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>modified:Godeps/Godeps.json+1 added-1 removed
2 unmodified lines34567789102 unmodified lines "GoVersion": "go1.3", "Deps": [ { "ImportPath": "github.com/julienschmidt/httprouter", "Rev": "7deadb6844d2c6ff1dfb812eaa439b87cdaedf20" "Rev": "aeec11926f7a8fab580383810e1b1bbba99bdaa7" } ]}modified:render/render.go+28 added-6 removed
28 unmodified lines29 // Redirects30 redirectRender struct{}31 32 // Redirects33- htmlDebugRender struct{}33+ htmlDebugRender struct {34+ files []string35+ globs []string36+ }37 38 // form binding39 HTMLRender struct {40 Template *template.Template4 unmodified lines45 JSON = jsonRender{}46 XML = xmlRender{}47 Plain = plainRender{}48 Redirect = redirectRender{}46- HTMLDebug = htmlDebugRender{}49+ HTMLDebug = &htmlDebugRender{}50 )51 52 func writeHeader(w http.ResponseWriter, code int, contentType string) {53 w.Header().Set("Content-Type", contentType)30 unmodified lines84 }85 return err86 }87 88+func (r *htmlDebugRender) AddGlob(pattern string) {89+ r.globs = append(r.globs, pattern)90+}91+92+func (r *htmlDebugRender) AddFiles(files ...string) {93+ r.files = append(r.files, files...)94+}95+85-func (_ htmlDebugRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {96+func (r *htmlDebugRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {97 writeHeader(w, code, "text/html")98 file := data[0].(string)99 obj := data[1]89- t, err := template.ParseFiles(file)90- if err != nil {91- return err100+101+ t := template.New("")102+103+ if len(r.files) > 0 {104+ if _, err := t.ParseFiles(r.files...); err != nil {105+ return err106+ }107 }108+109+ for _, glob := range r.globs {110+ if _, err := t.ParseGlob(glob); err != nil {111+ return err112+ }113+ }114+115 return t.ExecuteTemplate(w, file, obj)116 }117 118 func (html HTMLRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {5 unmodified linesmodified:.travis.yml+2 added-1 removed
1223456language: go
sudo: falsego: - 1.3 - 1.4 - tipmodified:auth.go+52 added-50 removed
14 unmodified lines15 AuthUserKey = "user"16 )17 18 type (19- BasicAuthPair struct {20- Code string21- User string22- }19 Accounts map[string]string24- Pairs []BasicAuthPair20+ authPair struct {21+ Value string22+ User string23+ }24+ authPairs []authPair25 )26 27-func (a Pairs) Len() int { return len(a) }28-func (a Pairs) Swap(i, j int) { a[i], a[j] = a[j], a[i] }29-func (a Pairs) Less(i, j int) bool { return a[i].Code < a[j].Code }27+func (a authPairs) Len() int { return len(a) }28+func (a authPairs) Swap(i, j int) { a[i], a[j] = a[j], a[i] }29+func (a authPairs) Less(i, j int) bool { return a[i].Value < a[j].Value }30 31-func processCredentials(accounts Accounts) (Pairs, error) {31+// Implements a basic Basic HTTP Authorization. It takes as argument a map[string]string where32+// the key is the user name and the value is the password.33+func BasicAuth(accounts Accounts) HandlerFunc {34+ pairs, err := processAccounts(accounts)35+ if err != nil {36+ panic(err)37+ }38+ return func(c *Context) {39+ // Search user in the slice of allowed credentials40+ user, ok := searchCredential(pairs, c.Request.Header.Get("Authorization"))41+ if !ok {42+ // Credentials doesn't match, we return 401 Unauthorized and abort request.43+ c.Writer.Header().Set("WWW-Authenticate", "Basic realm=\"Authorization Required\"")44+ c.Fail(401, errors.New("Unauthorized"))45+ } else {46+ // user is allowed, set UserId to key "user" in this context, the userId can be read later using47+ // c.Get(gin.AuthUserKey)48+ c.Set(AuthUserKey, user)49+ }50+ }51+}52+53+func processAccounts(accounts Accounts) (authPairs, error) {54 if len(accounts) == 0 {33- return nil, errors.New("Empty list of authorized credentials.")55+ return nil, errors.New("Empty list of authorized credentials")56 }35- pairs := make(Pairs, 0, len(accounts))57+ pairs := make(authPairs, 0, len(accounts))58 for user, password := range accounts {37- if len(user) == 0 || len(password) == 0 {38- return nil, errors.New("User or password is empty")59+ if len(user) == 0 {60+ return nil, errors.New("User can not be empty")61 }62 base := user + ":" + password41- code := "Basic " + base64.StdEncoding.EncodeToString([]byte(base))42- pairs = append(pairs, BasicAuthPair{code, user})63+ value := "Basic " + base64.StdEncoding.EncodeToString([]byte(base))64+ pairs = append(pairs, authPair{65+ Value: value,66+ User: user,67+ })68 }69 // We have to sort the credentials in order to use bsearch later.70 sort.Sort(pairs)71 return pairs, nil72 }73 49-func secureCompare(given, actual string) bool {50- if subtle.ConstantTimeEq(int32(len(given)), int32(len(actual))) == 1 {51- return subtle.ConstantTimeCompare([]byte(given), []byte(actual)) == 152- } else {53- /* Securely compare actual to itself to keep constant time, but always return false */54- return subtle.ConstantTimeCompare([]byte(actual), []byte(actual)) == 1 && false55- }56-}57-58-func searchCredential(pairs Pairs, auth string) string {74+func searchCredential(pairs authPairs, auth string) (string, bool) {75 if len(auth) == 0 {60- return ""76+ return "", false77 }78 // Search user in the slice of allowed credentials63- r := sort.Search(len(pairs), func(i int) bool { return pairs[i].Code >= auth })64- if r < len(pairs) && secureCompare(pairs[r].Code, auth) {65- return pairs[r].User79+ r := sort.Search(len(pairs), func(i int) bool { return pairs[i].Value >= auth })80+ if r < len(pairs) && secureCompare(pairs[r].Value, auth) {81+ return pairs[r].User, true82 } else {67- return ""83+ return "", false84 }85 }86 71-// Implements a basic Basic HTTP Authorization. It takes as argument a map[string]string where72-// the key is the user name and the value is the password.73-func BasicAuth(accounts Accounts) HandlerFunc {74-75- pairs, err := processCredentials(accounts)76- if err != nil {77- panic(err)87+func secureCompare(given, actual string) bool {88+ if subtle.ConstantTimeEq(int32(len(given)), int32(len(actual))) == 1 {89+ return subtle.ConstantTimeCompare([]byte(given), []byte(actual)) == 190+ } else {91+ /* Securely compare actual to itself to keep constant time, but always return false */92+ return subtle.ConstantTimeCompare([]byte(actual), []byte(actual)) == 1 && false93 }79- return func(c *Context) {80- // Search user in the slice of allowed credentials81- user := searchCredential(pairs, c.Request.Header.Get("Authorization"))82- if len(user) == 0 {83- // Credentials doesn't match, we return 401 Unauthorized and abort request.84- c.Writer.Header().Set("WWW-Authenticate", "Basic realm=\"Authorization Required\"")85- c.Fail(401, errors.New("Unauthorized"))86- } else {87- // user is allowed, set UserId to key "user" in this context, the userId can be read later using88- // c.Get(gin.AuthUserKey)89- c.Set(AuthUserKey, user)90- }91- }94 }modified:AUTHORS.md+54 added-4 removed
112345678978910111216 unmodified lines293031323334353637383940414243442 unmodified lines474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697982 unmodified lines10110210310410510610710810911011111211311411511611711 unmodified lines129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158List of all the awesome people working to make Gin the best Web Framework in Go!List of all the awesome people working to make Gin the best Web Framework in Go.
##gin 0.x series authors
**Lead Developer:** Manu Martinez-Almeida (@manucorporat) **Staff:**Javier Provecho (@javierprovecho)**Original Developer:** Manu Martinez-Almeida (@manucorporat) **Long-term Maintainer:** Javier Provecho (@javierprovecho)
People and companies, who have contributed, in alphabetical order.
**@adammck (Adam Mckaig)**16 unmodified lines**@austinheap (Austin Heap)**- Added travis CI integration
**@andredublin (Andre Dublin)**- Fix typo in comment
**@bredov (Ludwig Valda Vasquez)**- Fix html templating in debug mode
**@bluele (Jun Kimura)**- Fixes code examples in README
2 unmodified lines
**@dickeyxxx (Jeff Dickey)**- Typos in README- Add example about serving static files
**@dutchcoders (DutchCoders)**- ★ Fix security bug that allows client to spoof ip- Fix typo. r.HTMLTemplates -> SetHTMLTemplate
**@fmd (Fareed Dudhia)**- Fix typo. SetHTTPTemplate -> SetHTMLTemplate
**@jammie-stackhouse (Jamie Stackhouse)- Add more shortcuts for router methods
**@jasonrhansen**- Fix spelling and grammar errors in documentation
**@JasonSoft (Jason Lee)**- Fix typo in comment
**@julienschmidt (Julien Schmidt)**- gofmt the code examples
**@kelcecil (Kel Cecil)**- Fix readme typo
**@kyledinh (Kyle Dinh)**- Adds RunTLS()
**@LinusU (Linus Unnebäck)**- Small fixes in README
**@loongmxbt (Saint Asky)**- Fix typo in example
**@lucas-clemente (Lucas Clemente)**- ★ work around path.Join removing trailing slashes from routes
2 unmodified lines- No repeat call c.Writer.Status() in gin.Logger- Fixes Content-Type for json render
**@mirzac (Mirza Ceric)**- Fix debug printing
**@mopemope (Yutaka Matsubara)**- ★ Adds Godep support (Dependencies Manager)- Fix variadic parameter in the flexible render API- Fix Corrupted plain render- Add Pluggable View Renderer Example
**@msemenistyi (Mykyta Semenistyi)**- update Readme.md. Add code to String method11 unmodified lines**@r8k (Rajiv Kilaparti)**- Fix Port usage in README.
**@se77en (Damon Zhao)**- Improve color logging
**@silasb (Silas Baronda)**- Fixing quotes in README
**@SkuliOskarsson (Skuli Oskarsson)**- Fixes some texts in README II
**@slimmy (Jimmy Pettersson)- Added messages for required bindings
**@smira (Andrey Smirnov)**- Add support for ignored/unexported fields in binding
**@yosssi (Keiji Yoshida)**- Fix link in README
**@yuyabee**- Fixed READMENo newline at end of fileNo newline at end of filemodified:CHANGELOG.md+8 added-1 removed
1 #Changelog2 3+###Gin 0.5 (Jan 4, 2015)4+5+- [NEW] Content Negotiation6+- [FIX] Solved security bug that allow a client to spoof ip7+- [FIX] Fix unexported/ignored fields in binding8+9+10 ###Gin 0.4 (Aug 21, 2014)11 12 - [NEW] Development mode13 - [NEW] Unit tests26 unmodified lines40 - [NEW] Completely new logger41 - [NEW] New API for serving static files. gin.Static()42 - [NEW] gin.H() can be serialized into XML43 - [NEW] Typed errors. Errors can be typed. Internet/external/custom.37-- [NEW] Support for Godebs44+- [NEW] Support for Godeps45 - [NEW] Travis/Godocs badges in README46 - [NEW] New Bind() and BindWith() methods for parsing request body.47 - [NEW] Add Content.Copy()48 - [NEW] Add context.LastError()13 unmodified linesmodified:context_test.go+44 added-3 removed
230 unmodified lines231 stepsPassed += 1232 c.Next()233 stepsPassed += 1234 // after check and abort235- c.Abort(409)235+ c.AbortWithStatus(409)236 })237 r.Use(func(c *Context) {238 stepsPassed += 1239 c.Next()240 stepsPassed += 1241- c.Abort(403)241+ c.AbortWithStatus(403)242 })243 244 // RUN245 w := PerformRequest(r, "GET", "/")13 unmodified lines259 var stepsPassed int = 0260 r := New()261 r.Use(func(context *Context) {262 stepsPassed += 1263- context.Abort(409)263+ context.AbortWithStatus(409)264 })265 r.Use(func(context *Context) {266 stepsPassed += 1267 context.Next()171 unmodified lines439 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 }442 }443+444+func TestClientIP(t *testing.T) {445+ r := New()446+447+ var clientIP string = ""448+ r.GET("/", func(c *Context) {449+ clientIP = c.ClientIP()450+ })451+452+ body := bytes.NewBuffer([]byte(""))453+ req, _ := http.NewRequest("GET", "/", body)454+ req.RemoteAddr = "clientip:1234"455+ w := httptest.NewRecorder()456+ r.ServeHTTP(w, req)457+458+ if clientIP != "clientip:1234" {459+ t.Errorf("ClientIP should not be %s, but clientip:1234", clientIP)460+ }461+}462+463+func TestClientIPWithXForwardedForWithProxy(t *testing.T) {464+ r := New()465+ r.Use(ForwardedFor())466+467+ var clientIP string = ""468+ r.GET("/", func(c *Context) {469+ clientIP = c.ClientIP()470+ })471+472+ body := bytes.NewBuffer([]byte(""))473+ req, _ := http.NewRequest("GET", "/", body)474+ req.RemoteAddr = "172.16.8.3:1234"475+ req.Header.Set("X-Real-Ip", "realip")476+ req.Header.Set("X-Forwarded-For", "1.2.3.4, 10.10.0.4, 192.168.0.43, 172.16.8.4")477+ w := httptest.NewRecorder()478+ r.ServeHTTP(w, req)479+480+ if clientIP != "1.2.3.4:0" {481+ t.Errorf("ClientIP should not be %s, but 1.2.3.4:0", clientIP)482+ }483+}modified:context.go+182 added-25 removed
10 unmodified lines11 "github.com/gin-gonic/gin/binding"12 "github.com/gin-gonic/gin/render"13 "github.com/julienschmidt/httprouter"14 "log"15+ "net"16 "net/http"17+ "strings"18 )19 20 const (21 ErrorTypeInternal = 1 << iota46 unmodified lines68 Params httprouter.Params69 Engine *Engine70 handlers []HandlerFunc71 index int872+ accepted []string73 }74 75 /************************************/73-/********** ROUTES GROUPING *********/76+/********** CONTEXT CREATION ********/77 /************************************/78 79 func (engine *Engine) createContext(w http.ResponseWriter, req *http.Request, params httprouter.Params, handlers []HandlerFunc) *Context {77- c := engine.cache.Get().(*Context)80+ c := engine.pool.Get().(*Context)81 c.writermem.reset(w)82 c.Request = req83 c.Params = params84 c.handlers = handlers85 c.Keys = nil86 c.index = -187+ c.accepted = nil88 c.Errors = c.Errors[0:0]89 return c90 }91 88-/************************************/89-/****** FLOW AND ERROR MANAGEMENT****/90-/************************************/92+func (engine *Engine) reuseContext(c *Context) {93+ engine.pool.Put(c)94+}95 96 func (c *Context) Copy() *Context {97 var cp Context = *c98 cp.index = AbortIndex99 cp.handlers = nil100 return &cp101 }102 103+/************************************/104+/*************** FLOW ***************/105+/************************************/106+107 // Next should be used only in the middlewares.108 // It executes the pending handlers in the chain inside the calling handler.109 // See example in github.110 func (c *Context) Next() {3 unmodified lines114 c.handlers[c.index](c)115 }116 }117 110-// Forces the system to do not continue calling the pending handlers.111-// For example, the first handler checks if the request is authorized. If it's not, context.Abort(401) should be called.112-// The rest of pending handlers would never be called for that request.113-func (c *Context) Abort(code int) {114- if code >= 0 {115- c.Writer.WriteHeader(code)116- }118+// Forces the system to do not continue calling the pending handlers in the chain.119+func (c *Context) Abort() {120 c.index = AbortIndex121 }122 123+// Same than AbortWithStatus() but also writes the specified response status code.124+// For example, the first handler checks if the request is authorized. If it's not, context.AbortWithStatus(401) should be called.125+func (c *Context) AbortWithStatus(code int) {126+ c.Writer.WriteHeader(code)127+ c.Abort()128+}129+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)124-// context.Abort(500)138+// context.AbortWithStatus(500)139 // ```140 func (c *Context) Fail(code int, err error) {141 c.Error(err, "Operation aborted")128- c.Abort(code)142+ c.AbortWithStatus(code)143 }144 145 func (c *Context) ErrorTyped(err error, typ uint32, meta interface{}) {146 c.Errors = append(c.Errors, errorMsg{10 unmodified lines157 c.ErrorTyped(err, ErrorTypeExternal, meta)158 }159 160 func (c *Context) LastError() error {147- s := len(c.Errors)148- if s > 0 {149- return errors.New(c.Errors[s-1].Err)161+ nuErrors := len(c.Errors)162+ if nuErrors > 0 {163+ return errors.New(c.Errors[nuErrors-1].Err)164 } else {165 return nil166 }167 }13 unmodified lines181 182 // 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) {184 if c.Keys != nil {171- item, ok := c.Keys[key]185+ value, ok := c.Keys[key]186 if ok {173- return item, nil187+ return value, nil188 }189 }190 return nil, errors.New("Key does not exist.")191 }1 unmodified line193 // MustGet returns the value for the given key or panics if the value doesn't exist.194 func (c *Context) MustGet(key string) interface{} {195 value, err := c.Get(key)196 if err != nil || value == nil {183- log.Panicf("Key %s doesn't exist", key)197+ log.Panicf("Key %s doesn't exist", value)198 }199 return value200 }201 202+func ipInMasks(ip net.IP, masks []interface{}) bool {203+ for _, proxy := range masks {204+ var mask *net.IPNet205+ var err error206+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+ }217+218+ if mask.Contains(ip) {219+ return true220+ }221+ }222+223+ return false224+}225+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", "172.16.0.0/12", "192.168.0.0/16"}234+235+ proxies = make([]interface{}, len(reservedLocalIps))236+237+ for i, v := range reservedLocalIps {238+ proxies[i] = v239+ }240+ }241+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.247+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+ }275+ }276+}277+278+func (c *Context) ClientIP() string {279+ return c.Request.RemoteAddr280+}281+282 /************************************/189-/******** ENCODING MANAGEMENT********/283+/********* PARSING REQUEST **********/284 /************************************/285 286 // This function checks the Content-Type to select a binding engine automatically,287 // Depending the "Content-Type" header different bindings are used:25 unmodified lines313 }314 return true315 }316 317+/************************************/318+/******** RESPONSE RENDERING ********/319+/************************************/320+321 func (c *Context) Render(code int, render render.Render, obj ...interface{}) {322 if err := render.Render(c.Writer, code, obj...); err != nil {323 c.ErrorTyped(err, ErrorTypeInternal, obj)226- c.Abort(500)324+ c.AbortWithStatus(500)325 }326 }327 328 // Serializes the given struct as JSON into the response body in a fast and efficient way.33 unmodified lines362 func (c *Context) Data(code int, contentType string, data []byte) {363 if len(contentType) > 0 {364 c.Writer.Header().Set("Content-Type", contentType)365 }268- if code >= 0 {269- c.Writer.WriteHeader(code)366+ c.Writer.WriteHeader(code)270- }367 c.Writer.Write(data)368 }369 370 // Writes the specified file into the body stream371 func (c *Context) File(filepath string) {372 http.ServeFile(c.Writer, c.Request, filepath)373 }374+375+/************************************/376+/******** CONTENT NEGOTIATION *******/377+/************************************/378+379+type Negotiate struct {380+ Offered []string381+ HTMLPath string382+ HTMLData interface{}383+ JSONData interface{}384+ XMLData interface{}385+ Data interface{}386+}387+388+func (c *Context) Negotiate(code int, config Negotiate) {389+ switch c.NegotiateFormat(config.Offered...) {390+ case MIMEJSON:391+ data := chooseData(config.JSONData, config.Data)392+ c.JSON(code, data)393+394+ case MIMEHTML:395+ data := chooseData(config.HTMLData, config.Data)396+ if len(config.HTMLPath) == 0 {397+ panic("negotiate config is wrong. html path is needed")398+ }399+ c.HTML(code, config.HTMLPath, data)400+401+ case MIMEXML:402+ data := chooseData(config.XMLData, config.Data)403+ c.XML(code, data)404+405+ default:406+ c.Fail(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server"))407+ }408+}409+410+func (c *Context) NegotiateFormat(offered ...string) string {411+ if len(offered) == 0 {412+ panic("you must provide at least one offer")413+ }414+ if c.accepted == nil {415+ c.accepted = parseAccept(c.Request.Header.Get("Accept"))416+ }417+ if len(c.accepted) == 0 {418+ return offered[0]419+420+ } else {421+ for _, accepted := range c.accepted {422+ for _, offert := range offered {423+ if accepted == offert {424+ return offert425+ }426+ }427+ }428+ return ""429+ }430+}431+432+func (c *Context) SetAccepted(formats ...string) {433+ c.accepted = formats434+}modified:deprecated.go+1 added-1 removed
39 unmodified lines40 func (engine *Engine) LoadHTMLTemplates(pattern string) {41 engine.LoadHTMLGlob(pattern)42 }43 44-// DEPRECATED. Use NotFound() instead44+// DEPRECATED. Use NoRoute() instead45 func (engine *Engine) NotFound404(handlers ...HandlerFunc) {46 engine.NoRoute(handlers...)47 }modified:gin_test.go+4 added-5 removed
106 unmodified lines107 // TEST108 if passed == true {109 t.Errorf(method + " route handler was invoked, when it should not")110 }111- if w.Code != http.StatusNotFound {112- // If this fails, it's because httprouter needs to be updated to at least f78f58a0db113- t.Errorf("Status code should be %v, was %d. Location: %s", http.StatusNotFound, w.Code, w.HeaderMap.Get("Location"))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 }115 116 // TestSingleRouteOK tests that POST route is correctly invoked.27 unmodified lines144 w := PerformRequest(r, "GET", filePath)145 146 // TEST147 if w.Code != 200 {149- t.Errorf("Response code should be Ok, was: %s", w.Code)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 }13 unmodified lines166 167 // TEST168 bodyAsString := w.Body.String()169 if w.Code != 200 {171- t.Errorf("Response code should be Ok, was: %s", w.Code)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 }32 unmodified linesmodified:gin.go+46 added-165 removed
3 unmodified lines4 5 package gin6 7 import (8- "fmt"8 "github.com/gin-gonic/gin/render"9 "github.com/julienschmidt/httprouter"10 "html/template"11 "math"12 "net/http"14- "path"13 "sync"14 )15 16 const (8 unmodified lines25 26 type (27 HandlerFunc func(*Context)28 31- // Used internally to configure router, a RouterGroup is associated with a prefix32- // and an array of handlers (middlewares)33- RouterGroup struct {34- Handlers []HandlerFunc35- prefix string36- parent *RouterGroup37- engine *Engine38- }39-29 // Represents the web framework, it wraps the blazing fast httprouter multiplexer and a list of global middlewares.30 Engine struct {31 *RouterGroup43- HTMLRender render.Render44- cache sync.Pool45- finalNoRoute []HandlerFunc46- noRoute []HandlerFunc47- router *httprouter.Router32+ HTMLRender render.Render33+ Default404Body []byte34+ pool sync.Pool35+ allNoRoute []HandlerFunc36+ noRoute []HandlerFunc37+ router *httprouter.Router38 }39 )40 51-func (engine *Engine) handle404(w http.ResponseWriter, req *http.Request) {52- c := engine.createContext(w, req, nil, engine.finalNoRoute)53- // set 404 by default, useful for logging54- c.Writer.WriteHeader(404)55- c.Next()56- if !c.Writer.Written() {57- if c.Writer.Status() == 404 {58- c.Data(-1, MIMEPlain, []byte("404 page not found"))59- } else {60- c.Writer.WriteHeaderNow()61- }62- }63- engine.cache.Put(c)64-}65-41 // Returns a new blank Engine instance without any middleware attached.42 // The most basic configuration43 func New() *Engine {44 engine := &Engine{}70- engine.RouterGroup = &RouterGroup{nil, "/", nil, engine}45+ engine.RouterGroup = &RouterGroup{46+ Handlers: nil,47+ absolutePath: "/",48+ engine: engine,49+ }50 engine.router = httprouter.New()51+ engine.Default404Body = []byte("404 page not found")52 engine.router.NotFound = engine.handle40473- engine.cache.New = func() interface{} {53+ engine.pool.New = func() interface{} {54 c := &Context{Engine: engine}55 c.Writer = &c.writermem56 return c57 }7 unmodified lines65 return engine66 }67 68 func (engine *Engine) LoadHTMLGlob(pattern string) {89- if gin_mode == debugCode {69+ if IsDebugging() {70+ render.HTMLDebug.AddGlob(pattern)71 engine.HTMLRender = render.HTMLDebug72 } else {73 templ := template.Must(template.ParseGlob(pattern))74 engine.SetHTMLTemplate(templ)75 }76 }77 78 func (engine *Engine) LoadHTMLFiles(files ...string) {98- if gin_mode == debugCode {79+ if IsDebugging() {80+ render.HTMLDebug.AddFiles(files...)81 engine.HTMLRender = render.HTMLDebug82 } else {83 templ := template.Must(template.ParseFiles(files...))84 engine.SetHTMLTemplate(templ)8 unmodified lines93 94 // Adds handlers for NoRoute. It return a 404 code by default.95 func (engine *Engine) NoRoute(handlers ...HandlerFunc) {96 engine.noRoute = handlers115- engine.finalNoRoute = engine.combineHandlers(engine.noRoute)97+ engine.rebuild404Handlers()98 }99 100 func (engine *Engine) Use(middlewares ...HandlerFunc) {101 engine.RouterGroup.Use(middlewares...)120- engine.finalNoRoute = engine.combineHandlers(engine.noRoute)102+ engine.rebuild404Handlers()103 }104 123-// ServeHTTP makes the router implement the http.Handler interface.124-func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {125- engine.router.ServeHTTP(w, req)105+func (engine *Engine) rebuild404Handlers() {106+ engine.allNoRoute = engine.combineHandlers(engine.noRoute)107 }108 128-func (engine *Engine) Run(addr string) {129- if gin_mode == debugCode {130- fmt.Println("[GIN-debug] Listening and serving HTTP on " + addr)109+func (engine *Engine) handle404(w http.ResponseWriter, req *http.Request) {110+ c := engine.createContext(w, req, nil, engine.allNoRoute)111+ // set 404 by default, useful for logging112+ c.Writer.WriteHeader(404)113+ c.Next()114+ if !c.Writer.Written() {115+ if c.Writer.Status() == 404 {116+ c.Data(-1, MIMEPlain, engine.Default404Body)117+ } else {118+ c.Writer.WriteHeaderNow()119+ }120 }132- if err := http.ListenAndServe(addr, engine); err != nil {133- panic(err)134- }121+ engine.reuseContext(c)122 }123 137-func (engine *Engine) RunTLS(addr string, cert string, key string) {138- if gin_mode == debugCode {139- fmt.Println("[GIN-debug] Listening and serving HTTPS on " + addr)140- }141- if err := http.ListenAndServeTLS(addr, cert, key, engine); err != nil {142- panic(err)143- }124+// ServeHTTP makes the router implement the http.Handler interface.125+func (engine *Engine) ServeHTTP(writer http.ResponseWriter, request *http.Request) {126+ engine.router.ServeHTTP(writer, request)127 }128 146-/************************************/147-/********** ROUTES GROUPING *********/148-/************************************/149-150-// Adds middlewares to the group, see example code in github.151-func (group *RouterGroup) Use(middlewares ...HandlerFunc) {152- group.Handlers = append(group.Handlers, middlewares...)153-}154-155-// Creates a new router group. You should add all the routes that have common middlwares or the same path prefix.156-// For example, all the routes that use a common middlware for authorization could be grouped.157-func (group *RouterGroup) Group(component string, handlers ...HandlerFunc) *RouterGroup {158- prefix := group.pathFor(component)159-160- return &RouterGroup{161- Handlers: group.combineHandlers(handlers),162- parent: group,163- prefix: prefix,164- engine: group.engine,129+func (engine *Engine) Run(addr string) error {130+ debugPrint("Listening and serving HTTP on %s", addr)131+ if err := http.ListenAndServe(addr, engine); err != nil {132+ return err133 }134+ return nil135 }136 168-func (group *RouterGroup) pathFor(p string) string {169- joined := path.Join(group.prefix, p)170- // Append a '/' if the last component had one, but only if it's not there already171- if len(p) > 0 && p[len(p)-1] == '/' && joined[len(joined)-1] != '/' {172- return joined + "/"137+func (engine *Engine) RunTLS(addr string, cert string, key string) error {138+ debugPrint("Listening and serving HTTPS on %s", addr)139+ if err := http.ListenAndServeTLS(addr, cert, key, engine); err != nil {140+ return err141 }174- return joined142+ return nil143 }176-177-// Handle registers a new request handle and middlewares with the given path and method.178-// The last handler should be the real handler, the other ones should be middlewares that can and should be shared among different routes.179-// See the example code in github.180-//181-// For GET, POST, PUT, PATCH and DELETE requests the respective shortcut182-// functions can be used.183-//184-// This function is intended for bulk loading and to allow the usage of less185-// frequently used, non-standardized or custom methods (e.g. for internal186-// communication with a proxy).187-func (group *RouterGroup) Handle(method, p string, handlers []HandlerFunc) {188- p = group.pathFor(p)189- handlers = group.combineHandlers(handlers)190- if gin_mode == debugCode {191- nuHandlers := len(handlers)192- name := funcName(handlers[nuHandlers-1])193- fmt.Printf("[GIN-debug] %-5s %-25s --> %s (%d handlers)\n", method, p, name, nuHandlers)194- }195- group.engine.router.Handle(method, p, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {196- c := group.engine.createContext(w, req, params, handlers)197- c.Next()198- c.Writer.WriteHeaderNow()199- group.engine.cache.Put(c)200- })201-}202-203-// POST is a shortcut for router.Handle("POST", path, handle)204-func (group *RouterGroup) POST(path string, handlers ...HandlerFunc) {205- group.Handle("POST", path, handlers)206-}207-208-// GET is a shortcut for router.Handle("GET", path, handle)209-func (group *RouterGroup) GET(path string, handlers ...HandlerFunc) {210- group.Handle("GET", path, handlers)211-}212-213-// DELETE is a shortcut for router.Handle("DELETE", path, handle)214-func (group *RouterGroup) DELETE(path string, handlers ...HandlerFunc) {215- group.Handle("DELETE", path, handlers)216-}217-218-// PATCH is a shortcut for router.Handle("PATCH", path, handle)219-func (group *RouterGroup) PATCH(path string, handlers ...HandlerFunc) {220- group.Handle("PATCH", path, handlers)221-}222-223-// PUT is a shortcut for router.Handle("PUT", path, handle)224-func (group *RouterGroup) PUT(path string, handlers ...HandlerFunc) {225- group.Handle("PUT", path, handlers)226-}227-228-// OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle)229-func (group *RouterGroup) OPTIONS(path string, handlers ...HandlerFunc) {230- group.Handle("OPTIONS", path, handlers)231-}232-233-// HEAD is a shortcut for router.Handle("HEAD", path, handle)234-func (group *RouterGroup) HEAD(path string, handlers ...HandlerFunc) {235- group.Handle("HEAD", path, handlers)236-}237-238-// Static serves files from the given file system root.239-// Internally a http.FileServer is used, therefore http.NotFound is used instead240-// of the Router's NotFound handler.241-// To use the operating system's file system implementation,242-// use :243-// router.Static("/static", "/var/www")244-func (group *RouterGroup) Static(p, root string) {245- prefix := group.pathFor(p)246- p = path.Join(p, "/*filepath")247- fileServer := http.StripPrefix(prefix, http.FileServer(http.Dir(root)))248- group.GET(p, func(c *Context) {249- fileServer.ServeHTTP(c.Writer, c.Request)250- })251- group.HEAD(p, func(c *Context) {252- fileServer.ServeHTTP(c.Writer, c.Request)253- })254-}255-256-func (group *RouterGroup) combineHandlers(handlers []HandlerFunc) []HandlerFunc {257- s := len(group.Handlers) + len(handlers)258- h := make([]HandlerFunc, 0, s)259- h = append(h, group.Handlers...)260- h = append(h, handlers...)261- return h262-}modified:logger.go+58 added-35 removed
8 unmodified lines9 "os"10 "time"11 )12 13+var (14+ green = string([]byte{27, 91, 57, 55, 59, 52, 50, 109})15+ white = string([]byte{27, 91, 57, 48, 59, 52, 55, 109})16+ yellow = string([]byte{27, 91, 57, 55, 59, 52, 51, 109})17+ red = string([]byte{27, 91, 57, 55, 59, 52, 49, 109})18+ blue = string([]byte{27, 91, 57, 55, 59, 52, 52, 109})19+ magenta = string([]byte{27, 91, 57, 55, 59, 52, 53, 109})20+ cyan = string([]byte{27, 91, 57, 55, 59, 52, 54, 109})21+ reset = string([]byte{27, 91, 48, 109})22+)23+24 func ErrorLogger() HandlerFunc {25 return ErrorLoggerT(ErrorTypeAll)26 }27 8 unmodified lines36 }37 }38 }39 29-var (30- green = string([]byte{27, 91, 57, 55, 59, 52, 50, 109})31- white = string([]byte{27, 91, 57, 48, 59, 52, 55, 109})32- yellow = string([]byte{27, 91, 57, 55, 59, 52, 51, 109})33- red = string([]byte{27, 91, 57, 55, 59, 52, 49, 109})34- reset = string([]byte{27, 91, 48, 109})35-)36-40 func Logger() HandlerFunc {41 stdlogger := log.New(os.Stdout, "", 0)42 //errlogger := log.New(os.Stderr, "", 0)43 3 unmodified lines47 48 // Process request49 c.Next()50 48- // save the IP of the requester49- requester := c.Request.Header.Get("X-Real-IP")50- // if the requester-header is empty, check the forwarded-header51- if len(requester) == 0 {52- requester = c.Request.Header.Get("X-Forwarded-For")53- }54- // if the requester is still empty, use the hard-coded address from the socket55- if len(requester) == 0 {56- requester = c.Request.RemoteAddr57- }58-59- var color string60- code := c.Writer.Status()61- switch {62- case code >= 200 && code <= 299:63- color = green64- case code >= 300 && code <= 399:65- color = white66- case code >= 400 && code <= 499:67- color = yellow68- default:69- color = red70- }51+ // Stop timer52 end := time.Now()53 latency := end.Sub(start)54+55+ clientIP := c.ClientIP()56+ method := c.Request.Method57+ statusCode := c.Writer.Status()58+ statusColor := colorForStatus(statusCode)59+ methodColor := colorForMethod(method)60+73- stdlogger.Printf("[GIN] %v |%s %3d %s| %12v | %s %4s %s\n%s",61+ stdlogger.Printf("[GIN] %v |%s %3d %s| %12v | %s |%s %s %-7s %s\n%s",62 end.Format("2006/01/02 - 15:04:05"),75- color, code, reset,63+ statusColor, statusCode, reset,64 latency,77- requester,78- c.Request.Method, c.Request.URL.Path,65+ clientIP,66+ methodColor, reset, method,67+ c.Request.URL.Path,68 c.Errors.String(),69 )70 }71 }72+73+func colorForStatus(code int) string {74+ switch {75+ case code >= 200 && code <= 299:76+ return green77+ case code >= 300 && code <= 399:78+ return white79+ case code >= 400 && code <= 499:80+ return yellow81+ default:82+ return red83+ }84+}85+86+func colorForMethod(method string) string {87+ switch {88+ case method == "GET":89+ return blue90+ case method == "POST":91+ return cyan92+ case method == "PUT":93+ return yellow94+ case method == "DELETE":95+ return red96+ case method == "PATCH":97+ return green98+ case method == "HEAD":99+ return magenta100+ case method == "OPTIONS":101+ return white102+ default:103+ return reset104+ }105+}modified:mode.go+24 added-7 removed
3 unmodified lines4 5 package gin6 7 import (8+ "fmt"9 "os"10 )11 12 const GIN_MODE = "GIN_MODE"9 unmodified lines22 testCode = iota23 )24 25 var gin_mode int = debugCode26+var mode_name string = DebugMode27 28+func init() {29+ value := os.Getenv(GIN_MODE)30+ if len(value) == 0 {31+ SetMode(DebugMode)32+ } else {33+ SetMode(value)34+ }35+}36+37 func SetMode(value string) {38 switch value {39 case DebugMode:40 gin_mode = debugCode1 unmodified line42 gin_mode = releaseCode43 case TestMode:44 gin_mode = testCode45 default:35- panic("gin mode unknown, the allowed modes are: " + DebugMode + " and " + ReleaseMode)46+ panic("gin mode unknown: " + value)47 }48+ mode_name = value49 }50 39-func init() {40- value := os.Getenv(GIN_MODE)41- if len(value) == 0 {42- SetMode(DebugMode)43- } else {44- SetMode(value)51+func Mode() string {52+ return mode_name53+}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 }modified:README.md+59 added-12 removed
1 unmodified line2 3 [](https://godoc.org/github.com/gin-gonic/gin)4 [](https://travis-ci.org/gin-gonic/gin)5 6-Gin is a web framework written in Golang. It features a martini-like API with much better performance, up to 40 times faster. If you need performance and good productivity, you will love Gin. 7-6+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. 7 8+9+10+```11+$ cat test.go12+```13+```go14+package main15+16+import "github.com/gin-gonic/gin"17+18+func main() {19+ router := gin.Default()20+ router.GET("/", func(c *gin.Context) {21+ c.String(200, "hello world")22+ })23+ router.GET("/ping", func(c *gin.Context) {24+ c.String(200, "pong")25+ })26+ router.POST("/submit", func(c *gin.Context) {27+ c.String(401, "not authorized")28+ })29+ router.PUT("/error", func(c *gin.Context) {30+ c.String(500, "and error hapenned :(")31+ })32+ router.Run(":8080")33+}34+```35+36 ##Gin is new, will it be supported?37 38 Yes, Gin is an internal project of [my](https://github.com/manucorporat) upcoming startup. We developed it and we are going to continue using and improve it.39 10 unmodified lines50 - [x] Improve XML support51 - [x] Flexible rendering system52 - [ ] More powerful validation API53 - [ ] Improve documentation27-- [ ] Add more cool middlewares, for example redis caching (this also helps developers to understand the framework).54+- [X] Add more cool middlewares, for example redis caching (this also helps developers to understand the framework).55 - [x] Continuous integration56 57 58 59 ## Start using it33-Obviously, you need to have Git and Go! already installed to run Gin. 60+Obviously, you need to have Git and Go already installed to run Gin. 61 Run this in your terminal62 63 ```64 go get github.com/gin-gonic/gin65 ```39-Then import it in your Go! code:66+Then import it in your Go code:67 68 ```69 import "github.com/gin-gonic/gin"70 ```178 unmodified lines249 func main() {250 r := gin.Default()251 252 // Example for binding JSON ({"user": "manu", "password": "123"})226- r.POST("/login", func(c *gin.Context) {253+ r.POST("/loginJSON", func(c *gin.Context) {254 var json LoginJSON255 256 c.Bind(&json) // This will infer what binder to use depending on the content-type header.257 if json.User == "manu" && json.Password == "123" {2 unmodified lines260 c.JSON(401, gin.H{"status": "unauthorized"})261 }262 })263 237- // Example for binding a HTLM form (user=manu&password=123)238- r.POST("/login", func(c *gin.Context) {264+ // Example for binding a HTML form (user=manu&password=123)265+ r.POST("/loginHTML", func(c *gin.Context) {266 var form LoginForm267 268 c.BindWith(&form, binding.Form) // You can also specify which binder to use. We support binding.Form, binding.JSON and binding.XML.269 if form.User == "manu" && form.Password == "123" {13 unmodified lines283 ```go284 func main() {285 r := gin.Default()286 260- // gin.H is a shortcup for map[string]interface{}287+ // gin.H is a shortcut for map[string]interface{}288 r.GET("/someJSON", func(c *gin.Context) {289 c.JSON(200, gin.H{"message": "hey", "status": 200})290 })291 20 unmodified lines312 r.Run(":8080")313 }314 ```315 316+####Serving static files317 318+Use Engine.ServeFiles(path string, root http.FileSystem):319+320+```go321+func main() {322+ r := gin.Default()323+ r.Static("/assets", "./assets")324+325+ // Listen and server on 0.0.0.0:8080326+ r.Run(":8080")327+}328+```329+330+Note: this will use `httpNotFound` instead of the Router's `NotFound` handler.331+332 ####Serving static files333 334 Use Engine.ServeFiles(path string, root http.FileSystem):335 15 unmodified lines351 352 ```go353 func main() {354 r := gin.Default()313- r.LoadHTMLTemplates("templates/*")355+ r.LoadHTMLGlob("templates/*")356 r.GET("/index", func(c *gin.Context) {357 obj := gin.H{"title": "Main website"}358 c.HTML(200, "index.tmpl", obj)359 })1 unmodified line361 // Listen and server on 0.0.0.0:8080362 r.Run(":8080")363 }364 ```365+```html366+<h1>367+ {{ .title }}368+</h1>369+```370 371 You can also use your own html template render372 373 ```go1 unmodified line375 376 func main() {377 r := gin.Default()378 html := template.Must(template.ParseFiles("file1", "file2"))332- r.HTMLTemplates = html379+ r.SetHTMLTemplate(html)380 381 // Listen and server on 0.0.0.0:8080382 r.Run(":8080")383 }75 unmodified lines459 // /admin/secrets endpoint460 // hit "localhost:8080/admin/secrets461 authorized.GET("/secrets", func(c *gin.Context) {462 // get user, it was setted by the BasicAuth middleware416- user := c.Get(gin.AuthUserKey).(string)463+ user := c.MustGet(gin.AuthUserKey).(string)464 if secret, ok := secrets[user]; ok {465 c.JSON(200, gin.H{"user": user, "secret": secret})466 } else {467 c.JSON(200, gin.H{"user": user, "secret": "NO SECRET :("})68 unmodified linesmodified:recovery_test.go+1 added-1 removed
37 unmodified lines38 log.SetOutput(bytes.NewBuffer(nil))39 r := New()40 r.Use(Recovery())41 r.GET("/recovery", func(c *Context) {42- c.Abort(400)42+ c.AbortWithStatus(400)43 panic("Oupps, Houston, we have a problem")44 })45 46 // RUN10 unmodified linesmodified:response_writer.go+19 added-8 removed
10 unmodified lines11 "net"12 "net/http"13 )14 15+const (16+ NoWritten = -117+)18+19 type (20 ResponseWriter interface {21 http.ResponseWriter22 http.Hijacker23 http.Flusher24 http.CloseNotifier25 26 Status() int27+ Size() int28 Written() bool29 WriteHeaderNow()30 }31 32 responseWriter struct {33 http.ResponseWriter29- status int30- written bool34+ status int35+ size int36 }37 )38 39 func (w *responseWriter) reset(writer http.ResponseWriter) {40 w.ResponseWriter = writer41 w.status = 20037- w.written = false42+ w.size = NoWritten43 }44 45 func (w *responseWriter) WriteHeader(code int) {46 if code > 0 {47 w.status = code43- if w.written {48+ if w.Written() {49 log.Println("[GIN] WARNING. Headers were already written!")50 }51 }52 }53 54 func (w *responseWriter) WriteHeaderNow() {50- if !w.written {51- w.written = true55+ if !w.Written() {56+ w.size = 057 w.ResponseWriter.WriteHeader(w.status)58 }59 }60 61 func (w *responseWriter) Write(data []byte) (n int, err error) {62 w.WriteHeaderNow()58- return w.ResponseWriter.Write(data)63+ n, err = w.ResponseWriter.Write(data)64+ w.size += n65+ return66 }67 68 func (w *responseWriter) Status() int {69 return w.status70 }71 72+func (w *responseWriter) Size() int {73+ return w.size74+}75+76 func (w *responseWriter) Written() bool {66- return w.written77+ return w.size != NoWritten78 }79 80 // Implements the http.Hijacker interface81 func (w *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {19 unmodified linesadded:routergroup.go+148 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+ "github.com/julienschmidt/httprouter"9+ "net/http"10+ "path"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 *Engine19+}20+21+// Adds middlewares to the group, see example code in github.22+func (group *RouterGroup) Use(middlewares ...HandlerFunc) {23+ group.Handlers = append(group.Handlers, middlewares...)24+}25+26+// 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,33+ }34+}35+36+// Handle registers a new request handle and middlewares with the given path and method.37+// The last handler should be the real handler, the other ones should be middlewares that can and should be shared among different routes.38+// See the example code in github.39+//40+// For GET, POST, PUT, PATCH and DELETE requests the respective shortcut41+// functions can be used.42+//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) {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+ }54+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+ })61+}62+63+// POST is a shortcut for router.Handle("POST", path, handle)64+func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) {65+ group.Handle("POST", relativePath, handlers)66+}67+68+// GET is a shortcut for router.Handle("GET", path, handle)69+func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) {70+ group.Handle("GET", relativePath, handlers)71+}72+73+// DELETE is a shortcut for router.Handle("DELETE", path, handle)74+func (group *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) {75+ group.Handle("DELETE", relativePath, handlers)76+}77+78+// PATCH is a shortcut for router.Handle("PATCH", path, handle)79+func (group *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc) {80+ group.Handle("PATCH", relativePath, handlers)81+}82+83+// PUT is a shortcut for router.Handle("PUT", path, handle)84+func (group *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) {85+ group.Handle("PUT", relativePath, handlers)86+}87+88+// OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle)89+func (group *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc) {90+ group.Handle("OPTIONS", relativePath, handlers)91+}92+93+// HEAD is a shortcut for router.Handle("HEAD", path, handle)94+func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) {95+ group.Handle("HEAD", relativePath, handlers)96+}97+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)101+}102+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)106+}107+108+// Static serves files from the given file system root.109+// Internally a http.FileServer is used, therefore http.NotFound is used instead110+// of the Router's NotFound handler.111+// To use the operating system's file system implementation,112+// use :113+// router.Static("/static", "/var/www")114+func (group *RouterGroup) Static(relativePath, root string) {115+ absolutePath := group.calculateAbsolutePath(relativePath)116+ handler := group.createStaticHandler(absolutePath, root)117+ absolutePath = path.Join(absolutePath, "/*filepath")118+119+ // Register GET and HEAD handlers120+ group.GET(absolutePath, handler)121+ group.HEAD(absolutePath, handler)122+}123+124+func (group *RouterGroup) createStaticHandler(absolutePath, root string) func(*Context) {125+ fileServer := http.StripPrefix(absolutePath, http.FileServer(http.Dir(root)))126+ return func(c *Context) {127+ fileServer.ServeHTTP(c.Writer, c.Request)128+ }129+}130+131+func (group *RouterGroup) combineHandlers(handlers []HandlerFunc) []HandlerFunc {132+ finalSize := len(group.Handlers) + len(handlers)133+ mergedHandlers := make([]HandlerFunc, 0, finalSize)134+ mergedHandlers = append(mergedHandlers, group.Handlers...)135+ return append(mergedHandlers, handlers...)136+}137+138+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 absolutePath148+}modified:utils.go+35 added-3 removed
6 unmodified lines7 import (8 "encoding/xml"9 "reflect"10 "runtime"11+ "strings"12 )13 14 type H map[string]interface{}15 21 unmodified lines37 return nil38 }39 40 func filterFlags(content string) string {40- for i, a := range content {41- if a == ' ' || a == ';' {41+ for i, char := range content {42+ if char == ' ' || char == ';' {43 return content[:i]44 }45 }46 return content47 }48 49+func chooseData(custom, wildcard interface{}) interface{} {50+ if custom == nil {51+ if wildcard == nil {52+ panic("negotiation config is invalid")53+ }54+ return wildcard55+ }56+ return custom57+}58+59+func parseAccept(accept string) []string {60+ parts := strings.Split(accept, ",")61+ for i, part := range parts {62+ index := strings.IndexByte(part, ';')63+ if index >= 0 {64+ part = part[0:index]65+ }66+ part = strings.TrimSpace(part)67+ parts[i] = part68+ }69+ return parts70+}71+72+func lastChar(str string) uint8 {73+ size := len(str)74+ if size == 0 {75+ panic("The length of the string can't be 0")76+ }77+ return str[size-1]78+}79+48-func funcName(f interface{}) string {80+func nameOfFunction(f interface{}) string {81 return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()82 }