Skip to content
Myr

Merge branch 'develop' | v0.5 release

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 50e7e42, 2b85363 · Browse files · 13 files+402 added−64 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

13 files+402 added−64 removed

  • other:+402 added−64 removed

13 files+402 added−64 removed

modified:binding/binding.go+82 added-14 removed
23 unmodified lines
2425 // XML binding26 xmlBinding struct{}2728 // // form binding28 // form binding29 formBinding struct{}3031 // multipart form binding32 multipartFormBinding struct{}33)3435const MAX_MEMORY = 1 * 1024 * 10243637var (33 JSON = jsonBinding{}34 XML = xmlBinding{}35 Form = formBinding{} // todo38 JSON = jsonBinding{}39 XML = xmlBinding{}40 Form = formBinding{} // todo41 MultipartForm = multipartFormBinding{}42)4344func (_ jsonBinding) Bind(req *http.Request, obj interface{}) error {45 decoder := json.NewDecoder(req.Body)
22 unmodified lines
68 }69 return Validate(obj)70}7172func (_ multipartFormBinding) Bind(req *http.Request, obj interface{}) error {73 if err := req.ParseMultipartForm(MAX_MEMORY); err != nil {74 return err75 }76 if err := mapForm(obj, req.Form); err != nil {77 return err78 }79 return Validate(obj)80}8182func mapForm(ptr interface{}, form map[string][]string) error {83 typ := reflect.TypeOf(ptr).Elem()84 formStruct := reflect.ValueOf(ptr).Elem()85 for i := 0; i < typ.NumField(); i++ {
27 unmodified lines
113 }114 return nil115}116117func setIntField(val string, bitSize int, structField reflect.Value) error {118 if val == "" {119 val = "0"120 }121122 intVal, err := strconv.ParseInt(val, 10, bitSize)123 if err == nil {124 structField.SetInt(intVal)125 }126127 return err128}129130func setUintField(val string, bitSize int, structField reflect.Value) error {131 if val == "" {132 val = "0"133 }134135 uintVal, err := strconv.ParseUint(val, 10, bitSize)136 if err == nil {137 structField.SetUint(uintVal)138 }139140 return err141}142143func setWithProperType(valueKind reflect.Kind, val string, structField reflect.Value) error {144 switch valueKind {103 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:104 if val == "" {105 val = "0"106 }107 intVal, err := strconv.Atoi(val)108 if err != nil {109 return err110 } else {111 structField.SetInt(int64(intVal))112 }145 case reflect.Int:146 return setIntField(val, 0, structField)147 case reflect.Int8:148 return setIntField(val, 8, structField)149 case reflect.Int16:150 return setIntField(val, 16, structField)151 case reflect.Int32:152 return setIntField(val, 32, structField)153 case reflect.Int64:154 return setIntField(val, 64, structField)155 case reflect.Uint:156 return setUintField(val, 0, structField)157 case reflect.Uint8:158 return setUintField(val, 8, structField)159 case reflect.Uint16:160 return setUintField(val, 16, structField)161 case reflect.Uint32:162 return setUintField(val, 32, structField)163 case reflect.Uint64:164 return setUintField(val, 64, structField)165 case reflect.Bool:166 if val == "" {167 val = "false"168 }
81 unmodified lines
250 if err != nil {251 return err252 }253 }254 } else {255 fieldType := field.Type.Kind()256 if fieldType == reflect.Struct {257 if reflect.DeepEqual(zero, fieldValue) {258 continue259 }260 err := Validate(fieldValue, field.Name)261 if err != nil {262 return err263 }264 } else if fieldType == reflect.Slice && field.Type.Elem().Kind() == reflect.Struct {265 err := Validate(fieldValue, field.Name)266 if err != nil {267 return err268 }269 }270 }271 }272 case reflect.Slice:273 for i := 0; i < val.Len(); i++ {
11 unmodified lines
modified:Godeps/Godeps.json+1 added-1 removed
modified:render/render.go+17 added
24 unmodified lines
2526 // Plain text27 plainRender struct{}2829 // HTML Plain text30 htmlPlainRender struct{}3132 // Redirects33 redirectRender struct{}3435 // Redirects
11 unmodified lines
47var (48 JSON = jsonRender{}49 XML = xmlRender{}50 Plain = plainRender{}51 HTMLPlain = htmlPlainRender{}52 Redirect = redirectRender{}53 HTMLDebug = &htmlDebugRender{}54)55
32 unmodified lines
88 }89 return err90}9192func (_ htmlPlainRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {93 writeHeader(w, code, "text/html")94 format := data[0].(string)95 args := data[1].([]interface{})96 var err error97 if len(args) > 0 {98 _, err = w.Write([]byte(fmt.Sprintf(format, args...)))99 } else {100 _, err = w.Write([]byte(format))101 }102 return err103}104105func (r *htmlDebugRender) AddGlob(pattern string) {106 r.globs = append(r.globs, pattern)107}108
32 unmodified lines
modified:auth_test.go+24 added
57 unmodified lines
58 if w.HeaderMap.Get("WWW-Authenticate") != "Basic realm=\"Authorization Required\"" {59 t.Errorf("WWW-Authenticate header is incorrect: %s", w.HeaderMap.Get("Content-Type"))60 }61}6263func TestBasicAuth401WithCustomRealm(t *testing.T) {64 req, _ := http.NewRequest("GET", "/login", nil)65 w := httptest.NewRecorder()6667 r := New()68 accounts := Accounts{"foo": "bar"}69 r.Use(BasicAuthForRealm(accounts, "My Custom Realm"))7071 r.GET("/login", func(c *Context) {72 c.String(200, "autorized")73 })7475 req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("admin:password")))76 r.ServeHTTP(w, req)7778 if w.Code != 401 {79 t.Errorf("Response code should be Not autorized, was: %s", w.Code)80 }8182 if w.HeaderMap.Get("WWW-Authenticate") != "Basic realm=\"My Custom Realm\"" {83 t.Errorf("WWW-Authenticate header is incorrect: %s", w.HeaderMap.Get("Content-Type"))84 }85}
modified:auth.go+15 added-4 removed
6 unmodified lines
7import (8 "crypto/subtle"9 "encoding/base64"10 "errors"11 "fmt"12 "sort"13)1415const (
12 unmodified lines
28func (a authPairs) Len() int { return len(a) }29func (a authPairs) Swap(i, j int) { a[i], a[j] = a[j], a[i] }30func (a authPairs) Less(i, j int) bool { return a[i].Value < a[j].Value }3131// 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 {32// Implements a basic Basic HTTP Authorization. It takes as arguments a map[string]string where33// the key is the user name and the value is the password, as well as the name of the Realm34// (see http://tools.ietf.org/html/rfc2617#section-1.2)35func BasicAuthForRealm(accounts Accounts, realm string) HandlerFunc {36 pairs, err := processAccounts(accounts)37 if err != nil {38 panic(err)39 }
1 unmodified line
41 // Search user in the slice of allowed credentials42 user, ok := searchCredential(pairs, c.Request.Header.Get("Authorization"))43 if !ok {44 // Credentials doesn't match, we return 401 Unauthorized and abort request.45 if realm == "" {46 realm = "Authorization Required"47 }43 c.Writer.Header().Set("WWW-Authenticate", "Basic realm=\"Authorization Required\"")48 c.Writer.Header().Set("WWW-Authenticate", fmt.Sprintf("Basic realm=\"%s\"", realm))49 c.Fail(401, errors.New("Unauthorized"))50 } else {51 // user is allowed, set UserId to key "user" in this context, the userId can be read later using52 // c.Get(gin.AuthUserKey)
1 unmodified line
54 }55 }56}5758// Implements a basic Basic HTTP Authorization. It takes as argument a map[string]string where59// the key is the user name and the value is the password.60func BasicAuth(accounts Accounts) HandlerFunc {61 return BasicAuthForRealm(accounts, "")62}6364func processAccounts(accounts Accounts) (authPairs, error) {65 if len(accounts) == 0 {66 return nil, errors.New("Empty list of authorized credentials")67 }
38 unmodified lines
modified:AUTHORS.md+56 added
7 unmodified lines
8**Long-term Maintainer:** Javier Provecho (@javierprovecho)910People and companies, who have contributed, in alphabetical order.1112**@858806258 (杰哥)**13- Fix typo in example141516**@achedeuzot (Klemen Sever)**17- Fix newline debug printing1819
4 unmodified lines
24**@AlexanderChen1989 (Alexander)**25- Typos in README262728**@alexanderdidenko (Aleksandr Didenko)**29- Add support multipart/form-data303132**@alexandernyquist (Alexander Nyquist)**33- Using template.Must to fix multiple return issue34- ★ Added support for OPTIONS verb35- ★ Setting response headers before calling WriteHeader
26 unmodified lines
62- Typos in README63- Add example about serving static files646566**@donileo (Adonis)**67- Add NoMethod handler686970**@dutchcoders (DutchCoders)**71- ★ Fix security bug that allows client to spoof ip72- Fix typo. r.HTMLTemplates -> SetHTMLTemplate737475**@el3ctro- (Joshua Loper)**76- Fix typo in example777879**@ethankan (Ethan Kan)**80- Unsigned integers in binding818283**(Evgeny Persienko)**84- Validate sub structures858687**@frankbille (Frank Bille)**88- Add support for HTTP Realm Auth899091**@fmd (Fareed Dudhia)**92- Fix typo. SetHTTPTemplate -> SetHTMLTemplate939495**@ironiridis (Christopher Harrington)**96- Remove old reference979899**@jammie-stackhouse (Jamie Stackhouse)**100- Add more shortcuts for router methods101102
32 unmodified lines
135**@lucas-clemente (Lucas Clemente)**136- ★ work around path.Join removing trailing slashes from routes137138139**@mattn (Yasuhiro Matsumoto)**140- Improve color logger141142143**@mdigger (Dmitry Sedykh)**144- Fixes Form binding when content-type is x-www-form-urlencoded145- No repeat call c.Writer.Status() in gin.Logger146- Fixes Content-Type for json render
26 unmodified lines
173**@r8k (Rajiv Kilaparti)**174- Fix Port usage in README.175176177**@rayrod2030 (Ray Rodriguez)**178- Fix typo in example179180181**@rns**182- Fix typo in example183184185**@RobAWilkinson (Robert Wilkinson)**186- Add example of forms and params187188189**@rogierlommers (Rogier Lommers)**190- Add updated static serve example191192193**@se77en (Damon Zhao)**194- Improve color logging195196
16 unmodified lines
213**@superalsrk (SRK.Lyu)**214- Update httprouter godeps215216217**@tebeka (Miki Tebeka)**218- Use net/http constants instead of numeric values219220221**@techjanitor**222- Update context.go reserved IPs223224225**@yosssi (Keiji Yoshida)**226- Fix link in README227228
2 unmodified lines
modified:CHANGELOG.md+8 added-1 removed
modified:context_test.go+36 added
439 unmodified lines
440 t.Errorf("Content-Type should not be application/json, was %s", w.HeaderMap.Get("Content-Type"))441 }442}443444func TestBindingForm(t *testing.T) {445446 body := bytes.NewBuffer([]byte("foo=bar&num=123&unum=1234567890"))447448 r := New()449 r.POST("/binding/form", func(c *Context) {450 var body struct {451 Foo string `form:"foo"`452 Num int `form:"num"`453 Unum uint `form:"unum"`454 }455 if c.Bind(&body) {456 c.JSON(200, H{"foo": body.Foo, "num": body.Num, "unum": body.Unum})457 }458 })459460 req, _ := http.NewRequest("POST", "/binding/form", body)461 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")462 w := httptest.NewRecorder()463464 r.ServeHTTP(w, req)465466 if w.Code != 200 {467 t.Errorf("Response code should be Ok, was: %d", w.Code)468 }469470 expected := "{\"foo\":\"bar\",\"num\":123,\"unum\":1234567890}\n"471 if w.Body.String() != expected {472 t.Errorf("Response should be %s, was %s", expected, w.Body.String())473 }474475 if w.HeaderMap.Get("Content-Type") != "application/json; charset=utf-8" {476 t.Errorf("Content-Type should be application/json, was %s", w.HeaderMap.Get("Content-Type"))477 }478}479480func TestClientIP(t *testing.T) {481 r := New()482483 var clientIP string = ""
36 unmodified lines
modified:context.go+8 added-1 removed
228 unmodified lines
229// 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"}233 var reservedLocalIps = []string{"10.0.0.0/8", "127.0.0.1/32", "172.16.0.0/12", "192.168.0.0/16"}234235 proxies = make([]interface{}, len(reservedLocalIps))236237 for i, v := range reservedLocalIps {
56 unmodified lines
294 ctype := filterFlags(c.Request.Header.Get("Content-Type"))295 switch {296 case c.Request.Method == "GET" || ctype == MIMEPOSTForm:297 b = binding.Form298 case ctype == MIMEMultipartPOSTForm:299 b = binding.MultipartForm300 case ctype == MIMEJSON:301 b = binding.JSON302 case ctype == MIMEXML || ctype == MIMEXML2:303 b = binding.XML
46 unmodified lines
350func (c *Context) String(code int, format string, values ...interface{}) {351 c.Render(code, render.Plain, format, values)352}353354// Writes the given string into the response body and sets the Content-Type to "text/html" without template.355func (c *Context) HTMLString(code int, format string, values ...interface{}) {356 c.Render(code, render.HTMLPlain, format, values)357}358359// Returns a HTTP redirect to the specific location.360func (c *Context) Redirect(code int, location string) {361 if code >= 300 && code <= 308 {362 c.Render(code, render.Redirect, location)
79 unmodified lines
modified:gin.go+45 added-15 removed
12 unmodified lines
13 "sync"14)1516const (17 AbortIndex = math.MaxInt8 / 218 MIMEJSON = "application/json"19 MIMEHTML = "text/html"20 MIMEXML = "application/xml"21 MIMEXML2 = "text/xml"22 MIMEPlain = "text/plain"23 MIMEPOSTForm = "application/x-www-form-urlencoded"17 AbortIndex = math.MaxInt8 / 218 MIMEJSON = "application/json"19 MIMEHTML = "text/html"20 MIMEXML = "application/xml"21 MIMEXML2 = "text/xml"22 MIMEPlain = "text/plain"23 MIMEPOSTForm = "application/x-www-form-urlencoded"24 MIMEMultipartPOSTForm = "multipart/form-data"25)2627type (28 HandlerFunc func(*Context)2930 // Represents the web framework, it wraps the blazing fast httprouter multiplexer and a list of global middlewares.31 Engine struct {32 *RouterGroup32 HTMLRender render.Render33 Default404Body []byte34 pool sync.Pool35 allNoRoute []HandlerFunc36 noRoute []HandlerFunc37 router *httprouter.Router33 HTMLRender render.Render34 Default404Body []byte35 Default405Body []byte36 pool sync.Pool37 allNoRouteNoMethod []HandlerFunc38 noRoute []HandlerFunc39 noMethod []HandlerFunc40 router *httprouter.Router41 }42)4344// Returns a new blank Engine instance without any middleware attached.
6 unmodified lines
51 engine: engine,52 }53 engine.router = httprouter.New()54 engine.Default404Body = []byte("404 page not found")55 engine.Default405Body = []byte("405 method not allowed")56 engine.router.NotFound = engine.handle40457 engine.router.MethodNotAllowed = engine.handle40558 engine.pool.New = func() interface{} {59 c := &Context{Engine: engine}60 c.Writer = &c.writermem61 return c
39 unmodified lines
101 engine.noRoute = handlers102 engine.rebuild404Handlers()103}104105func (engine *Engine) NoMethod(handlers ...HandlerFunc) {106 engine.noMethod = handlers107 engine.rebuild405Handlers()108}109110func (engine *Engine) Use(middlewares ...HandlerFunc) {111 engine.RouterGroup.Use(middlewares...)112 engine.rebuild404Handlers()113 engine.rebuild405Handlers()114}115116func (engine *Engine) rebuild404Handlers() {106 engine.allNoRoute = engine.combineHandlers(engine.noRoute)117 engine.allNoRouteNoMethod = engine.combineHandlers(engine.noRoute)118}119120func (engine *Engine) rebuild405Handlers() {121 engine.allNoRouteNoMethod = engine.combineHandlers(engine.noMethod)122}123124func (engine *Engine) handle404(w http.ResponseWriter, req *http.Request) {110 c := engine.createContext(w, req, nil, engine.allNoRoute)125 c := engine.createContext(w, req, nil, engine.allNoRouteNoMethod)126 // set 404 by default, useful for logging127 c.Writer.WriteHeader(404)128 c.Next()129 if !c.Writer.Written() {
5 unmodified lines
135 }136 engine.reuseContext(c)137}138139func (engine *Engine) handle405(w http.ResponseWriter, req *http.Request) {140 c := engine.createContext(w, req, nil, engine.allNoRouteNoMethod)141 // set 405 by default, useful for logging142 c.Writer.WriteHeader(405)143 c.Next()144 if !c.Writer.Written() {145 if c.Writer.Status() == 405 {146 c.Data(-1, MIMEPlain, engine.Default405Body)147 } else {148 c.Writer.WriteHeaderNow()149 }150 }151 engine.reuseContext(c)152}153154// ServeHTTP makes the router implement the http.Handler interface.155func (engine *Engine) ServeHTTP(writer http.ResponseWriter, request *http.Request) {156 engine.router.ServeHTTP(writer, request)157}
16 unmodified lines
modified:logger.go+2 added-2 removed
3 unmodified lines
45package gin67import (8 "github.com/mattn/go-colorable"9 "log"9 "os"10 "time"11)1213var (
23 unmodified lines
37 }38}3940func Logger() HandlerFunc {41 stdlogger := log.New(os.Stdout, "", 0)41 stdlogger := log.New(colorable.NewColorableStdout(), "", 0)42 //errlogger := log.New(os.Stderr, "", 0)4344 return func(c *Context) {45 // Start timer
60 unmodified lines
modified:README.md+107 added-25 removed
1#Gin Web Framework [![GoDoc](https://godoc.org/github.com/gin-gonic/gin?status.svg)](https://godoc.org/github.com/gin-gonic/gin) [![Build Status](https://travis-ci.org/gin-gonic/gin.svg)](https://travis-ci.org/gin-gonic/gin)23[![Join the chat at https://gitter.im/gin-gonic/gin](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/gin-gonic/gin?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)45Gin 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. 67![Gin console logger](https://gin-gonic.github.io/gin/other/console.png)8
2 unmodified lines
11```12```go13package main1415import (16 "net/http"13import "github.com/gin-gonic/gin"17 "github.com/gin-gonic/gin"18)1920func main() {21 router := gin.Default()22 router.GET("/", func(c *gin.Context) {18 c.String(200, "hello world")23 c.String(http.StatusOK, "hello world")24 })25 router.GET("/ping", func(c *gin.Context) {21 c.String(200, "pong")26 c.String(http.StatusOK, "pong")27 })28 router.POST("/submit", func(c *gin.Context) {24 c.String(401, "not authorized")29 c.String(http.StatusUnauthorized, "not authorized")30 })31 router.PUT("/error", func(c *gin.Context) {27 c.String(500, "and error hapenned :(")32 c.String(http.StatusInternalServerError, "and error happened :(")33 })34 router.Run(":8080")35}36```
52 unmodified lines
89#### Create most basic PING/PONG HTTP endpoint90```go 91package main9293import (94 "net/http"88import "github.com/gin-gonic/gin"95 "github.com/gin-gonic/gin"96)9798func main() {99 r := gin.Default()100 r.GET("/ping", func(c *gin.Context) {93 c.String(200, "pong")101 c.String(http.StatusOK, "pong")102 })10396 // Listen and server on 0.0.0.0:8080104 // Listen and serve on 0.0.0.0:8080105 r.Run(":8080")106}107```108
26 unmodified lines
135 // This handler will match /user/john but will not match neither /user/ or /user136 r.GET("/user/:name", func(c *gin.Context) {137 name := c.Params.ByName("name")138 message := "Hello "+name131 c.String(200, message)139 c.String(http.StatusOK, message)140 })141142 // However, this one will match /user/john/ and also /user/john/send143 // If no other routers match /user/john, it will redirect to /user/join/144 r.GET("/user/:name/*action", func(c *gin.Context) {145 name := c.Params.ByName("name")146 action := c.Params.ByName("action")147 message := name + " is " + action140 c.String(200, message)148 c.String(http.StatusOK, message)149 })150 151 // Listen and server on 0.0.0.0:8080152 r.Run(":8080")
9 unmodified lines
162 // You need to call ParseForm() on the request to receive url and form params first163 c.Request.ParseForm()164 165 firstname := c.Request.Form.Get("firstname")158 lastname := c.Request.Form.get("lastname")166 lastname := c.Request.Form.Get("lastname")167168 message := "Hello "+ firstname + lastname161 c.String(200, message)169 c.String(http.StatusOK, message)170 })171 r.Run(":8080")172}173```174175###Multipart Form176```go177package main178179import (180 "github.com/gin-gonic/gin"181 "github.com/gin-gonic/gin/binding"182)183184type LoginForm struct {185 User string `form:"user" binding:"required"`186 Password string `form:"password" binding:"required"`187}188189func main() {190191 r := gin.Default()192193 r.POST("/login", func(c *gin.Context) {194195 var form LoginForm196 c.BindWith(&form, binding.MultipartForm)197198 if form.User == "user" && form.Password == "password" {199 c.JSON(200, gin.H{"status": "you are logged in"})200 } else {201 c.JSON(401, gin.H{"status": "unauthorized"})202 }203204 })205206 r.Run(":8080")207208}209```210211Test it with:212```bash213$ curl -v --form user=user --form password=password http://localhost:8080/login214```215216#### Grouping routes217```go218func main() {219 r := gin.Default()
100 unmodified lines
320 var json LoginJSON321322 c.Bind(&json) // This will infer what binder to use depending on the content-type header.323 if json.User == "manu" && json.Password == "123" {275 c.JSON(200, gin.H{"status": "you are logged in"})324 c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})325 } else {277 c.JSON(401, gin.H{"status": "unauthorized"})326 c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})327 }328 })329330 // Example for binding a HTML form (user=manu&password=123)
1 unmodified line
332 var form LoginForm333334 c.BindWith(&form, binding.Form) // You can also specify which binder to use. We support binding.Form, binding.JSON and binding.XML.335 if form.User == "manu" && form.Password == "123" {287 c.JSON(200, gin.H{"status": "you are logged in"})336 c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})337 } else {289 c.JSON(401, gin.H{"status": "unauthorized"})338 c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})339 }340 })341342 // Listen and server on 0.0.0.0:8080
8 unmodified lines
351 r := gin.Default()352353 // gin.H is a shortcut for map[string]interface{}354 r.GET("/someJSON", func(c *gin.Context) {306 c.JSON(200, gin.H{"message": "hey", "status": 200})355 c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})356 })357358 r.GET("/moreJSON", func(c *gin.Context) {359 // You also can use a struct
6 unmodified lines
366 msg.Message = "hey"367 msg.Number = 123368 // Note that msg.Name becomes "user" in the JSON369 // Will output : {"user": "Lena", "Message": "hey", "Number": 123}321 c.JSON(200, msg)370 c.JSON(http.StatusOK, msg)371 })372373 r.GET("/someXML", func(c *gin.Context) {325 c.XML(200, gin.H{"message": "hey", "status": 200})374 c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})375 })376377 // Listen and server on 0.0.0.0:8080378 r.Run(":8080")379}380```381382####Serving static files334383Use Engine.ServeFiles(path string, root http.FileSystem):384385```go386func main() {
4 unmodified lines
391 r.Run(":8080")392}393```394395Use the following example to serve static files at top level route of your domain. Files are being served from directory ./html.396397```398r := gin.Default()399r.Use(static.Serve("/", static.LocalFile("html", false)))400```401402Note: this will use `httpNotFound` instead of the Router's `NotFound` handler.403404####HTML rendering405
4 unmodified lines
410 r := gin.Default()411 r.LoadHTMLGlob("templates/*")412 r.GET("/index", func(c *gin.Context) {413 obj := gin.H{"title": "Main website"}359 c.HTML(200, "index.tmpl", obj)414 c.HTML(http.StatusOK, "index.tmpl", obj)415 })416417 // Listen and server on 0.0.0.0:8080418 r.Run(":8080")
19 unmodified lines
438 r.Run(":8080")439}440```441442#####Using layout files with templates443```go444var baseTemplate = "main.tmpl"445446r.GET("/", func(c *gin.Context) {447 r.SetHTMLTemplate(template.Must(template.ParseFiles(baseTemplate, "whatever.tmpl")))448 c.HTML(200, "base", data)449})450```451main.tmpl452```html453{{define "base"}}454<html>455 <head></head>456 <body>457 {{template "content" .}}458 </body>459</html>460{{end}}461```462whatever.tmpl463```html464{{define "content"}}465<h1>Hello World!</h1>466{{end}}467```468469#### Redirects470471Issuing a HTTP redirect is easy:472473```go474r.GET("/test", func(c *gin.Context) {393 c.Redirect(301, "http://www.google.com/")475 c.Redirect(http.StatusMovedPermanently, "http://www.google.com/")476})477```478Both internal and external locations are supported.479
39 unmodified lines
519```520521#### Using BasicAuth() middleware522```go441// similate some private data523// simulate some private data524var secrets = gin.H{525 "foo": gin.H{"email": "foo@bar.com", "phone": "123433"},526 "austin": gin.H{"email": "austin@example.com", "phone": "666"},527 "lena": gin.H{"email": "lena@guapa.com", "phone": "523443"},
16 unmodified lines
544 authorized.GET("/secrets", func(c *gin.Context) {545 // get user, it was setted by the BasicAuth middleware546 user := c.MustGet(gin.AuthUserKey).(string)547 if secret, ok := secrets[user]; ok {466 c.JSON(200, gin.H{"user": user, "secret": secret})548 c.JSON(http.StatusOK, gin.H{"user": user, "secret": secret})549 } else {468 c.JSON(200, gin.H{"user": user, "secret": "NO SECRET :("})550 c.JSON(http.StatusOK, gin.H{"user": user, "secret": "NO SECRET :("})551 }552 })553554 // Listen and server on 0.0.0.0:8080
64 unmodified lines
modified:recovery.go+1 added-1 removed
80 unmodified lines
81 return name82}8384// Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.85// While Martini is in development mode, Recovery will also output the panic as HTML.85// While Gin is in development mode, Recovery will also output the panic as HTML.86func Recovery() HandlerFunc {87 return func(c *Context) {88 defer func() {89 if err := recover(); err != nil {
9 unmodified lines