From 9e930b9bdd5a29bac38fb491ffac4e7ea84b825d Mon Sep 17 00:00:00 2001 From: Javier Provecho Fernandez Date: Fri, 15 Apr 2016 01:16:46 +0200 Subject: [PATCH] lint code --- README.md | 2 +- binding/protobuf.go | 4 +-- binding/validate_test.go | 52 ++++++++++++++--------------- context.go | 6 ++-- context_test.go | 4 +-- errors.go | 4 +-- examples/realtime-advanced/stats.go | 6 ++-- gin.go | 8 ++--- ginS/gins.go | 14 ++++---- gin_test.go | 14 ++++---- githubapi_test.go | 2 +- logger.go | 4 +-- mode.go | 9 +++-- render/html.go | 3 +- tree.go | 4 ++- tree_test.go | 2 +- utils.go | 7 ++-- 17 files changed, 72 insertions(+), 73 deletions(-) diff --git a/README.md b/README.md index 9cfba236..99a6d0bf 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ [![Build Status](https://travis-ci.org/gin-gonic/gin.svg)](https://travis-ci.org/gin-gonic/gin) [![Coverage Status](https://coveralls.io/repos/gin-gonic/gin/badge.svg?branch=master)](https://coveralls.io/r/gin-gonic/gin?branch=master) -[![Go Report Card](https://goreportcard.com/badge/github.com/gin-gonic/gin)] +[![Go Report Card](https://goreportcard.com/badge/github.com/gin-gonic/gin)](https://goreportcard.com/report/github.com/gin-gonic/gin) [![GoDoc](https://godoc.org/github.com/gin-gonic/gin?status.svg)](https://godoc.org/github.com/gin-gonic/gin) [![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) diff --git a/binding/protobuf.go b/binding/protobuf.go index d6bef029..9f956228 100644 --- a/binding/protobuf.go +++ b/binding/protobuf.go @@ -13,11 +13,11 @@ import ( type protobufBinding struct{} -func (_ protobufBinding) Name() string { +func (protobufBinding) Name() string { return "protobuf" } -func (_ protobufBinding) Bind(req *http.Request, obj interface{}) error { +func (protobufBinding) Bind(req *http.Request, obj interface{}) error { buf, err := ioutil.ReadAll(req.Body) if err != nil { diff --git a/binding/validate_test.go b/binding/validate_test.go index faccaa3f..cbcb389d 100644 --- a/binding/validate_test.go +++ b/binding/validate_test.go @@ -16,15 +16,15 @@ type testInterface interface { String() string } -type substruct_noValidation struct { - I_String string - I_Int int +type substructNoValidation struct { + IString string + IInt int } -type mapNoValidationSub map[string]substruct_noValidation +type mapNoValidationSub map[string]substructNoValidation -type struct_noValidation_values struct { - substruct_noValidation +type structNoValidationValues struct { + substructNoValidation Boolean bool @@ -46,7 +46,7 @@ type struct_noValidation_values struct { Date time.Time - Struct substruct_noValidation + Struct substructNoValidation InlinedStruct struct { String []string Integer int @@ -54,8 +54,8 @@ type struct_noValidation_values struct { IntSlice []int IntPointerSlice []*int - StructPointerSlice []*substruct_noValidation - StructSlice []substruct_noValidation + StructPointerSlice []*substructNoValidation + StructSlice []substructNoValidation InterfaceSlice []testInterface UniversalInterface interface{} @@ -65,9 +65,9 @@ type struct_noValidation_values struct { StructMap mapNoValidationSub } -func createNoValidation_values() struct_noValidation_values { +func createNoValidationValues() structNoValidationValues { integer := 1 - s := struct_noValidation_values{ + s := structNoValidationValues{ Boolean: true, Uinteger: 1 << 29, Integer: -10000, @@ -84,33 +84,33 @@ func createNoValidation_values() struct_noValidation_values { String: "text", Date: time.Time{}, CustomInterface: &bytes.Buffer{}, - Struct: substruct_noValidation{}, + Struct: substructNoValidation{}, IntSlice: []int{-3, -2, 1, 0, 1, 2, 3}, IntPointerSlice: []*int{&integer}, - StructSlice: []substruct_noValidation{}, + StructSlice: []substructNoValidation{}, UniversalInterface: 1.2, FloatMap: map[string]float32{ "foo": 1.23, "bar": 232.323, }, StructMap: mapNoValidationSub{ - "foo": substruct_noValidation{}, - "bar": substruct_noValidation{}, + "foo": substructNoValidation{}, + "bar": substructNoValidation{}, }, // StructPointerSlice []noValidationSub // InterfaceSlice []testInterface } s.InlinedStruct.Integer = 1000 s.InlinedStruct.String = []string{"first", "second"} - s.I_String = "substring" - s.I_Int = 987654 + s.IString = "substring" + s.IInt = 987654 return s } func TestValidateNoValidationValues(t *testing.T) { - origin := createNoValidation_values() - test := createNoValidation_values() - empty := struct_noValidation_values{} + origin := createNoValidationValues() + test := createNoValidationValues() + empty := structNoValidationValues{} assert.Nil(t, validate(test)) assert.Nil(t, validate(&test)) @@ -120,8 +120,8 @@ func TestValidateNoValidationValues(t *testing.T) { assert.Equal(t, origin, test) } -type struct_noValidation_pointer struct { - substruct_noValidation +type structNoValidationPointer struct { + substructNoValidation Boolean bool @@ -143,12 +143,12 @@ type struct_noValidation_pointer struct { Date *time.Time - Struct *substruct_noValidation + Struct *substructNoValidation IntSlice *[]int IntPointerSlice *[]*int - StructPointerSlice *[]*substruct_noValidation - StructSlice *[]substruct_noValidation + StructPointerSlice *[]*substructNoValidation + StructSlice *[]substructNoValidation InterfaceSlice *[]testInterface FloatMap *map[string]float32 @@ -158,7 +158,7 @@ type struct_noValidation_pointer struct { func TestValidateNoValidationPointers(t *testing.T) { //origin := createNoValidation_values() //test := createNoValidation_values() - empty := struct_noValidation_pointer{} + empty := structNoValidationPointer{} //assert.Nil(t, validate(test)) //assert.Nil(t, validate(&test)) diff --git a/context.go b/context.go index 7b4676f6..5d3b6a4e 100644 --- a/context.go +++ b/context.go @@ -69,7 +69,7 @@ func (c *Context) reset() { // Copy returns a copy of the current context that can be safely used outside the request's scope. // This have to be used then the context has to be passed to a goroutine. func (c *Context) Copy() *Context { - var cp Context = *c + var cp = *c cp.writermem.ResponseWriter = nil cp.Writer = &cp.writermem cp.index = abortIndex @@ -172,7 +172,7 @@ func (c *Context) Get(key string) (value interface{}, exists bool) { return } -// Returns the value for the given key if it exists, otherwise it panics. +// MustGet returns the value for the given key if it exists, otherwise it panics. func (c *Context) MustGet(key string) interface{} { if value, exists := c.Get(key); exists { return value @@ -244,7 +244,7 @@ func (c *Context) PostForm(key string) string { return value } -// PostForm returns the specified key from a POST urlencoded form or multipart form +// DefaultPostForm returns the specified key from a POST urlencoded form or multipart form // when it exists, otherwise it returns the specified defaultValue string. // See: PostForm() and GetPostForm() for further information. func (c *Context) DefaultPostForm(key, defaultValue string) string { diff --git a/context_test.go b/context_test.go index a13b5412..97d4957c 100644 --- a/context_test.go +++ b/context_test.go @@ -262,14 +262,14 @@ func TestContextPostFormMultipart(t *testing.T) { Bar string `form:"bar"` BarAsInt int `form:"bar"` Array []string `form:"array"` - Id string `form:"id"` + ID string `form:"id"` } assert.NoError(t, c.Bind(&obj)) assert.Equal(t, obj.Foo, "bar") assert.Equal(t, obj.Bar, "10") assert.Equal(t, obj.BarAsInt, 10) assert.Equal(t, obj.Array, []string{"first", "second"}) - assert.Equal(t, obj.Id, "") + assert.Equal(t, obj.ID, "") value, ok := c.GetQuery("foo") assert.False(t, ok) diff --git a/errors.go b/errors.go index bced19aa..7716bfae 100644 --- a/errors.go +++ b/errors.go @@ -66,7 +66,7 @@ func (msg *Error) JSON() interface{} { return json } -// Implements the json.Marshaller interface +// MarshalJSON implements the json.Marshaller interface func (msg *Error) MarshalJSON() ([]byte, error) { return json.Marshal(msg.JSON()) } @@ -89,7 +89,7 @@ func (a errorMsgs) ByType(typ ErrorType) errorMsgs { if typ == ErrorTypeAny { return a } - var result errorMsgs = nil + var result errorMsgs for _, msg := range a { if msg.IsType(typ) { result = append(result, msg) diff --git a/examples/realtime-advanced/stats.go b/examples/realtime-advanced/stats.go index c36ecc78..554ab86a 100644 --- a/examples/realtime-advanced/stats.go +++ b/examples/realtime-advanced/stats.go @@ -16,9 +16,9 @@ var savedStats map[string]uint64 func statsWorker() { c := time.Tick(1 * time.Second) - var lastMallocs uint64 = 0 - var lastFrees uint64 = 0 - for _ = range c { + var lastMallocs uint64 + var lastFrees uint64 + for range c { var stats runtime.MemStats runtime.ReadMemStats(&stats) diff --git a/gin.go b/gin.go index fb1df9cd..60f4ab29 100644 --- a/gin.go +++ b/gin.go @@ -14,7 +14,7 @@ import ( "github.com/gin-gonic/gin/render" ) -// Framework's version +// Version is Framework's version const Version = "v1.0rc2" var default404Body = []byte("404 page not found") @@ -147,19 +147,19 @@ func (engine *Engine) SetHTMLTemplate(templ *template.Template) { engine.HTMLRender = render.HTMLProduction{Template: templ} } -// Adds handlers for NoRoute. It return a 404 code by default. +// NoRoute adds handlers for NoRoute. It return a 404 code by default. func (engine *Engine) NoRoute(handlers ...HandlerFunc) { engine.noRoute = handlers engine.rebuild404Handlers() } -// Sets the handlers called when... TODO +// NoMethod sets the handlers called when... TODO func (engine *Engine) NoMethod(handlers ...HandlerFunc) { engine.noMethod = handlers engine.rebuild405Handlers() } -// Attachs a global middleware to the router. ie. the middleware attached though Use() will be +// Use attachs a global middleware to the router. ie. the middleware attached though Use() will be // included in the handlers chain for every single request. Even 404, 405, static files... // For example, this is the right place for a logger or error management middleware. func (engine *Engine) Use(middleware ...HandlerFunc) IRoutes { diff --git a/ginS/gins.go b/ginS/gins.go index 71744702..d40d1c3a 100644 --- a/ginS/gins.go +++ b/ginS/gins.go @@ -34,17 +34,17 @@ func SetHTMLTemplate(templ *template.Template) { engine().SetHTMLTemplate(templ) } -// Adds handlers for NoRoute. It return a 404 code by default. +// NoRoute adds handlers for NoRoute. It return a 404 code by default. func NoRoute(handlers ...HandlerFunc) { engine().NoRoute(handlers...) } -// Sets the handlers called when... TODO +// NoMethod sets the handlers called when... TODO func NoMethod(handlers ...HandlerFunc) { engine().NoMethod(handlers...) } -// Creates a new router group. You should add all the routes that have common middlwares or the same path prefix. +// Group creates a new router group. You should add all the routes that have common middlwares or the same path prefix. // For example, all the routes that use a common middlware for authorization could be grouped. func Group(relativePath string, handlers ...HandlerFunc) *RouterGroup { return engine().Group(relativePath, handlers...) @@ -111,28 +111,28 @@ func StaticFS(relativePath string, fs http.FileSystem) IRoutes { return engine().StaticFS(relativePath, fs) } -// Attachs a global middleware to the router. ie. the middlewares attached though Use() will be +// Use attachs a global middleware to the router. ie. the middlewares attached though Use() will be // included in the handlers chain for every single request. Even 404, 405, static files... // For example, this is the right place for a logger or error management middleware. func Use(middlewares ...HandlerFunc) IRoutes { return engine().Use(middlewares...) } -// The router is attached to a http.Server and starts listening and serving HTTP requests. +// Run : The router is attached to a http.Server and starts listening and serving HTTP requests. // It is a shortcut for http.ListenAndServe(addr, router) // Note: this method will block the calling goroutine undefinitelly unless an error happens. func Run(addr ...string) (err error) { return engine().Run(addr...) } -// The router is attached to a http.Server and starts listening and serving HTTPS requests. +// RunTLS : The router is attached to a http.Server and starts listening and serving HTTPS requests. // It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, router) // Note: this method will block the calling goroutine undefinitelly unless an error happens. func RunTLS(addr string, certFile string, keyFile string) (err error) { return engine().RunTLS(addr, certFile, keyFile) } -// The router is attached to a http.Server and starts listening and serving HTTP requests +// RunUnix : The router is attached to a http.Server and starts listening and serving HTTP requests // through the specified unix socket (ie. a file) // Note: this method will block the calling goroutine undefinitelly unless an error happens. func RunUnix(file string) (err error) { diff --git a/gin_test.go b/gin_test.go index af95ab84..eda4ffe1 100644 --- a/gin_test.go +++ b/gin_test.go @@ -201,13 +201,13 @@ func compareFunc(t *testing.T, a, b interface{}) { func TestListOfRoutes(t *testing.T) { router := New() - router.GET("/favicon.ico", handler_test1) - router.GET("/", handler_test1) + router.GET("/favicon.ico", handlerTest1) + router.GET("/", handlerTest1) group := router.Group("/users") { - group.GET("/", handler_test2) - group.GET("/:id", handler_test1) - group.POST("/:id", handler_test2) + group.GET("/", handlerTest2) + group.GET("/:id", handlerTest1) + group.POST("/:id", handlerTest2) } router.Static("/static", ".") @@ -251,5 +251,5 @@ func assertRoutePresent(t *testing.T, gotRoutes RoutesInfo, wantRoute RouteInfo) t.Errorf("route not found: %v", wantRoute) } -func handler_test1(c *Context) {} -func handler_test2(c *Context) {} +func handlerTest1(c *Context) {} +func handlerTest2(c *Context) {} diff --git a/githubapi_test.go b/githubapi_test.go index 2227fa6a..75f2de93 100644 --- a/githubapi_test.go +++ b/githubapi_test.go @@ -341,7 +341,7 @@ func exampleFromPath(path string) (string, Params) { if start >= 0 { value := fmt.Sprint(rand.Intn(100000)) params = append(params, Param{ - Key: path[start:len(path)], + Key: path[start:], Value: value, }) output.WriteString(value) diff --git a/logger.go b/logger.go index a1776a99..d56bc628 100644 --- a/logger.go +++ b/logger.go @@ -35,13 +35,13 @@ func ErrorLoggerT(typ ErrorType) HandlerFunc { } } -// Instances a Logger middleware that will write the logs to gin.DefaultWriter +// Logger instances a Logger middleware that will write the logs to gin.DefaultWriter // By default gin.DefaultWriter = os.Stdout func Logger() HandlerFunc { return LoggerWithWriter(DefaultWriter) } -// Instance a Logger middleware with the specified writter buffer. +// LoggerWithWriter instance a Logger middleware with the specified writter buffer. // Example: os.Stdout, a file opened in write mode, a socket... func LoggerWithWriter(out io.Writer, notlogged ...string) HandlerFunc { var skip map[string]struct{} diff --git a/mode.go b/mode.go index bf9e995b..fcb8f8fa 100644 --- a/mode.go +++ b/mode.go @@ -5,7 +5,6 @@ package gin import ( - "io" "os" "github.com/gin-gonic/gin/binding" @@ -31,11 +30,11 @@ const ( // To support coloring in Windows use: // import "github.com/mattn/go-colorable" // gin.DefaultWriter = colorable.NewColorableStdout() -var DefaultWriter io.Writer = os.Stdout -var DefaultErrorWriter io.Writer = os.Stderr +var DefaultWriter = os.Stdout +var DefaultErrorWriter = os.Stderr -var ginMode int = debugCode -var modeName string = DebugMode +var ginMode = debugCode +var modeName = DebugMode func init() { mode := os.Getenv(ENV_GIN_MODE) diff --git a/render/html.go b/render/html.go index 01f6bf22..8bfb23ac 100644 --- a/render/html.go +++ b/render/html.go @@ -61,7 +61,6 @@ func (r HTML) Render(w http.ResponseWriter) error { writeContentType(w, htmlContentType) if len(r.Name) == 0 { return r.Template.Execute(w, r.Data) - } else { - return r.Template.ExecuteTemplate(w, r.Name, r.Data) } + return r.Template.ExecuteTemplate(w, r.Name, r.Data) } diff --git a/tree.go b/tree.go index 4f2082ee..4f1da271 100644 --- a/tree.go +++ b/tree.go @@ -20,7 +20,7 @@ type Param struct { // It is therefore safe to read values by the index. type Params []Param -// ByName returns the value of the first Param which key matches the given name. +// Get returns the value of the first Param which key matches the given name. // If no matching Param is found, an empty string is returned. func (ps Params) Get(name string) (string, bool) { for _, entry := range ps { @@ -31,6 +31,8 @@ func (ps Params) Get(name string) (string, bool) { return "", false } +// ByName returns the value of the first Param which key matches the given name. +// If no matching Param is found, an empty string is returned. func (ps Params) ByName(name string) (va string) { va, _ = ps.Get(name) return diff --git a/tree_test.go b/tree_test.go index 04dacdc5..ed21783c 100644 --- a/tree_test.go +++ b/tree_test.go @@ -21,7 +21,7 @@ func printChildren(n *node, prefix string) { } } -// Used as a workaround since we can't compare functions or their adresses +// Used as a workaround since we can't compare functions or their addressses var fakeHandlerValue string func fakeHandler(val string) HandlersChain { diff --git a/utils.go b/utils.go index 2814791f..18064fb5 100644 --- a/utils.go +++ b/utils.go @@ -47,7 +47,7 @@ func WrapH(h http.Handler) HandlerFunc { type H map[string]interface{} -// Allows type H to be used with xml.Marshal +// MarshalXML allows type H to be used with xml.Marshal func (h H) MarshalXML(e *xml.Encoder, start xml.StartElement) error { start.Name = xml.Name{ Space: "", @@ -143,10 +143,9 @@ func resolveAddress(addr []string) string { if port := os.Getenv("PORT"); len(port) > 0 { debugPrint("Environment variable PORT=\"%s\"", port) return ":" + port - } else { - debugPrint("Environment variable PORT is undefined. Using port :8080 by default") - return ":8080" } + debugPrint("Environment variable PORT is undefined. Using port :8080 by default") + return ":8080" case 1: return addr[0] default: