Skip to content
Myr

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

21 files+839 added−331 removed

modified:binding/binding.go+3 added-3 removed
85 unmodified lines
86 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 lines
168 case reflect.Struct:169 for i := 0; i < typ.NumField(); i++ {170 field := typ.Field(i)171172 // 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 }176177 fieldValue := val.Field(i).Interface()
39 unmodified lines
added:examples/pluggable_renderer/example_pongo2.go+58 added
1package main23import (4 "github.com/flosch/pongo2"5 "github.com/gin-gonic/gin"6 "net/http"7)89type pongoRender struct {10 cache map[string]*pongo2.Template11}1213func newPongoRender() *pongoRender {14 return &pongoRender{map[string]*pongo2.Template{}}15}1617func 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}2324func (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.Template2829 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}4243func main() {44 r := gin.Default()45 r.HTMLRender = newPongoRender()4647 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 })5556 // Listen and server on 0.0.0.0:808057 r.Run(":8080")58}
added:examples/pluggable_renderer/index.html+12 added
modified:Godeps/Godeps.json+1 added-1 removed
modified:render/render.go+28 added-6 removed
28 unmodified lines
29 // Redirects30 redirectRender struct{}3132 // Redirects33 htmlDebugRender struct{}33 htmlDebugRender struct {34 files []string35 globs []string36 }3738 // form binding39 HTMLRender struct {40 Template *template.Template
4 unmodified lines
45 JSON = jsonRender{}46 XML = xmlRender{}47 Plain = plainRender{}48 Redirect = redirectRender{}46 HTMLDebug = htmlDebugRender{}49 HTMLDebug = &htmlDebugRender{}50)5152func writeHeader(w http.ResponseWriter, code int, contentType string) {53 w.Header().Set("Content-Type", contentType)
30 unmodified lines
84 }85 return err86}8788func (r *htmlDebugRender) AddGlob(pattern string) {89 r.globs = append(r.globs, pattern)90}9192func (r *htmlDebugRender) AddFiles(files ...string) {93 r.files = append(r.files, files...)94}9585func (_ htmlDebugRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {96func (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 err100101 t := template.New("")102103 if len(r.files) > 0 {104 if _, err := t.ParseFiles(r.files...); err != nil {105 return err106 }107 }108109 for _, glob := range r.globs {110 if _, err := t.ParseGlob(glob); err != nil {111 return err112 }113 }114115 return t.ExecuteTemplate(w, file, obj)116}117118func (html HTMLRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {
5 unmodified lines
modified:.travis.yml+2 added-1 removed
modified:auth.go+52 added-50 removed
14 unmodified lines
15 AuthUserKey = "user"16)1718type (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)2627func (a Pairs) Len() int { return len(a) }28func (a Pairs) Swap(i, j int) { a[i], a[j] = a[j], a[i] }29func (a Pairs) Less(i, j int) bool { return a[i].Code < a[j].Code }27func (a authPairs) Len() int { return len(a) }28func (a authPairs) Swap(i, j int) { a[i], a[j] = a[j], a[i] }29func (a authPairs) Less(i, j int) bool { return a[i].Value < a[j].Value }3031func 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.33func 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}5253func 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}7349func 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}5758func searchCredential(pairs Pairs, auth string) string {74func 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}8671// 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.73func BasicAuth(accounts Accounts) HandlerFunc {7475 pairs, err := processCredentials(accounts)76 if err != nil {77 panic(err)87func 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
modified:CHANGELOG.md+8 added-1 removed
1#Changelog23###Gin 0.5 (Jan 4, 2015)45- [NEW] Content Negotiation6- [FIX] Solved security bug that allow a client to spoof ip7- [FIX] Fix unexported/ignored fields in binding8910###Gin 0.4 (Aug 21, 2014)1112- [NEW] Development mode13- [NEW] Unit tests
26 unmodified lines
40- [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 lines
modified:context_test.go+44 added-3 removed
230 unmodified lines
231 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 })243244 // RUN245 w := PerformRequest(r, "GET", "/")
13 unmodified lines
259 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 lines
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 }442}443444func TestClientIP(t *testing.T) {445 r := New()446447 var clientIP string = ""448 r.GET("/", func(c *Context) {449 clientIP = c.ClientIP()450 })451452 body := bytes.NewBuffer([]byte(""))453 req, _ := http.NewRequest("GET", "/", body)454 req.RemoteAddr = "clientip:1234"455 w := httptest.NewRecorder()456 r.ServeHTTP(w, req)457458 if clientIP != "clientip:1234" {459 t.Errorf("ClientIP should not be %s, but clientip:1234", clientIP)460 }461}462463func TestClientIPWithXForwardedForWithProxy(t *testing.T) {464 r := New()465 r.Use(ForwardedFor())466467 var clientIP string = ""468 r.GET("/", func(c *Context) {469 clientIP = c.ClientIP()470 })471472 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)479480 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 lines
11 "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)1920const (21 ErrorTypeInternal = 1 << iota
46 unmodified lines
68 Params httprouter.Params69 Engine *Engine70 handlers []HandlerFunc71 index int872 accepted []string73}7475/************************************/73/********** ROUTES GROUPING *********/76/********** CONTEXT CREATION ********/77/************************************/7879func (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}9188/************************************/89/****** FLOW AND ERROR MANAGEMENT****/90/************************************/92func (engine *Engine) reuseContext(c *Context) {93 engine.pool.Put(c)94}9596func (c *Context) Copy() *Context {97 var cp Context = *c98 cp.index = AbortIndex99 cp.handlers = nil100 return &cp101}102103/************************************/104/*************** FLOW ***************/105/************************************/106107// 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.110func (c *Context) Next() {
3 unmodified lines
114 c.handlers[c.index](c)115 }116}117110// 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.113func (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.119func (c *Context) Abort() {120 c.index = AbortIndex121}122123// 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.125func (c *Context) AbortWithStatus(code int) {126 c.Writer.WriteHeader(code)127 c.Abort()128}129130/************************************/131/********* ERROR MANAGEMENT *********/132/************************************/133134// 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// ```140func (c *Context) Fail(code int, err error) {141 c.Error(err, "Operation aborted")128 c.Abort(code)142 c.AbortWithStatus(code)143}144145func (c *Context) ErrorTyped(err error, typ uint32, meta interface{}) {146 c.Errors = append(c.Errors, errorMsg{
10 unmodified lines
157 c.ErrorTyped(err, ErrorTypeExternal, meta)158}159160func (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 lines
181182// Get returns the value for the given key or an error if the key does not exist.183func (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 line
193// MustGet returns the value for the given key or panics if the value doesn't exist.194func (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}201202func ipInMasks(ip net.IP, masks []interface{}) bool {203 for _, proxy := range masks {204 var mask *net.IPNet205 var err error206207 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 }217218 if mask.Contains(ip) {219 return true220 }221 }222223 return false224}225226// 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.230func 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"}234235 proxies = make([]interface{}, len(reservedLocalIps))236237 for i, v := range reservedLocalIps {238 proxies[i] = v239 }240 }241242 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.247248 // check if remoteaddr is local ip or in list of defined proxies249 remoteIp := net.ParseIP(strings.Split(c.Request.RemoteAddr, ":")[0])250251 if !ipInMasks(remoteIp, proxies) {252 return253 }254255 if forwardedFor := c.Request.Header.Get("X-Forwarded-For"); forwardedFor != "" {256 parts := strings.Split(forwardedFor, ",")257258 for i := len(parts) - 1; i >= 0; i-- {259 part := parts[i]260261 ip := net.ParseIP(strings.TrimSpace(part))262263 if ipInMasks(ip, proxies) {264 continue265 }266267 // returning remote addr conform the original remote addr format268 c.Request.RemoteAddr = ip.String() + ":0"269270 // remove forwarded for address271 c.Request.Header.Set("X-Forwarded-For", "")272 return273 }274 }275 }276}277278func (c *Context) ClientIP() string {279 return c.Request.RemoteAddr280}281282/************************************/189/******** ENCODING MANAGEMENT********/283/********* PARSING REQUEST **********/284/************************************/285286// This function checks the Content-Type to select a binding engine automatically,287// Depending the "Content-Type" header different bindings are used:
25 unmodified lines
313 }314 return true315}316317/************************************/318/******** RESPONSE RENDERING ********/319/************************************/320321func (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}327328// Serializes the given struct as JSON into the response body in a fast and efficient way.
33 unmodified lines
362func (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}369370// Writes the specified file into the body stream371func (c *Context) File(filepath string) {372 http.ServeFile(c.Writer, c.Request, filepath)373}374375/************************************/376/******** CONTENT NEGOTIATION *******/377/************************************/378379type Negotiate struct {380 Offered []string381 HTMLPath string382 HTMLData interface{}383 JSONData interface{}384 XMLData interface{}385 Data interface{}386}387388func (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)393394 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)400401 case MIMEXML:402 data := chooseData(config.XMLData, config.Data)403 c.XML(code, data)404405 default:406 c.Fail(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server"))407 }408}409410func (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]419420 } 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}431432func (c *Context) SetAccepted(formats ...string) {433 c.accepted = formats434}
modified:deprecated.go+1 added-1 removed
39 unmodified lines
40func (engine *Engine) LoadHTMLTemplates(pattern string) {41 engine.LoadHTMLGlob(pattern)42}4344// DEPRECATED. Use NotFound() instead44// DEPRECATED. Use NoRoute() instead45func (engine *Engine) NotFound404(handlers ...HandlerFunc) {46 engine.NoRoute(handlers...)47}
modified:gin_test.go+4 added-5 removed
106 unmodified lines
107 // 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}115116// TestSingleRouteOK tests that POST route is correctly invoked.
27 unmodified lines
144 w := PerformRequest(r, "GET", filePath)145146 // 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 lines
166167 // 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 lines
modified:gin.go+46 added-165 removed
3 unmodified lines
45package gin67import (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)1516const (
8 unmodified lines
2526type (27 HandlerFunc func(*Context)2831 // 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 }3929 // 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)4051func (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}6541// Returns a new blank Engine instance without any middleware attached.42// The most basic configuration43func 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 lines
65 return engine66}6768func (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}7778func (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 lines
9394// Adds handlers for NoRoute. It return a 404 code by default.95func (engine *Engine) NoRoute(handlers ...HandlerFunc) {96 engine.noRoute = handlers115 engine.finalNoRoute = engine.combineHandlers(engine.noRoute)97 engine.rebuild404Handlers()98}99100func (engine *Engine) Use(middlewares ...HandlerFunc) {101 engine.RouterGroup.Use(middlewares...)120 engine.finalNoRoute = engine.combineHandlers(engine.noRoute)102 engine.rebuild404Handlers()103}104123// ServeHTTP makes the router implement the http.Handler interface.124func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {125 engine.router.ServeHTTP(w, req)105func (engine *Engine) rebuild404Handlers() {106 engine.allNoRoute = engine.combineHandlers(engine.noRoute)107}108128func (engine *Engine) Run(addr string) {129 if gin_mode == debugCode {130 fmt.Println("[GIN-debug] Listening and serving HTTP on " + addr)109func (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}123137func (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.125func (engine *Engine) ServeHTTP(writer http.ResponseWriter, request *http.Request) {126 engine.router.ServeHTTP(writer, request)127}128146/************************************/147/********** ROUTES GROUPING *********/148/************************************/149150// Adds middlewares to the group, see example code in github.151func (group *RouterGroup) Use(middlewares ...HandlerFunc) {152 group.Handlers = append(group.Handlers, middlewares...)153}154155// 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.157func (group *RouterGroup) Group(component string, handlers ...HandlerFunc) *RouterGroup {158 prefix := group.pathFor(component)159160 return &RouterGroup{161 Handlers: group.combineHandlers(handlers),162 parent: group,163 prefix: prefix,164 engine: group.engine,129func (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}136168func (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 + "/"137func (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}176177// 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).187func (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}202203// POST is a shortcut for router.Handle("POST", path, handle)204func (group *RouterGroup) POST(path string, handlers ...HandlerFunc) {205 group.Handle("POST", path, handlers)206}207208// GET is a shortcut for router.Handle("GET", path, handle)209func (group *RouterGroup) GET(path string, handlers ...HandlerFunc) {210 group.Handle("GET", path, handlers)211}212213// DELETE is a shortcut for router.Handle("DELETE", path, handle)214func (group *RouterGroup) DELETE(path string, handlers ...HandlerFunc) {215 group.Handle("DELETE", path, handlers)216}217218// PATCH is a shortcut for router.Handle("PATCH", path, handle)219func (group *RouterGroup) PATCH(path string, handlers ...HandlerFunc) {220 group.Handle("PATCH", path, handlers)221}222223// PUT is a shortcut for router.Handle("PUT", path, handle)224func (group *RouterGroup) PUT(path string, handlers ...HandlerFunc) {225 group.Handle("PUT", path, handlers)226}227228// OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle)229func (group *RouterGroup) OPTIONS(path string, handlers ...HandlerFunc) {230 group.Handle("OPTIONS", path, handlers)231}232233// HEAD is a shortcut for router.Handle("HEAD", path, handle)234func (group *RouterGroup) HEAD(path string, handlers ...HandlerFunc) {235 group.Handle("HEAD", path, handlers)236}237238// 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")244func (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}255256func (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 lines
9 "os"10 "time"11)1213var (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)2324func ErrorLogger() HandlerFunc {25 return ErrorLoggerT(ErrorTypeAll)26}27
8 unmodified lines
36 }37 }38}3929var (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)3640func Logger() HandlerFunc {41 stdlogger := log.New(os.Stdout, "", 0)42 //errlogger := log.New(os.Stderr, "", 0)43
3 unmodified lines
4748 // Process request49 c.Next()5048 // 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 }5859 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)5455 clientIP := c.ClientIP()56 method := c.Request.Method57 statusCode := c.Writer.Status()58 statusColor := colorForStatus(statusCode)59 methodColor := colorForMethod(method)6073 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}7273func 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}8586func 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 lines
45package gin67import (8 "fmt"9 "os"10)1112const GIN_MODE = "GIN_MODE"
9 unmodified lines
22 testCode = iota23)2425var gin_mode int = debugCode26var mode_name string = DebugMode2728func init() {29 value := os.Getenv(GIN_MODE)30 if len(value) == 0 {31 SetMode(DebugMode)32 } else {33 SetMode(value)34 }35}3637func SetMode(value string) {38 switch value {39 case DebugMode:40 gin_mode = debugCode
1 unmodified line
42 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}5039func init() {40 value := os.Getenv(GIN_MODE)41 if len(value) == 0 {42 SetMode(DebugMode)43 } else {44 SetMode(value)51func Mode() string {52 return mode_name53}5455func IsDebugging() bool {56 return gin_mode == debugCode57}5859func 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 line
23[![GoDoc](https://godoc.org/github.com/gin-gonic/gin?status.svg)](https://godoc.org/github.com/gin-gonic/gin)4[![Build Status](https://travis-ci.org/gin-gonic/gin.svg)](https://travis-ci.org/gin-gonic/gin)56Gin 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![Gin console logger](http://gin-gonic.github.io/gin/other/console.png)6Gin 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. 78![Gin console logger](https://gin-gonic.github.io/gin/other/console.png)910```11$ cat test.go12```13```go14package main1516import "github.com/gin-gonic/gin"1718func 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```3536##Gin is new, will it be supported?3738Yes, 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 lines
50- [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 integration56575859## Start using it33Obviously, you need to have Git and Go! already installed to run Gin. 60Obviously, you need to have Git and Go already installed to run Gin. 61Run this in your terminal6263```64go get github.com/gin-gonic/gin65```39Then import it in your Go! code:66Then import it in your Go code:6768```69import "github.com/gin-gonic/gin"70```
178 unmodified lines
249func main() {250 r := gin.Default()251252 // 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 LoginJSON255256 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 lines
260 c.JSON(401, gin.H{"status": "unauthorized"})261 }262 })263237 // 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 LoginForm267268 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 lines
283```go284func main() {285 r := gin.Default()286260 // 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 lines
312 r.Run(":8080")313}314```315316####Serving static files317318Use Engine.ServeFiles(path string, root http.FileSystem):319320```go321func main() {322 r := gin.Default()323 r.Static("/assets", "./assets")324325 // Listen and server on 0.0.0.0:8080326 r.Run(":8080")327}328```329330Note: this will use `httpNotFound` instead of the Router's `NotFound` handler.331332####Serving static files333334Use Engine.ServeFiles(path string, root http.FileSystem):335
15 unmodified lines
351352```go353func 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 line
361 // Listen and server on 0.0.0.0:8080362 r.Run(":8080")363}364```365```html366<h1>367 {{ .title }}368</h1>369```370371You can also use your own html template render372373```go
1 unmodified line
375376func main() {377 r := gin.Default()378 html := template.Must(template.ParseFiles("file1", "file2"))332 r.HTMLTemplates = html379 r.SetHTMLTemplate(html)380381 // Listen and server on 0.0.0.0:8080382 r.Run(":8080")383}
75 unmodified lines
459 // /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 lines
modified:recovery_test.go+1 added-1 removed
37 unmodified lines
38 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 })4546 // RUN
10 unmodified lines
modified:response_writer.go+19 added-8 removed
10 unmodified lines
11 "net"12 "net/http"13)1415const (16 NoWritten = -117)1819type (20 ResponseWriter interface {21 http.ResponseWriter22 http.Hijacker23 http.Flusher24 http.CloseNotifier2526 Status() int27 Size() int28 Written() bool29 WriteHeaderNow()30 }3132 responseWriter struct {33 http.ResponseWriter29 status int30 written bool34 status int35 size int36 }37)3839func (w *responseWriter) reset(writer http.ResponseWriter) {40 w.ResponseWriter = writer41 w.status = 20037 w.written = false42 w.size = NoWritten43}4445func (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}5354func (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}6061func (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}6768func (w *responseWriter) Status() int {69 return w.status70}7172func (w *responseWriter) Size() int {73 return w.size74}7576func (w *responseWriter) Written() bool {66 return w.written77 return w.size != NoWritten78}7980// Implements the http.Hijacker interface81func (w *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
19 unmodified lines
added: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.45package gin67import (8 "github.com/julienschmidt/httprouter"9 "net/http"10 "path"11)1213// Used internally to configure router, a RouterGroup is associated with a prefix14// and an array of handlers (middlewares)15type RouterGroup struct {16 Handlers []HandlerFunc17 absolutePath string18 engine *Engine19}2021// Adds middlewares to the group, see example code in github.22func (group *RouterGroup) Use(middlewares ...HandlerFunc) {23 group.Handlers = append(group.Handlers, middlewares...)24}2526// 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.28func (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}3536// 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).46func (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 }5455 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}6263// POST is a shortcut for router.Handle("POST", path, handle)64func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) {65 group.Handle("POST", relativePath, handlers)66}6768// GET is a shortcut for router.Handle("GET", path, handle)69func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) {70 group.Handle("GET", relativePath, handlers)71}7273// DELETE is a shortcut for router.Handle("DELETE", path, handle)74func (group *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) {75 group.Handle("DELETE", relativePath, handlers)76}7778// PATCH is a shortcut for router.Handle("PATCH", path, handle)79func (group *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc) {80 group.Handle("PATCH", relativePath, handlers)81}8283// PUT is a shortcut for router.Handle("PUT", path, handle)84func (group *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) {85 group.Handle("PUT", relativePath, handlers)86}8788// OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle)89func (group *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc) {90 group.Handle("OPTIONS", relativePath, handlers)91}9293// HEAD is a shortcut for router.Handle("HEAD", path, handle)94func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) {95 group.Handle("HEAD", relativePath, handlers)96}9798// LINK is a shortcut for router.Handle("LINK", path, handle)99func (group *RouterGroup) LINK(relativePath string, handlers ...HandlerFunc) {100 group.Handle("LINK", relativePath, handlers)101}102103// UNLINK is a shortcut for router.Handle("UNLINK", path, handle)104func (group *RouterGroup) UNLINK(relativePath string, handlers ...HandlerFunc) {105 group.Handle("UNLINK", relativePath, handlers)106}107108// 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")114func (group *RouterGroup) Static(relativePath, root string) {115 absolutePath := group.calculateAbsolutePath(relativePath)116 handler := group.createStaticHandler(absolutePath, root)117 absolutePath = path.Join(absolutePath, "/*filepath")118119 // Register GET and HEAD handlers120 group.GET(absolutePath, handler)121 group.HEAD(absolutePath, handler)122}123124func (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}130131func (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}137138func (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 lines
7import (8 "encoding/xml"9 "reflect"10 "runtime"11 "strings"12)1314type H map[string]interface{}15
21 unmodified lines
37 return nil38}3940func 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}4849func 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}5859func 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}7172func 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}7948func funcName(f interface{}) string {80func nameOfFunction(f interface{}) string {81 return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()82}