diff --git a/_benchmarks/iris-mvc-templates/controllers/home_controller.go b/_benchmarks/iris-mvc-templates/controllers/home_controller.go index b97c60fe..575c3a36 100644 --- a/_benchmarks/iris-mvc-templates/controllers/home_controller.go +++ b/_benchmarks/iris-mvc-templates/controllers/home_controller.go @@ -13,7 +13,8 @@ func (c *HomeController) GetAbout() mvc.Result { Name: "about.html", Data: map[string]interface{}{ "Title": "About Page", - "Message": "Your application description page."}, + "Message": "Your application description page.", + }, } } @@ -22,6 +23,7 @@ func (c *HomeController) GetContact() mvc.Result { Name: "contact.html", Data: map[string]interface{}{ "Title": "Contact Page", - "Message": "Your application description page."}, + "Message": "Your application description page.", + }, } } diff --git a/_examples/authentication/oauth2/main.go b/_examples/authentication/oauth2/main.go index 562a2a12..e14824de 100644 --- a/_examples/authentication/oauth2/main.go +++ b/_examples/authentication/oauth2/main.go @@ -179,7 +179,6 @@ var SetState = func(ctx iris.Context) string { } return "state" - } // GetState gets the state returned by the provider during the callback. @@ -273,14 +272,14 @@ func main() { yammer.New(os.Getenv("YAMMER_KEY"), os.Getenv("YAMMER_SECRET"), "http://localhost:3000/auth/yammer/callback"), onedrive.New(os.Getenv("ONEDRIVE_KEY"), os.Getenv("ONEDRIVE_SECRET"), "http://localhost:3000/auth/onedrive/callback"), - //Pointed localhost.com to http://localhost:3000/auth/yahoo/callback through proxy as yahoo + // Pointed localhost.com to http://localhost:3000/auth/yahoo/callback through proxy as yahoo // does not allow to put custom ports in redirection uri yahoo.New(os.Getenv("YAHOO_KEY"), os.Getenv("YAHOO_SECRET"), "http://localhost.com"), slack.New(os.Getenv("SLACK_KEY"), os.Getenv("SLACK_SECRET"), "http://localhost:3000/auth/slack/callback"), stripe.New(os.Getenv("STRIPE_KEY"), os.Getenv("STRIPE_SECRET"), "http://localhost:3000/auth/stripe/callback"), wepay.New(os.Getenv("WEPAY_KEY"), os.Getenv("WEPAY_SECRET"), "http://localhost:3000/auth/wepay/callback", "view_user"), - //By default paypal production auth urls will be used, please set PAYPAL_ENV=sandbox as environment variable for testing - //in sandbox environment + // By default paypal production auth urls will be used, please set PAYPAL_ENV=sandbox as environment variable for testing + // in sandbox environment paypal.New(os.Getenv("PAYPAL_KEY"), os.Getenv("PAYPAL_SECRET"), "http://localhost:3000/auth/paypal/callback"), steam.New(os.Getenv("STEAM_KEY"), "http://localhost:3000/auth/steam/callback"), heroku.New(os.Getenv("HEROKU_KEY"), os.Getenv("HEROKU_SECRET"), "http://localhost:3000/auth/heroku/callback"), @@ -292,7 +291,7 @@ func main() { discord.New(os.Getenv("DISCORD_KEY"), os.Getenv("DISCORD_SECRET"), "http://localhost:3000/auth/discord/callback", discord.ScopeIdentify, discord.ScopeEmail), meetup.New(os.Getenv("MEETUP_KEY"), os.Getenv("MEETUP_SECRET"), "http://localhost:3000/auth/meetup/callback"), - //Auth0 allocates domain per customer, a domain must be provided for auth0 to work + // Auth0 allocates domain per customer, a domain must be provided for auth0 to work auth0.New(os.Getenv("AUTH0_KEY"), os.Getenv("AUTH0_SECRET"), "http://localhost:3000/auth/auth0/callback", os.Getenv("AUTH0_DOMAIN")), xero.New(os.Getenv("XERO_KEY"), os.Getenv("XERO_SECRET"), "http://localhost:3000/auth/xero/callback"), ) @@ -363,7 +362,6 @@ func main() { // start of the router app.Get("/auth/{provider}/callback", func(ctx iris.Context) { - user, err := CompleteUserAuth(ctx) if err != nil { ctx.StatusCode(iris.StatusInternalServerError) @@ -394,7 +392,6 @@ func main() { }) app.Get("/", func(ctx iris.Context) { - ctx.ViewData("", providerIndex) if err := ctx.View("index.html"); err != nil { diff --git a/_examples/experimental-handlers/casbin/wrapper/main_test.go b/_examples/experimental-handlers/casbin/wrapper/main_test.go index 48a4a0b7..d69ec42e 100644 --- a/_examples/experimental-handlers/casbin/wrapper/main_test.go +++ b/_examples/experimental-handlers/casbin/wrapper/main_test.go @@ -71,7 +71,6 @@ func TestCasbinWrapper(t *testing.T) { for _, tt := range ttAdminDeleted { check(e, tt.method, tt.path, tt.username, tt.status) } - } func check(e *httptest.Expect, method, path, username string, status int) { diff --git a/_examples/file-server/basic/main_test.go b/_examples/file-server/basic/main_test.go index d0aaef82..0d1c485e 100644 --- a/_examples/file-server/basic/main_test.go +++ b/_examples/file-server/basic/main_test.go @@ -57,7 +57,7 @@ func (r resource) loadFromBase(dir string) string { } func TestFileServerBasic(t *testing.T) { - var urls = []resource{ + urls := []resource{ "/static/css/main.css", "/static/js/jquery-2.1.1.js", "/static/favicon.ico", diff --git a/_examples/hero/basic/main.go b/_examples/hero/basic/main.go index 90015ed3..e027faf4 100644 --- a/_examples/hero/basic/main.go +++ b/_examples/hero/basic/main.go @@ -6,7 +6,6 @@ import ( ) func main() { - app := iris.New() // 1 diff --git a/_examples/http-listening/listen-addr/omit-server-errors/main_test.go b/_examples/http-listening/listen-addr/omit-server-errors/main_test.go index a1915419..8aa74580 100644 --- a/_examples/http-listening/listen-addr/omit-server-errors/main_test.go +++ b/_examples/http-listening/listen-addr/omit-server-errors/main_test.go @@ -45,7 +45,6 @@ func TestListenAddr(t *testing.T) { if got := log.String(); !strings.Contains(got, expectedMessage) { t.Fatalf("expecting to log to contains the:\n'%s'\ninstead of:\n'%s'", expectedMessage, got) } - } func TestListenAddrWithoutServerErr(t *testing.T) { diff --git a/_examples/http_request/read-json-struct-validation/main.go b/_examples/http_request/read-json-struct-validation/main.go index 16dab511..d75b75e1 100644 --- a/_examples/http_request/read-json-struct-validation/main.go +++ b/_examples/http_request/read-json-struct-validation/main.go @@ -131,7 +131,6 @@ func main() { // hooks right into validator and you can combine with validation tags and still have a // common error output format. func UserStructLevelValidation(sl validator.StructLevel) { - user := sl.Current().Interface().(User) if len(user.FirstName) == 0 && len(user.LastName) == 0 { diff --git a/_examples/http_request/read-json/main.go b/_examples/http_request/read-json/main.go index 88f84407..2d4748e4 100644 --- a/_examples/http_request/read-json/main.go +++ b/_examples/http_request/read-json/main.go @@ -32,7 +32,6 @@ type Person struct { func MyHandler2(ctx iris.Context) { var persons []Person err := ctx.ReadJSON(&persons) - if err != nil { ctx.StatusCode(iris.StatusBadRequest) ctx.WriteString(err.Error()) diff --git a/_examples/http_request/read-many/main.go b/_examples/http_request/read-many/main.go index b8d8cbf8..f18f0bf9 100644 --- a/_examples/http_request/read-many/main.go +++ b/_examples/http_request/read-many/main.go @@ -20,7 +20,6 @@ func main() { ctx.WriteString(`The body was empty or iris.WithoutBodyConsumptionOnUnmarshal option is missing from app.Run. Check the terminal window for any queries logs.`) - } else { ctx.WriteString("OK body is still:\n") ctx.Write(body) diff --git a/_examples/http_request/request-logger/main.go b/_examples/http_request/request-logger/main.go index 888de7a6..812f3b71 100644 --- a/_examples/http_request/request-logger/main.go +++ b/_examples/http_request/request-logger/main.go @@ -20,7 +20,7 @@ func main() { // Query appends the url query to the Path. Query: true, - //Columns: true, + // Columns: true, // if !empty then its contents derives from `ctx.Values().Get("logger_message") // will be added to the logs. @@ -62,5 +62,4 @@ func main() { // http://lcoalhost:8080/notfoundhere // see the output on the console. app.Run(iris.Addr(":8080"), iris.WithoutServerError(iris.ErrServerClosed)) - } diff --git a/_examples/http_request/upload-file/main.go b/_examples/http_request/upload-file/main.go index bc6cf50d..e57aa9f9 100644 --- a/_examples/http_request/upload-file/main.go +++ b/_examples/http_request/upload-file/main.go @@ -113,7 +113,6 @@ func main() { // assuming that you have a folder named 'uploads' out, err := os.OpenFile("./uploads/"+fname, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { ctx.StatusCode(iris.StatusInternalServerError) ctx.HTML("Error while uploading: " + err.Error() + "") diff --git a/_examples/http_request/upload-files/main.go b/_examples/http_request/upload-files/main.go index d73bdd23..55cab74b 100644 --- a/_examples/http_request/upload-files/main.go +++ b/_examples/http_request/upload-files/main.go @@ -84,7 +84,6 @@ func saveUploadedFile(fh *multipart.FileHeader, destDirectory string) (int64, er out, err := os.OpenFile(filepath.Join(destDirectory, fh.Filename), os.O_WRONLY|os.O_CREATE, os.FileMode(0666)) - if err != nil { return 0, err } diff --git a/_examples/http_responsewriter/content-negotiation/main_test.go b/_examples/http_responsewriter/content-negotiation/main_test.go index 0c69a092..eb4a12b7 100644 --- a/_examples/http_responsewriter/content-negotiation/main_test.go +++ b/_examples/http_responsewriter/content-negotiation/main_test.go @@ -74,5 +74,4 @@ func TestContentNegotiation(t *testing.T) { if expected, got := expectedHTMLResponse, string(rawResponse); expected != got { t.Fatalf("expected response to be:\n%s but got:\n%s", expected, got) } - } diff --git a/_examples/http_responsewriter/herotemplate/app.go b/_examples/http_responsewriter/herotemplate/app.go index f948f71d..f840aa69 100644 --- a/_examples/http_responsewriter/herotemplate/app.go +++ b/_examples/http_responsewriter/herotemplate/app.go @@ -14,14 +14,13 @@ import ( // Read more at https://github.com/shiyanhui/hero/hero func main() { - app := iris.New() app.Get("/users", func(ctx iris.Context) { ctx.Gzip(true) ctx.ContentType("text/html") - var userList = []string{ + userList := []string{ "Alice", "Bob", "Tom", diff --git a/_examples/http_responsewriter/herotemplate/template/userlist.html.go b/_examples/http_responsewriter/herotemplate/template/userlist.html.go index ebf6fcf1..d8d62324 100644 --- a/_examples/http_responsewriter/herotemplate/template/userlist.html.go +++ b/_examples/http_responsewriter/herotemplate/template/userlist.html.go @@ -37,5 +37,4 @@ func UserList(userList []string, buffer *bytes.Buffer) { `) - } diff --git a/_examples/http_responsewriter/herotemplate/template/userlistwriter.html.go b/_examples/http_responsewriter/herotemplate/template/userlistwriter.html.go index 114bffa9..f6df2ed5 100644 --- a/_examples/http_responsewriter/herotemplate/template/userlistwriter.html.go +++ b/_examples/http_responsewriter/herotemplate/template/userlistwriter.html.go @@ -40,5 +40,4 @@ func UserListToWriter(userList []string, w io.Writer) (int, error) { `) return w.Write(_buffer.Bytes()) - } diff --git a/_examples/http_responsewriter/sse-third-party/main.go b/_examples/http_responsewriter/sse-third-party/main.go index 8be45764..93c61032 100644 --- a/_examples/http_responsewriter/sse-third-party/main.go +++ b/_examples/http_responsewriter/sse-third-party/main.go @@ -42,7 +42,6 @@ func main() { s.Publish("messages", &sse.Event{ Data: []byte("third message"), }) - }() // ... app.Run(iris.Addr(":8080"), iris.WithoutServerError(iris.ErrServerClosed)) diff --git a/_examples/miscellaneous/i18n/main.go b/_examples/miscellaneous/i18n/main.go index ef103723..fa4735ab 100644 --- a/_examples/miscellaneous/i18n/main.go +++ b/_examples/miscellaneous/i18n/main.go @@ -14,11 +14,12 @@ func newApp() *iris.Application { Languages: map[string]string{ "en-US": "./locales/locale_en-US.ini", "el-GR": "./locales/locale_el-GR.ini", - "zh-CN": "./locales/locale_zh-CN.ini"}}) + "zh-CN": "./locales/locale_zh-CN.ini", + }, + }) app.Use(globalLocale) app.Get("/", func(ctx iris.Context) { - // it tries to find the language by: // ctx.Values().GetString("language") // if that was empty then @@ -47,7 +48,9 @@ func newApp() *iris.Application { URLParameter: "lang", Languages: map[string]string{ "en-US": "./locales/locale_multi_first_en-US.ini, ./locales/locale_multi_second_en-US.ini", - "el-GR": "./locales/locale_multi_first_el-GR.ini, ./locales/locale_multi_second_el-GR.ini"}}) + "el-GR": "./locales/locale_multi_first_el-GR.ini, ./locales/locale_multi_second_el-GR.ini", + }, + }) app.Get("/multi", multiLocale, func(ctx iris.Context) { language := ctx.Values().GetString(ctx.Application().ConfigurationReadOnly().GetTranslateLanguageContextKey()) diff --git a/_examples/miscellaneous/i18n/main_test.go b/_examples/miscellaneous/i18n/main_test.go index 2594c2fa..1fecbc79 100644 --- a/_examples/miscellaneous/i18n/main_test.go +++ b/_examples/miscellaneous/i18n/main_test.go @@ -45,5 +45,4 @@ func TestI18n(t *testing.T) { Body().Equal(elgrMulti) e.GET("/multi").WithQueryString("lang=en-US").Expect().Status(httptest.StatusOK). Body().Equal(enusMulti) - } diff --git a/_examples/mvc/login/web/controllers/user_controller.go b/_examples/mvc/login/web/controllers/user_controller.go index ea4e6377..7ab13c0d 100644 --- a/_examples/mvc/login/web/controllers/user_controller.go +++ b/_examples/mvc/login/web/controllers/user_controller.go @@ -96,7 +96,6 @@ func (c *UserController) PostRegister() mvc.Result { // but it's good to know you can set a custom code; // Code: 303, } - } var loginStaticView = mvc.View{ diff --git a/_examples/routing/basic/main.go b/_examples/routing/basic/main.go index 9bb530d9..8e5e2ab5 100644 --- a/_examples/routing/basic/main.go +++ b/_examples/routing/basic/main.go @@ -71,7 +71,6 @@ func newApp() *iris.Application { // Pssst, don't forget dynamic-path example for more "magic"! app.Get("/api/users/{userid:uint64 min(1)}", func(ctx iris.Context) { userID, err := ctx.Params().GetUint64("userid") - if err != nil { ctx.Writef("error while trying to parse userid parameter," + "this will never happen if :uint64 is being used because if it's not a valid uint64 it will fire Not Found automatically.") diff --git a/_examples/routing/basic/main_test.go b/_examples/routing/basic/main_test.go index 0f1b98cd..6825fbea 100644 --- a/_examples/routing/basic/main_test.go +++ b/_examples/routing/basic/main_test.go @@ -85,5 +85,4 @@ func TestRoutingBasic(t *testing.T) { e.Request("GET", "/").WithURL("http://any-subdomain-here.example.com").Expect().Status(httptest.StatusOK). Body().Equal(expectedSubdomainWildcardIndexResponse) - } diff --git a/_examples/routing/custom-wrapper/main.go b/_examples/routing/custom-wrapper/main.go index ea8bfae4..68ccf30c 100644 --- a/_examples/routing/custom-wrapper/main.go +++ b/_examples/routing/custom-wrapper/main.go @@ -11,7 +11,6 @@ import ( // You can use the .WrapRouter to add custom logic when or when not the router should // be executed in order to execute the registered routes' handlers. func newApp() *iris.Application { - app := iris.New() app.OnErrorCode(iris.StatusNotFound, func(ctx iris.Context) { diff --git a/_examples/routing/main_test.go b/_examples/routing/main_test.go index e588ea85..4fd2c4a1 100644 --- a/_examples/routing/main_test.go +++ b/_examples/routing/main_test.go @@ -75,7 +75,7 @@ func TestRouting(t *testing.T) { app := newApp() e := httptest.New(t, app) - var tests = []troute{ + tests := []troute{ // GET newTroute("GET", "", "/healthcheck", httptest.StatusOK), newTroute("GET", "", "/games/{gameID}/clans", httptest.StatusOK, "gameID", "42"), diff --git a/_examples/routing/reverse/main.go b/_examples/routing/reverse/main.go index 1ab53c11..23287534 100644 --- a/_examples/routing/reverse/main.go +++ b/_examples/routing/reverse/main.go @@ -36,5 +36,4 @@ func main() { // See view/template_html_4 example for more reverse routing examples // using the reverse router component and the {{url}} and {{urlpath}} template functions. app.Run(iris.Addr(":8080")) - } diff --git a/_examples/routing/route-state/main.go b/_examples/routing/route-state/main.go index 58058598..542af9ee 100644 --- a/_examples/routing/route-state/main.go +++ b/_examples/routing/route-state/main.go @@ -16,7 +16,6 @@ func main() { }) app.Get("/change", func(ctx iris.Context) { - if none.IsOnline() { none.Method = iris.MethodNone } else { diff --git a/_examples/sessions/database/badger/main.go b/_examples/sessions/database/badger/main.go index fb5a9646..52212d15 100644 --- a/_examples/sessions/database/badger/main.go +++ b/_examples/sessions/database/badger/main.go @@ -41,10 +41,10 @@ func main() { }) app.Get("/set", func(ctx iris.Context) { s := sess.Start(ctx) - //set session values + // set session values s.Set("name", "iris") - //test if set here + // test if set here ctx.Writef("All ok session value of the 'name' is: %s", s.GetString("name")) }) @@ -83,7 +83,7 @@ func main() { }) app.Get("/destroy", func(ctx iris.Context) { - //destroy, removes the entire session data and cookie + // destroy, removes the entire session data and cookie sess.Destroy(ctx) }) diff --git a/_examples/sessions/database/boltdb/main.go b/_examples/sessions/database/boltdb/main.go index 721be3ae..c2310c2e 100644 --- a/_examples/sessions/database/boltdb/main.go +++ b/_examples/sessions/database/boltdb/main.go @@ -42,10 +42,10 @@ func main() { }) app.Get("/set", func(ctx iris.Context) { s := sess.Start(ctx) - //set session values + // set session values s.Set("name", "iris") - //test if set here + // test if set here ctx.Writef("All ok session value of the 'name' is: %s", s.GetString("name")) }) @@ -84,7 +84,7 @@ func main() { }) app.Get("/destroy", func(ctx iris.Context) { - //destroy, removes the entire session data and cookie + // destroy, removes the entire session data and cookie sess.Destroy(ctx) }) diff --git a/_examples/sessions/database/redis/main.go b/_examples/sessions/database/redis/main.go index 76437a4f..8a9e8ca2 100644 --- a/_examples/sessions/database/redis/main.go +++ b/_examples/sessions/database/redis/main.go @@ -60,10 +60,10 @@ func main() { }) app.Get("/set", func(ctx iris.Context) { s := sess.Start(ctx) - //set session values + // set session values s.Set("name", "iris") - //test if set here + // test if set here ctx.Writef("All ok session value of the 'name' is: %s", s.GetString("name")) }) @@ -120,7 +120,7 @@ func main() { }) app.Get("/destroy", func(ctx iris.Context) { - //destroy, removes the entire session data and cookie + // destroy, removes the entire session data and cookie sess.Destroy(ctx) }) diff --git a/_examples/sessions/middleware/main.go b/_examples/sessions/middleware/main.go index 54010b47..88b070fe 100644 --- a/_examples/sessions/middleware/main.go +++ b/_examples/sessions/middleware/main.go @@ -46,12 +46,12 @@ func main() { ctx.HTML("") }) - //set session values. + // set session values. app.Get("/set", func(ctx iris.Context) { session := sessions.Get(ctx) session.Set("name", "iris") - //test if set here. + // test if set here. ctx.Writef("All ok session set to: %s", session.GetString("name")) // Set will set the value as-it-is, @@ -97,7 +97,7 @@ func main() { }) app.Get("/destroy", func(ctx iris.Context) { - //destroy, removes the entire session data and cookie + // destroy, removes the entire session data and cookie // sess.Destroy(ctx) // or sessions.Get(ctx).Destroy() @@ -123,7 +123,6 @@ func main() { // try to change it, if we used `Set` instead of `SetImmutable` this // change will affect the underline array of the session's value "businessEdit", but now it will not. businessGet[0].Name = "Gabriel" - }) app.Get("/get_immutable", func(ctx iris.Context) { diff --git a/_examples/sessions/overview/main.go b/_examples/sessions/overview/main.go index b4ee0121..8d9b4f47 100644 --- a/_examples/sessions/overview/main.go +++ b/_examples/sessions/overview/main.go @@ -12,7 +12,6 @@ var ( ) func secret(ctx iris.Context) { - // Check if user is authenticated if auth, _ := sess.Start(ctx).GetBoolean("authenticated"); !auth { ctx.StatusCode(iris.StatusForbidden) diff --git a/_examples/sessions/securecookie/main.go b/_examples/sessions/securecookie/main.go index da2a4101..61a4a814 100644 --- a/_examples/sessions/securecookie/main.go +++ b/_examples/sessions/securecookie/main.go @@ -34,12 +34,11 @@ func newApp() *iris.Application { ctx.Writef("You should navigate to the /set, /get, /delete, /clear,/destroy instead") }) app.Get("/set", func(ctx iris.Context) { - - //set session values + // set session values s := mySessions.Start(ctx) s.Set("name", "iris") - //test if set here + // test if set here ctx.Writef("All ok session set to: %s", s.GetString("name")) }) @@ -68,7 +67,7 @@ func newApp() *iris.Application { }) app.Get("/destroy", func(ctx iris.Context) { - //destroy, removes the entire session data and cookie + // destroy, removes the entire session data and cookie mySessions.Destroy(ctx) }) // Note about destroy: diff --git a/_examples/subdomains/redirect/main_test.go b/_examples/subdomains/redirect/main_test.go index 4f2a62cf..5663da86 100644 --- a/_examples/subdomains/redirect/main_test.go +++ b/_examples/subdomains/redirect/main_test.go @@ -26,5 +26,4 @@ func TestSubdomainRedirectWWW(t *testing.T) { for _, test := range tests { e.GET(test.path).Expect().Status(httptest.StatusOK).Body().Equal(test.response) } - } diff --git a/_examples/subdomains/www/main_test.go b/_examples/subdomains/www/main_test.go index ffd756cc..f38b2105 100644 --- a/_examples/subdomains/www/main_test.go +++ b/_examples/subdomains/www/main_test.go @@ -54,5 +54,4 @@ func TestSubdomainWWW(t *testing.T) { Status(httptest.StatusOK). Body().Equal(test.response()) } - } diff --git a/_examples/testing/httptest/main_test.go b/_examples/testing/httptest/main_test.go index 492826b3..579ba701 100644 --- a/_examples/testing/httptest/main_test.go +++ b/_examples/testing/httptest/main_test.go @@ -27,5 +27,4 @@ func TestNewApp(t *testing.T) { // with invalid basic auth e.GET("/admin/settings").WithBasicAuth("invalidusername", "invalidpassword"). Expect().Status(httptest.StatusUnauthorized) - } diff --git a/_examples/tutorial/api-for-apache-kafka/src/main.go b/_examples/tutorial/api-for-apache-kafka/src/main.go index 8c20df0c..0db740d2 100644 --- a/_examples/tutorial/api-for-apache-kafka/src/main.go +++ b/_examples/tutorial/api-for-apache-kafka/src/main.go @@ -375,5 +375,4 @@ func getTopicConsumeSSEHandler(ctx iris.Context) { flusher.Flush() } } - } diff --git a/_examples/tutorial/dropzonejs/src/main.go b/_examples/tutorial/dropzonejs/src/main.go index c6cc67ad..7d91282c 100644 --- a/_examples/tutorial/dropzonejs/src/main.go +++ b/_examples/tutorial/dropzonejs/src/main.go @@ -32,7 +32,6 @@ type uploadedFiles struct { } func scanUploads(dir string) *uploadedFiles { - f := new(uploadedFiles) lindex := dir[len(dir)-1] @@ -54,7 +53,6 @@ func scanUploads(dir string) *uploadedFiles { func (f *uploadedFiles) scan(dir string) { f.dir = dir filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { - // if it's directory or a thumbnail we saved earlier, skip it. if info.IsDir() || strings.HasPrefix(info.Name(), "thumbnail_") { return nil @@ -117,7 +115,6 @@ func (f *uploadedFiles) createThumbnail(uf uploadedFile) { png.Encode(out, resized) } // and so on... you got the point, this code can be simplify, as a practise. - } func main() { @@ -152,7 +149,6 @@ func main() { // assuming that you have a folder named 'uploads' out, err := os.OpenFile(uploadsDir+fname, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { ctx.StatusCode(iris.StatusInternalServerError) ctx.Application().Logger().Warnf("Error while preparing the new file: %v", err.Error()) diff --git a/_examples/tutorial/mongodb/main.go b/_examples/tutorial/mongodb/main.go index b16acacf..c008bba2 100644 --- a/_examples/tutorial/mongodb/main.go +++ b/_examples/tutorial/mongodb/main.go @@ -26,7 +26,7 @@ import ( const version = "0.0.1" func init() { - var envFileName = ".env" + envFileName := ".env" flagset := flag.CommandLine flagset.StringVar(&envFileName, "env", envFileName, "the env file which web app will use to extract its environment variables") diff --git a/_examples/tutorial/url-shortener/main.go b/_examples/tutorial/url-shortener/main.go index 7e9e488b..6a8f2b89 100644 --- a/_examples/tutorial/url-shortener/main.go +++ b/_examples/tutorial/url-shortener/main.go @@ -99,7 +99,6 @@ func newApp(db *DB) *iris.Application { ctx.ViewData("FORM_RESULT", template.HTML("
"+shortenURL+" 
")) } - } } diff --git a/_examples/tutorial/url-shortener/main_test.go b/_examples/tutorial/url-shortener/main_test.go index fa8002d5..a020894e 100644 --- a/_examples/tutorial/url-shortener/main_test.go +++ b/_examples/tutorial/url-shortener/main_test.go @@ -73,5 +73,4 @@ func TestURLShortener(t *testing.T) { } time.Sleep(1 * time.Second) - } diff --git a/_examples/tutorial/url-shortener/store.go b/_examples/tutorial/url-shortener/store.go index f2b78891..ebf5fd88 100644 --- a/_examples/tutorial/url-shortener/store.go +++ b/_examples/tutorial/url-shortener/store.go @@ -20,9 +20,7 @@ type Store interface { Close() // release the store or ignore } -var ( - tableURLs = []byte("urls") -) +var tableURLs = []byte("urls") // DB representation of a Store. // Only one table/bucket which contains the urls, so it's not a fully Database, @@ -44,7 +42,7 @@ func openDatabase(stumb string) *bolt.DB { } // create the buckets here - var tables = [...][]byte{ + tables := [...][]byte{ tableURLs, } @@ -160,7 +158,6 @@ func (d *DB) GetByValue(value string) (keys []string) { // Len returns all the "shorted" urls length func (d *DB) Len() (num int) { d.db.View(func(tx *bolt.Tx) error { - // Assume bucket exists and has keys b := tx.Bucket(tableURLs) if b == nil { diff --git a/_examples/view/overview/main.go b/_examples/view/overview/main.go index 0c3e9a27..5d6d5e26 100644 --- a/_examples/view/overview/main.go +++ b/_examples/view/overview/main.go @@ -14,11 +14,9 @@ func main() { // - {{ current }} app.RegisterView(iris.HTML("./templates", ".html")) app.Get("/", func(ctx iris.Context) { - ctx.ViewData("Name", "iris") // the .Name inside the ./templates/hi.html ctx.Gzip(true) // enable gzip for big files ctx.View("hi.html") // render the template with the file name relative to the './templates' - }) // http://localhost:8080/ diff --git a/_examples/view/template_html_3/main.go b/_examples/view/template_html_3/main.go index 82b192f3..adf98358 100644 --- a/_examples/view/template_html_3/main.go +++ b/_examples/view/template_html_3/main.go @@ -59,7 +59,6 @@ func main() { // http://localhost:8080 // http://localhost:8080/redirect/my-page1 app.Run(iris.Addr(":8080")) - } func writePathHandler(ctx iris.Context) { diff --git a/_examples/view/template_jet_0/main.go b/_examples/view/template_jet_0/main.go index c94d33c7..8ed61f05 100644 --- a/_examples/view/template_jet_0/main.go +++ b/_examples/view/template_jet_0/main.go @@ -91,7 +91,7 @@ func main() { }) app.RegisterView(tmpl) // <-- - var todos = map[string]*tTODO{ + todos := map[string]*tTODO{ "example-todo-1": {Text: "Add an show todo page to the example project", Done: true}, "example-todo-2": {Text: "Add an add todo page to the example project"}, "example-todo-3": {Text: "Add an update todo page to the example project"}, diff --git a/_examples/view/template_pug_0/main.go b/_examples/view/template_pug_0/main.go index 1d5f35e6..2f07bb5b 100644 --- a/_examples/view/template_pug_0/main.go +++ b/_examples/view/template_pug_0/main.go @@ -25,5 +25,4 @@ func index(ctx iris.Context) { // Q: why need extension .pug? // A: Because you can register more than one view engine per Iris application. ctx.View("index.pug") - } diff --git a/_examples/view/write-to/main.go b/_examples/view/write-to/main.go index 19adbe72..2ed176fa 100644 --- a/_examples/view/write-to/main.go +++ b/_examples/view/write-to/main.go @@ -34,7 +34,6 @@ func main() { RefTitle: "Iris web framework", RefLink: "https://iris-go.com", }) - if err != nil { app.Logger().Errorf("error from app.View: %v", err) } diff --git a/cache/browser_test.go b/cache/browser_test.go index 8c691df5..30f8d954 100644 --- a/cache/browser_test.go +++ b/cache/browser_test.go @@ -76,6 +76,7 @@ func TestCache304(t *testing.T) { r = e.GET("/").Expect().Status(httptest.StatusOK) r.Body().Equal("send") } + func TestETag(t *testing.T) { t.Parallel() diff --git a/cache/cache_test.go b/cache/cache_test.go index 0d731e41..6c2f8081 100644 --- a/cache/cache_test.go +++ b/cache/cache_test.go @@ -104,7 +104,6 @@ func TestClientNoCache(t *testing.T) { if err := runTest(e, "/", &n, expectedBodyStr, "/nocache"); err != nil { t.Fatalf(t.Name()+": %v", err) } - } func TestCache(t *testing.T) { @@ -136,7 +135,6 @@ func TestCache(t *testing.T) { if err := runTest(e, "/other", &n2, expectedBodyStr2, ""); err != nil { t.Fatalf(t.Name()+" other: %v", err) } - } func TestCacheHandlerParallel(t *testing.T) { @@ -185,7 +183,6 @@ func TestCacheValidator(t *testing.T) { atomic.AddUint32(&n, 1) ctx.Header("DONT", "DO not cache that response even if it was claimed") ctx.Write([]byte(expectedBodyStr)) - }) e := httptest.New(t, app) diff --git a/cache/client/handler.go b/cache/client/handler.go index 0120241c..e4a4163b 100644 --- a/cache/client/handler.go +++ b/cache/client/handler.go @@ -168,5 +168,4 @@ func (h *Handler) ServeHTTP(ctx context.Context) { // fmt.Printf("key: %s\n", key) // fmt.Printf("write content type: %s\n", response.Headers()["ContentType"]) // fmt.Printf("write body len: %d\n", len(response.Body())) - } diff --git a/cache/client/rule/chained.go b/cache/client/rule/chained.go index fc4b59e3..b448a652 100644 --- a/cache/client/rule/chained.go +++ b/cache/client/rule/chained.go @@ -36,7 +36,6 @@ func Chained(rule Rule, next ...Rule) Rule { } return c - } // Claim validator diff --git a/cache/entry/entry.go b/cache/entry/entry.go index f875323c..ed79ce64 100644 --- a/cache/entry/entry.go +++ b/cache/entry/entry.go @@ -101,7 +101,6 @@ func CopyHeaders(dst map[string][]string, src map[string][]string) { // to re-set the response with the new handler's content result func (e *Entry) Reset(statusCode int, headers map[string][]string, body []byte, lifeChanger LifeChanger) { - if e.response == nil { e.response = &Response{} } diff --git a/cache/uri/uribuilder.go b/cache/uri/uribuilder.go index 83ee3efd..f14da064 100644 --- a/cache/uri/uribuilder.go +++ b/cache/uri/uribuilder.go @@ -71,7 +71,6 @@ func (r URIBuilder) String() string { } func (r URIBuilder) build() string { - remoteURL := r.serverAddr // fasthttp appends the "/" in the last uri (with query args also, that's probably a fasthttp bug which I'll fix later) diff --git a/configuration_test.go b/configuration_test.go index 052da0eb..f120c7c5 100644 --- a/configuration_test.go +++ b/configuration_test.go @@ -223,7 +223,6 @@ Other: if expected, got := "Iris: https://github.com/kataras/iris", c.Other["MyServerName"]; expected != got { t.Fatalf("error on TestConfigurationYAML: Expected Other['MyServerName'] %s but got %s", expected, got) } - } func TestConfigurationTOML(t *testing.T) { diff --git a/context/context.go b/context/context.go index d7b25ae2..0e547556 100644 --- a/context/context.go +++ b/context/context.go @@ -2110,9 +2110,7 @@ func GetForm(r *http.Request, postMaxMemory int64, resetBody bool) (form map[str } } - var ( - bodyCopy []byte - ) + var bodyCopy []byte if resetBody { // on POST, PUT and PATCH it will read the form values from request body otherwise from URL queries. @@ -2360,7 +2358,6 @@ func uploadTo(fh *multipart.FileHeader, destDirectory string) (int64, error) { out, err := os.OpenFile(filepath.Join(destDirectory, fh.Filename), os.O_WRONLY|os.O_CREATE, os.FileMode(0666)) - if err != nil { return 0, err } @@ -2534,7 +2531,7 @@ func (ctx *context) shouldOptimize() bool { // // Example: https://github.com/kataras/iris/blob/master/_examples/http_request/read-json/main.go func (ctx *context) ReadJSON(outPtr interface{}) error { - var unmarshaler = json.Unmarshal + unmarshaler := json.Unmarshal if ctx.shouldOptimize() { unmarshaler = jsoniter.Unmarshal } @@ -2814,9 +2811,7 @@ func (ctx *context) ClientSupportsGzip() bool { return false } -var ( - errClientDoesNotSupportGzip = errors.New("client doesn't support gzip compression") -) +var errClientDoesNotSupportGzip = errors.New("client doesn't support gzip compression") // WriteGzip accepts bytes, which are compressed to gzip format and sent to the client. // returns the number of bytes written and an error ( if the client doesn't support gzip compression) @@ -3163,7 +3158,7 @@ func (ctx *context) JSON(v interface{}, opts ...JSON) (n int, err error) { if options.StreamingJSON { if ctx.shouldOptimize() { - var jsoniterConfig = jsoniter.Config{ + jsoniterConfig := jsoniter.Config{ EscapeHTML: !options.UnescapeHTML, IndentionStep: 4, }.Froze() @@ -3194,9 +3189,7 @@ func (ctx *context) JSON(v interface{}, opts ...JSON) (n int, err error) { return n, err } -var ( - finishCallbackB = []byte(");") -) +var finishCallbackB = []byte(");") // WriteJSONP marshals the given interface object and writes the JSON response to the writer. func WriteJSONP(writer io.Writer, v interface{}, options JSONP, enableOptimization ...bool) (int, error) { @@ -4081,9 +4074,7 @@ func (n *NegotiationAcceptBuilder) EncodingGzip() *NegotiationAcceptBuilder { // | Serve files | // +------------------------------------------------------------+ -var ( - errServeContent = errors.New("while trying to serve content to the client. Trace %s") -) +var errServeContent = errors.New("while trying to serve content to the client. Trace %s") // ServeContent serves content, headers are autoset // receives three parameters, it's low-level function, instead you can use .ServeFile(string,bool)/SendFile(string,string) @@ -4387,7 +4378,7 @@ func (ctx *context) Recorder() *ResponseRecorder { // when the response writer is recording the status code, body, headers and so on, // else returns nil and false. func (ctx *context) IsRecording() (*ResponseRecorder, bool) { - //NOTE: + // NOTE: // two return values in order to minimize the if statement: // if (Recording) then writer = Recorder() // instead we do: recorder,ok = Recording() @@ -4435,7 +4426,6 @@ func (ctx *context) BeginTransaction(pipe func(t *Transaction)) { // give back to the transaction the original writer (SetBeforeFlush works this way and only this way) // this is tricky but nessecery if we want ctx.FireStatusCode to work inside transactions t.Context().ResetResponseWriter(ctx.writer) - }() // run the worker with its context clone inside. diff --git a/context/gzip_response_writer.go b/context/gzip_response_writer.go index 6213e915..42be3626 100644 --- a/context/gzip_response_writer.go +++ b/context/gzip_response_writer.go @@ -133,7 +133,6 @@ func (w *GzipResponseWriter) WriteString(s string) (n int, err error) { if w.ResponseWriter.Header()[ContentTypeHeaderKey] == nil { w.ResponseWriter.Header().Set(ContentTypeHeaderKey, ContentTextHeaderValue) } - } return } diff --git a/context/request_params.go b/context/request_params.go index 740b2e8f..4e7cd468 100644 --- a/context/request_params.go +++ b/context/request_params.go @@ -89,124 +89,122 @@ func (r RequestParams) GetIntUnslashed(key string) (int, bool) { return -1, false } -var ( - // ParamResolvers is the global param resolution for a parameter type for a specific go std or custom type. - // - // Key is the specific type, which should be unique. - // The value is a function which accepts the parameter index - // and it should return the value as the parameter type evaluator expects it. - // i.e [reflect.TypeOf("string")] = func(paramIndex int) interface{} { - // return func(ctx Context) { - // return ctx.Params().GetEntryAt(paramIndex).ValueRaw.() - // } - // } - // - // Read https://github.com/kataras/iris/tree/master/_examples/routing/macros for more details. - // Checks for total available request parameters length - // and parameter index based on the hero/mvc function added - // in order to support the MVC.HandleMany("GET", "/path/{ps}/{pssecond} /path/{ps}") - // when on the second requested path, the 'pssecond' should be empty. - ParamResolvers = map[reflect.Type]func(paramIndex int) interface{}{ - reflect.TypeOf(""): func(paramIndex int) interface{} { - return func(ctx Context) string { - if ctx.Params().Len() <= paramIndex { - return "" - } - return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(string) +// ParamResolvers is the global param resolution for a parameter type for a specific go std or custom type. +// +// Key is the specific type, which should be unique. +// The value is a function which accepts the parameter index +// and it should return the value as the parameter type evaluator expects it. +// i.e [reflect.TypeOf("string")] = func(paramIndex int) interface{} { +// return func(ctx Context) { +// return ctx.Params().GetEntryAt(paramIndex).ValueRaw.() +// } +// } +// +// Read https://github.com/kataras/iris/tree/master/_examples/routing/macros for more details. +// Checks for total available request parameters length +// and parameter index based on the hero/mvc function added +// in order to support the MVC.HandleMany("GET", "/path/{ps}/{pssecond} /path/{ps}") +// when on the second requested path, the 'pssecond' should be empty. +var ParamResolvers = map[reflect.Type]func(paramIndex int) interface{}{ + reflect.TypeOf(""): func(paramIndex int) interface{} { + return func(ctx Context) string { + if ctx.Params().Len() <= paramIndex { + return "" } - }, - reflect.TypeOf(int(1)): func(paramIndex int) interface{} { - return func(ctx Context) int { - if ctx.Params().Len() <= paramIndex { - return 0 - } - // v, _ := ctx.Params().GetEntryAt(paramIndex).IntDefault(0) - // return v - return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(int) + return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(string) + } + }, + reflect.TypeOf(int(1)): func(paramIndex int) interface{} { + return func(ctx Context) int { + if ctx.Params().Len() <= paramIndex { + return 0 } - }, - reflect.TypeOf(int8(1)): func(paramIndex int) interface{} { - return func(ctx Context) int8 { - if ctx.Params().Len() <= paramIndex { - return 0 - } - return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(int8) + // v, _ := ctx.Params().GetEntryAt(paramIndex).IntDefault(0) + // return v + return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(int) + } + }, + reflect.TypeOf(int8(1)): func(paramIndex int) interface{} { + return func(ctx Context) int8 { + if ctx.Params().Len() <= paramIndex { + return 0 } - }, - reflect.TypeOf(int16(1)): func(paramIndex int) interface{} { - return func(ctx Context) int16 { - if ctx.Params().Len() <= paramIndex { - return 0 - } - return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(int16) + return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(int8) + } + }, + reflect.TypeOf(int16(1)): func(paramIndex int) interface{} { + return func(ctx Context) int16 { + if ctx.Params().Len() <= paramIndex { + return 0 } - }, - reflect.TypeOf(int32(1)): func(paramIndex int) interface{} { - return func(ctx Context) int32 { - if ctx.Params().Len() <= paramIndex { - return 0 - } - return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(int32) + return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(int16) + } + }, + reflect.TypeOf(int32(1)): func(paramIndex int) interface{} { + return func(ctx Context) int32 { + if ctx.Params().Len() <= paramIndex { + return 0 } - }, - reflect.TypeOf(int64(1)): func(paramIndex int) interface{} { - return func(ctx Context) int64 { - if ctx.Params().Len() <= paramIndex { - return 0 - } - return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(int64) + return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(int32) + } + }, + reflect.TypeOf(int64(1)): func(paramIndex int) interface{} { + return func(ctx Context) int64 { + if ctx.Params().Len() <= paramIndex { + return 0 } - }, - reflect.TypeOf(uint(1)): func(paramIndex int) interface{} { - return func(ctx Context) uint { - if ctx.Params().Len() <= paramIndex { - return 0 - } - return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(uint) + return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(int64) + } + }, + reflect.TypeOf(uint(1)): func(paramIndex int) interface{} { + return func(ctx Context) uint { + if ctx.Params().Len() <= paramIndex { + return 0 } - }, - reflect.TypeOf(uint8(1)): func(paramIndex int) interface{} { - return func(ctx Context) uint8 { - if ctx.Params().Len() <= paramIndex { - return 0 - } - return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(uint8) + return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(uint) + } + }, + reflect.TypeOf(uint8(1)): func(paramIndex int) interface{} { + return func(ctx Context) uint8 { + if ctx.Params().Len() <= paramIndex { + return 0 } - }, - reflect.TypeOf(uint16(1)): func(paramIndex int) interface{} { - return func(ctx Context) uint16 { - if ctx.Params().Len() <= paramIndex { - return 0 - } - return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(uint16) + return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(uint8) + } + }, + reflect.TypeOf(uint16(1)): func(paramIndex int) interface{} { + return func(ctx Context) uint16 { + if ctx.Params().Len() <= paramIndex { + return 0 } - }, - reflect.TypeOf(uint32(1)): func(paramIndex int) interface{} { - return func(ctx Context) uint32 { - if ctx.Params().Len() <= paramIndex { - return 0 - } - return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(uint32) + return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(uint16) + } + }, + reflect.TypeOf(uint32(1)): func(paramIndex int) interface{} { + return func(ctx Context) uint32 { + if ctx.Params().Len() <= paramIndex { + return 0 } - }, - reflect.TypeOf(uint64(1)): func(paramIndex int) interface{} { - return func(ctx Context) uint64 { - if ctx.Params().Len() <= paramIndex { - return 0 - } - return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(uint64) + return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(uint32) + } + }, + reflect.TypeOf(uint64(1)): func(paramIndex int) interface{} { + return func(ctx Context) uint64 { + if ctx.Params().Len() <= paramIndex { + return 0 } - }, - reflect.TypeOf(true): func(paramIndex int) interface{} { - return func(ctx Context) bool { - if ctx.Params().Len() <= paramIndex { - return false - } - return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(bool) + return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(uint64) + } + }, + reflect.TypeOf(true): func(paramIndex int) interface{} { + return func(ctx Context) bool { + if ctx.Params().Len() <= paramIndex { + return false } - }, - } -) + return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(bool) + } + }, +} // ParamResolverByTypeAndIndex will return a function that can be used to bind path parameter's exact value by its Go std type // and the parameter's index based on the registered path. diff --git a/context/response_recorder.go b/context/response_recorder.go index d32e1eeb..5a0840b9 100644 --- a/context/response_recorder.go +++ b/context/response_recorder.go @@ -188,7 +188,6 @@ func (w *ResponseRecorder) Clone() ResponseWriter { // WriteTo writes a response writer (temp: status code, headers and body) to another response writer func (w *ResponseRecorder) WriteTo(res ResponseWriter) { - if to, ok := res.(*ResponseRecorder); ok { // set the status code, to is first ( probably an error? (context.StatusCodeNotSuccessful, defaults to < 200 || >= 400). diff --git a/context/response_writer.go b/context/response_writer.go index 27d5dd85..3a6b89bc 100644 --- a/context/response_writer.go +++ b/context/response_writer.go @@ -298,7 +298,6 @@ func (w *responseWriter) WriteTo(to ResponseWriter) { } } } - } // the body is not copied, this writer doesn't support recording } diff --git a/core/errors/errors.go b/core/errors/errors.go index e06e97a1..70696144 100644 --- a/core/errors/errors.go +++ b/core/errors/errors.go @@ -8,10 +8,8 @@ import ( "github.com/iris-contrib/go.uuid" ) -var ( - // Prefix the error prefix, applies to each error's message. - Prefix = "" -) +// Prefix the error prefix, applies to each error's message. +var Prefix = "" // Error holds the error message, this message never really changes type Error struct { diff --git a/core/errors/errors_test.go b/core/errors/errors_test.go index 8c03eb31..937b6403 100644 --- a/core/errors/errors_test.go +++ b/core/errors/errors_test.go @@ -14,7 +14,6 @@ var userMail = "user1@mail.go" var expectedUserAlreadyExists = "User with mail: user1@mail.go already exists" func ExampleError() { - fmt.Print(errUserAlreadyExists.Format(userMail).Append("Please change your mail addr")) // Output: @@ -38,7 +37,6 @@ func TestFormat(t *testing.T) { } func TestAppendErr(t *testing.T) { - errChangeMailMsg := "Please change your mail addr" errChangeMail := fmt.Errorf(errChangeMailMsg) // test go standard error errAppended := errUserAlreadyExists.AppendErr(errChangeMail) diff --git a/core/errors/reporter.go b/core/errors/reporter.go index b38111f7..b501586c 100644 --- a/core/errors/reporter.go +++ b/core/errors/reporter.go @@ -78,7 +78,6 @@ func (r *Reporter) AddErr(err error) bool { // // Returns true if this "err" is not nil and it's added to the reporter's stack. func (r *Reporter) Add(format string, a ...interface{}) bool { - if format == "" && len(a) == 0 { return false } diff --git a/core/handlerconv/from_std.go b/core/handlerconv/from_std.go index 255bcaa9..57d6de9a 100644 --- a/core/handlerconv/from_std.go +++ b/core/handlerconv/from_std.go @@ -26,7 +26,7 @@ func FromStd(handler interface{}) context.Handler { case context.Handler: { // - //it's already a iris handler + // it's already a iris handler // return handler.(context.Handler) } @@ -67,7 +67,6 @@ func FromStd(handler interface{}) context.Handler { } } - } // FromStdWithNext receives a standar handler - middleware form - and returns a diff --git a/core/handlerconv/from_std_test.go b/core/handlerconv/from_std_test.go index 49bb7938..29afc2ee 100644 --- a/core/handlerconv/from_std_test.go +++ b/core/handlerconv/from_std_test.go @@ -36,7 +36,6 @@ func TestFromStd(t *testing.T) { } func TestFromStdWithNext(t *testing.T) { - basicauth := "secret" passed := "ok" diff --git a/core/host/supervisor_task_example_test.go b/core/host/supervisor_task_example_test.go index 9c83e8a1..d3a83726 100644 --- a/core/host/supervisor_task_example_test.go +++ b/core/host/supervisor_task_example_test.go @@ -76,7 +76,6 @@ func (m myTestTask) OnServe(host TaskHost) { time.AfterFunc(startDelay, func() { m.logger.Println("restart") host.Serve() // restart - }) } diff --git a/core/host/supervisor_test.go b/core/host/supervisor_test.go index 3f2dcbdd..523a2ae5 100644 --- a/core/host/supervisor_test.go +++ b/core/host/supervisor_test.go @@ -20,7 +20,6 @@ const ( ) func newTester(t *testing.T, baseURL string, handler http.Handler) *httpexpect.Expect { - var transporter http.RoundTripper if strings.HasPrefix(baseURL, "http") { // means we are testing real serve time @@ -57,9 +56,8 @@ func testSupervisor(t *testing.T, creator func(*http.Server, []func(TaskHost)) * ) // http routing - var ( - expectedBody = "this is the response body\n" - ) + + expectedBody := "this is the response body\n" mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { @@ -98,6 +96,7 @@ func testSupervisor(t *testing.T, creator func(*http.Server, []func(TaskHost)) * t.Fatalf("expected hello Task's message to be '%s' but got '%s'", expectedHelloMessage, got) } } + func TestSupervisor(t *testing.T) { testSupervisor(t, func(srv *http.Server, tasks []func(TaskHost)) *Supervisor { su := New(srv) diff --git a/core/netutil/addr.go b/core/netutil/addr.go index 2844dee1..49167ff2 100644 --- a/core/netutil/addr.go +++ b/core/netutil/addr.go @@ -30,7 +30,6 @@ var IsLoopbackSubdomain = func(s string) bool { if !strings.Contains(machineHostname, ".") { // if machine name's is not a loopback by itself valid = s == machineHostname } - } return valid } @@ -96,10 +95,8 @@ const ( defaultServerPort = 8080 ) -var ( - // defaultServerAddr the default server addr which is: localhost:8080 - defaultServerAddr = defaultServerHostname + ":" + strconv.Itoa(defaultServerPort) -) +// defaultServerAddr the default server addr which is: localhost:8080 +var defaultServerAddr = defaultServerHostname + ":" + strconv.Itoa(defaultServerPort) // ResolveAddr tries to convert a given string to an address which is compatible with net.Listener and server func ResolveAddr(addr string) string { diff --git a/core/netutil/tcp.go b/core/netutil/tcp.go index 1b025d29..9b2178cf 100644 --- a/core/netutil/tcp.go +++ b/core/netutil/tcp.go @@ -85,7 +85,6 @@ func UNIX(socketFile string, mode os.FileMode) (net.Listener, error) { // TLS returns a new TLS Listener and an error on failure. func TLS(addr, certFile, keyFile string) (net.Listener, error) { - if certFile == "" || keyFile == "" { return nil, errCertKeyMissing } diff --git a/core/router/api_builder.go b/core/router/api_builder.go index 35b64425..a40447bc 100644 --- a/core/router/api_builder.go +++ b/core/router/api_builder.go @@ -17,22 +17,20 @@ import ( // to store the "offline" routes. const MethodNone = "NONE" -var ( - // AllMethods contains the valid http methods: - // "GET", "POST", "PUT", "DELETE", "CONNECT", "HEAD", - // "PATCH", "OPTIONS", "TRACE". - AllMethods = []string{ - http.MethodGet, - http.MethodPost, - http.MethodPut, - http.MethodDelete, - http.MethodConnect, - http.MethodHead, - http.MethodPatch, - http.MethodOptions, - http.MethodTrace, - } -) +// AllMethods contains the valid http methods: +// "GET", "POST", "PUT", "DELETE", "CONNECT", "HEAD", +// "PATCH", "OPTIONS", "TRACE". +var AllMethods = []string{ + http.MethodGet, + http.MethodPost, + http.MethodPut, + http.MethodDelete, + http.MethodConnect, + http.MethodHead, + http.MethodPatch, + http.MethodOptions, + http.MethodTrace, +} // repository passed to all parties(subrouters), it's the object witch keeps // all the routes. @@ -403,7 +401,6 @@ func (api *APIBuilder) HandleMany(methodOrMulti string, relativePathorMulti stri } routes = append(routes, api.Handle(method, p, handlers...)) } - } } return @@ -433,7 +430,6 @@ func (api *APIBuilder) HandleDir(requestPath, directory string, opts ...DirOptio // and we need that path to call the `StripPrefix`. if _, fullpath := splitSubdomainAndPath(joinPath(api.relativePath, requestPath)); fullpath != "/" { h = StripPrefix(fullpath, h) - } requestPath = joinPath(requestPath, WildcardFileParam()) diff --git a/core/router/handler.go b/core/router/handler.go index b63d0979..c93ac62c 100644 --- a/core/router/handler.go +++ b/core/router/handler.go @@ -179,7 +179,6 @@ func (h *routerHandler) HandleRequest(ctx context.Context) { method := ctx.Method() path := ctx.Path() if !ctx.Application().ConfigurationReadOnly().GetDisablePathCorrection() { - if len(path) > 1 && strings.HasSuffix(path, "/") { // Remove trailing slash and client-permanent rule for redirection, // if confgiuration allows that and path has an extra slash. diff --git a/core/router/mime.go b/core/router/mime.go index e153d9e8..adc900eb 100644 --- a/core/router/mime.go +++ b/core/router/mime.go @@ -581,7 +581,6 @@ func TypeByExtension(ext string) (typ string) { // mime.TypeByExtension returns as text/plain; | charset=utf-8 the static .js (not always) if ext == ".js" && (typ == "text/plain" || typ == "text/plain; charset=utf-8") { - if ext == ".js" { typ = "application/javascript" } diff --git a/core/router/path_test.go b/core/router/path_test.go index 2c26c6da..2b2c7538 100644 --- a/core/router/path_test.go +++ b/core/router/path_test.go @@ -9,26 +9,44 @@ func TestCleanPath(t *testing.T) { path string expected string }{ - {"/", - "/"}, - {"noslashPrefix", - "/noslashPrefix"}, - {"slashSuffix/", - "/slashSuffix"}, - {"noSlashPrefixAndslashSuffix/", - "/noSlashPrefixAndslashSuffix"}, + { + "/", + "/", + }, + { + "noslashPrefix", + "/noslashPrefix", + }, + { + "slashSuffix/", + "/slashSuffix", + }, + { + "noSlashPrefixAndslashSuffix/", + "/noSlashPrefixAndslashSuffix", + }, // don't do any clean up inside {}, // fixes #927. - {"/total/{year:string regexp(\\d{4})}", - "/total/{year:string regexp(\\d{4})}"}, - {"/total/{year:string regexp(\\d{4})}/more", - "/total/{year:string regexp(\\d{4})}/more"}, - {"/total/{year:string regexp(\\d{4})}/more/{s:string regexp(\\d{7})}", - "/total/{year:string regexp(\\d{4})}/more/{s:string regexp(\\d{7})}"}, - {"/single_no_params", - "/single_no_params"}, - {"/single/{id:uint64}", - "/single/{id:uint64}"}, + { + "/total/{year:string regexp(\\d{4})}", + "/total/{year:string regexp(\\d{4})}", + }, + { + "/total/{year:string regexp(\\d{4})}/more", + "/total/{year:string regexp(\\d{4})}/more", + }, + { + "/total/{year:string regexp(\\d{4})}/more/{s:string regexp(\\d{7})}", + "/total/{year:string regexp(\\d{4})}/more/{s:string regexp(\\d{7})}", + }, + { + "/single_no_params", + "/single_no_params", + }, + { + "/single/{id:uint64}", + "/single/{id:uint64}", + }, } for i, tt := range tests { @@ -43,18 +61,30 @@ func TestSplitPath(t *testing.T) { path string expected []string }{ - {"/v2/stores/{id:string format(uuid)} /v3", - []string{"/v2/stores/{id:string format(uuid)}", "/v3"}}, - {"/user/{id:uint64} /admin/{id:uint64}", - []string{"/user/{id:uint64}", "/admin/{id:uint64}"}}, - {"/users/{id:int} /admins/{id:int64}", - []string{"/users/{id:int}", "/admins/{id:int64}"}}, - {"/user /admin", - []string{"/user", "/admin"}}, - {"/single_no_params", - []string{"/single_no_params"}}, - {"/single/{id:int}", - []string{"/single/{id:int}"}}, + { + "/v2/stores/{id:string format(uuid)} /v3", + []string{"/v2/stores/{id:string format(uuid)}", "/v3"}, + }, + { + "/user/{id:uint64} /admin/{id:uint64}", + []string{"/user/{id:uint64}", "/admin/{id:uint64}"}, + }, + { + "/users/{id:int} /admins/{id:int64}", + []string{"/users/{id:int}", "/admins/{id:int64}"}, + }, + { + "/user /admin", + []string{"/user", "/admin"}, + }, + { + "/single_no_params", + []string{"/single_no_params"}, + }, + { + "/single/{id:int}", + []string{"/single/{id:int}"}, + }, } equalSlice := func(s1 []string, s2 []string) bool { @@ -78,6 +108,7 @@ func TestSplitPath(t *testing.T) { } } } + func TestSplitSubdomainAndPath(t *testing.T) { tests := []struct { original string diff --git a/core/router/route.go b/core/router/route.go index 60446246..42dcc20b 100644 --- a/core/router/route.go +++ b/core/router/route.go @@ -51,7 +51,6 @@ type Route struct { // handlers are being changed to validate the macros at serve time, if needed. func NewRoute(method, subdomain, unparsedPath, mainHandlerName string, handlers context.Handlers, macros macro.Macros) (*Route, error) { - tmpl, err := macro.Parse(unparsedPath, macros) if err != nil { return nil, err diff --git a/core/router/route_test.go b/core/router/route_test.go index 58cc25f8..86a02cb3 100644 --- a/core/router/route_test.go +++ b/core/router/route_test.go @@ -3,13 +3,13 @@ package router import ( - "github.com/kataras/iris/macro" - "testing" + + "github.com/kataras/iris/macro" ) func TestRouteStaticPath(t *testing.T) { - var tests = []struct { + tests := []struct { tmpl string static string }{ diff --git a/core/router/router.go b/core/router/router.go index b180d502..e6efea9d 100644 --- a/core/router/router.go +++ b/core/router/router.go @@ -42,7 +42,6 @@ func (router *Router) RefreshRouter() error { // // Use of RefreshRouter to re-build the router if needed. func (router *Router) BuildRouter(cPool *context.Pool, requestHandler RequestHandler, routesProvider RoutesProvider, force bool) error { - if requestHandler == nil { return errors.New("router: request handler is nil") } diff --git a/core/router/router_handlers_order_test.go b/core/router/router_handlers_order_test.go index a8951c7b..e4942ec3 100644 --- a/core/router/router_handlers_order_test.go +++ b/core/router/router_handlers_order_test.go @@ -76,6 +76,7 @@ func TestMiddlewareByRouteDef(t *testing.T) { testResponse(t, app, "/mypath") } + func TestMiddlewareByUseAndDoneDef(t *testing.T) { app := iris.New() app.Use(firstUseGlobalHandler, secondUseGlobalHandler, firstUseHandler, secondUseHandler) diff --git a/core/router/router_wildcard_root_test.go b/core/router/router_wildcard_root_test.go index c3190ce5..37570f17 100644 --- a/core/router/router_wildcard_root_test.go +++ b/core/router/router_wildcard_root_test.go @@ -52,7 +52,7 @@ func h3(ctx context.Context) { } func TestRouterWildcardDifferentPrefixPath(t *testing.T) { - var tt = []testRoute{ + tt := []testRoute{ {"GET", "/s/{p:path}", h, []testRouteRequest{ {"GET", "", "/s/that/is/wildcard", iris.StatusOK, same_as_request_path}, {"GET", "", "/s/ok", iris.StatusOK, same_as_request_path}, @@ -71,7 +71,7 @@ func TestRouterWildcardDifferentPrefixPath(t *testing.T) { } func TestRouterWildcardAndStatic(t *testing.T) { - var tt = []testRoute{ + tt := []testRoute{ {"GET", "/some/{p:path}", h2, []testRouteRequest{ {"GET", "", "/some/that/is/wildcard", iris.StatusForbidden, same_as_request_path}, {"GET", "", "/some/did", iris.StatusForbidden, same_as_request_path}, @@ -95,7 +95,7 @@ func TestRouterWildcardAndStatic(t *testing.T) { } func TestRouterWildcardRootMany(t *testing.T) { - var tt = []testRoute{ + tt := []testRoute{ // all routes will be handlded by "h" because we added wildcard to root, // this feature is very important and can remove noumerous of previous hacks on our apps. {"GET", "/{p:path}", h, []testRouteRequest{ @@ -121,7 +121,7 @@ func TestRouterWildcardRootMany(t *testing.T) { } func TestRouterWildcardRootManyAndRootStatic(t *testing.T) { - var tt = []testRoute{ + tt := []testRoute{ // routes that may return 404 will be handled by the below route ("h" handler) because we added wildcard to root, // this feature is very important and can remove noumerous of previous hacks on our apps. // diff --git a/core/router/status.go b/core/router/status.go index d0b391c9..460284a7 100644 --- a/core/router/status.go +++ b/core/router/status.go @@ -88,7 +88,8 @@ func defaultErrorCodeHandlers() *ErrorCodeHandlers { for _, statusCode := range []int{ http.StatusNotFound, http.StatusMethodNotAllowed, - http.StatusInternalServerError} { + http.StatusInternalServerError, + } { chs.Register(statusCode, statusText(statusCode)) } diff --git a/core/router/status_test.go b/core/router/status_test.go index c18e2ff2..05ed04e5 100644 --- a/core/router/status_test.go +++ b/core/router/status_test.go @@ -61,7 +61,6 @@ func TestOnAnyErrorCode(t *testing.T) { Body().Equal(http.StatusText(iris.StatusNotAcceptable)) checkAndClearBuf(t, buff, expectedPrintBeforeExecuteErr) - } func checkAndClearBuf(t *testing.T, buff *bytes.Buffer, expected string) { diff --git a/hero/di/func.go b/hero/di/func.go index 1f30e307..d7368c97 100644 --- a/hero/di/func.go +++ b/hero/di/func.go @@ -88,7 +88,7 @@ func MakeFuncInjector(fn reflect.Value, hijack Hijacker, goodFunc TypeChecker, v // again, a next value even with the same type is able to be // used to other input arg. One value per input argument, order // matters if same type of course. - //if len(values) > j+1 { + // if len(values) > j+1 { values = append(values[:j], values[j+1:]...) //} @@ -126,7 +126,6 @@ func (s *FuncInjector) addValue(inputIndex int, value reflect.Value) bool { // the binded values to the func's inputs. b, err := MakeBindObject(value, s.goodFunc) - if err != nil { return false } @@ -197,7 +196,6 @@ func (s *FuncInjector) Inject(in *[]reflect.Value, ctx ...reflect.Value) { // input.InputIndex, v.String(), v.Type().Name()) args[input.InputIndex] = v }) - } *in = args diff --git a/hero/di/values.go b/hero/di/values.go index 0ffdd23f..b0543a62 100644 --- a/hero/di/values.go +++ b/hero/di/values.go @@ -124,9 +124,8 @@ func (bv *Values) AddOnce(value interface{}) bool { } func (bv *Values) addIfNotExists(v reflect.Value) bool { - var ( - typ = v.Type() // no element, raw things here. - ) + + typ := v.Type() // no element, raw things here. if !goodVal(v) { return false diff --git a/hero/func_result.go b/hero/func_result.go index 97afe290..314f745e 100644 --- a/hero/func_result.go +++ b/hero/func_result.go @@ -95,7 +95,6 @@ func DispatchErr(ctx context.Context, status int, err error) { // commonly used data to the response writer with a smart way. func DispatchCommon(ctx context.Context, statusCode int, contentType string, content []byte, v interface{}, err error, found bool) { - // if we have a false boolean as a return value // then skip everything and fire a not found, // we even don't care about the given status code or the object or the content. diff --git a/hero/handler.go b/hero/handler.go index dbe51d8f..e2c43ccf 100644 --- a/hero/handler.go +++ b/hero/handler.go @@ -11,9 +11,7 @@ import ( "github.com/kataras/golog" ) -var ( - contextTyp = reflect.TypeOf((*context.Context)(nil)).Elem() -) +var contextTyp = reflect.TypeOf((*context.Context)(nil)).Elem() // IsContext returns true if the "inTyp" is a type of Context. func IsContext(inTyp reflect.Type) bool { @@ -95,5 +93,4 @@ func makeHandler(handler interface{}, values ...reflect.Value) (context.Handler, } return h, nil - } diff --git a/hero/param_test.go b/hero/param_test.go index 112edd0f..ba03a6d3 100644 --- a/hero/param_test.go +++ b/hero/param_test.go @@ -44,5 +44,4 @@ func TestPathParams(t *testing.T) { if got != expected { t.Fatalf("expected the params 'firstname' + 'lastname' to be '%s' but got '%s'", expected, got) } - } diff --git a/iris.go b/iris.go index 4164e402..c854e533 100644 --- a/iris.go +++ b/iris.go @@ -35,10 +35,8 @@ import ( "github.com/kataras/iris/middleware/recover" ) -var ( - // Version is the current version number of the Iris Web Framework. - Version = "11.2.8" -) +// Version is the current version number of the Iris Web Framework. +const Version = "11.2.8" // HTTP status codes as registered with IANA. // See: http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml diff --git a/macro/interpreter/lexer/lexer.go b/macro/interpreter/lexer/lexer.go index 6a772602..9c553e59 100644 --- a/macro/interpreter/lexer/lexer.go +++ b/macro/interpreter/lexer/lexer.go @@ -69,7 +69,6 @@ func resolveTokenType(ch byte) token.Type { default: return token.IDENT // } - } // NextToken returns the next token in the series of characters. diff --git a/macro/interpreter/parser/parser_test.go b/macro/interpreter/parser/parser_test.go index 5424f675..9550c66f 100644 --- a/macro/interpreter/parser/parser_test.go +++ b/macro/interpreter/parser/parser_test.go @@ -93,7 +93,8 @@ func TestParseParam(t *testing.T) { valid bool expectedStatement ast.ParamStatement }{ - {true, + { + true, ast.ParamStatement{ Src: "{id:int min(1) max(5) else 404}", Name: "id", @@ -101,15 +102,19 @@ func TestParseParam(t *testing.T) { Funcs: []ast.ParamFunc{ { Name: "min", - Args: []string{"1"}}, + Args: []string{"1"}, + }, { Name: "max", - Args: []string{"5"}}, + Args: []string{"5"}, + }, }, ErrorCode: 404, - }}, // 0 + }, + }, // 0 - {true, + { + true, ast.ParamStatement{ // test alias of int. Src: "{id:number range(1,5)}", @@ -118,11 +123,14 @@ func TestParseParam(t *testing.T) { Funcs: []ast.ParamFunc{ { Name: "range", - Args: []string{"1", "5"}}, + Args: []string{"1", "5"}, + }, }, ErrorCode: 404, - }}, // 1 - {true, + }, + }, // 1 + { + true, ast.ParamStatement{ Src: "{file:path contains(.)}", Name: "file", @@ -130,84 +138,107 @@ func TestParseParam(t *testing.T) { Funcs: []ast.ParamFunc{ { Name: "contains", - Args: []string{"."}}, + Args: []string{"."}, + }, }, ErrorCode: 404, - }}, // 2 - {true, + }, + }, // 2 + { + true, ast.ParamStatement{ Src: "{username:alphabetical}", Name: "username", Type: mustLookupParamType("alphabetical"), ErrorCode: 404, - }}, // 3 - {true, + }, + }, // 3 + { + true, ast.ParamStatement{ Src: "{myparam}", Name: "myparam", Type: mustLookupParamType("string"), ErrorCode: 404, - }}, // 4 - {false, + }, + }, // 4 + { + false, ast.ParamStatement{ Src: "{myparam_:thisianunexpected}", Name: "myparam_", Type: nil, ErrorCode: 404, - }}, // 5 - {true, + }, + }, // 5 + { + true, ast.ParamStatement{ Src: "{myparam2}", Name: "myparam2", // we now allow integers to the parameter names. Type: ast.GetMasterParamType(testParamTypes...), ErrorCode: 404, - }}, // 6 - {true, + }, + }, // 6 + { + true, ast.ParamStatement{ Src: "{id:int even()}", // test param funcs without any arguments (LPAREN peek for RPAREN) Name: "id", Type: mustLookupParamType("number"), Funcs: []ast.ParamFunc{ { - Name: "even"}, + Name: "even", + }, }, ErrorCode: 404, - }}, // 7 - {true, + }, + }, // 7 + { + true, ast.ParamStatement{ Src: "{id:int64 else 404}", Name: "id", Type: mustLookupParamType("int64"), ErrorCode: 404, - }}, // 8 - {true, + }, + }, // 8 + { + true, ast.ParamStatement{ Src: "{id:long else 404}", // backwards-compatible test. Name: "id", Type: mustLookupParamType("int64"), ErrorCode: 404, - }}, // 9 - {true, + }, + }, // 9 + { + true, ast.ParamStatement{ Src: "{id:long else 404}", Name: "id", Type: mustLookupParamType("int64"), // backwards-compatible test of LookupParamType. ErrorCode: 404, - }}, // 10 - {true, + }, + }, // 10 + { + true, ast.ParamStatement{ Src: "{has:bool else 404}", Name: "has", Type: mustLookupParamType("bool"), ErrorCode: 404, - }}, // 11 - {true, + }, + }, // 11 + { + true, ast.ParamStatement{ Src: "{has:boolean else 404}", // backwards-compatible test. Name: "has", Type: mustLookupParamType("bool"), ErrorCode: 404, - }}, // 12 + }, + }, // 12 } @@ -237,88 +268,116 @@ func TestParse(t *testing.T) { valid bool expectedStatements []ast.ParamStatement }{ - {"/api/users/{id:int min(1) max(5) else 404}", true, - []ast.ParamStatement{{ - Src: "{id:int min(1) max(5) else 404}", - Name: "id", - Type: paramTypeNumber, - Funcs: []ast.ParamFunc{ - { - Name: "min", - Args: []string{"1"}}, - { - Name: "max", - Args: []string{"5"}}, + { + "/api/users/{id:int min(1) max(5) else 404}", true, + []ast.ParamStatement{ + { + Src: "{id:int min(1) max(5) else 404}", + Name: "id", + Type: paramTypeNumber, + Funcs: []ast.ParamFunc{ + { + Name: "min", + Args: []string{"1"}, + }, + { + Name: "max", + Args: []string{"5"}, + }, + }, + ErrorCode: 404, }, - ErrorCode: 404, }, - }}, // 0 - {"/admin/{id:uint64 range(1,5)}", true, - []ast.ParamStatement{{ - Src: "{id:uint64 range(1,5)}", - Name: "id", - Type: paramTypeUint64, - Funcs: []ast.ParamFunc{ - { - Name: "range", - Args: []string{"1", "5"}}, + }, // 0 + { + "/admin/{id:uint64 range(1,5)}", true, + []ast.ParamStatement{ + { + Src: "{id:uint64 range(1,5)}", + Name: "id", + Type: paramTypeUint64, + Funcs: []ast.ParamFunc{ + { + Name: "range", + Args: []string{"1", "5"}, + }, + }, + ErrorCode: 404, }, - ErrorCode: 404, }, - }}, // 1 - {"/files/{file:path contains(.)}", true, - []ast.ParamStatement{{ - Src: "{file:path contains(.)}", - Name: "file", - Type: paramTypePath, - Funcs: []ast.ParamFunc{ - { - Name: "contains", - Args: []string{"."}}, + }, // 1 + { + "/files/{file:path contains(.)}", true, + []ast.ParamStatement{ + { + Src: "{file:path contains(.)}", + Name: "file", + Type: paramTypePath, + Funcs: []ast.ParamFunc{ + { + Name: "contains", + Args: []string{"."}, + }, + }, + ErrorCode: 404, }, - ErrorCode: 404, }, - }}, // 2 - {"/profile/{username:alphabetical}", true, - []ast.ParamStatement{{ - Src: "{username:alphabetical}", - Name: "username", - Type: paramTypeAlphabetical, - ErrorCode: 404, + }, // 2 + { + "/profile/{username:alphabetical}", true, + []ast.ParamStatement{ + { + Src: "{username:alphabetical}", + Name: "username", + Type: paramTypeAlphabetical, + ErrorCode: 404, + }, }, - }}, // 3 - {"/something/here/{myparam}", true, - []ast.ParamStatement{{ - Src: "{myparam}", - Name: "myparam", - Type: paramTypeString, - ErrorCode: 404, + }, // 3 + { + "/something/here/{myparam}", true, + []ast.ParamStatement{ + { + Src: "{myparam}", + Name: "myparam", + Type: paramTypeString, + ErrorCode: 404, + }, }, - }}, // 4 - {"/unexpected/{myparam_:thisianunexpected}", false, - []ast.ParamStatement{{ - Src: "{myparam_:thisianunexpected}", - Name: "myparam_", - Type: nil, - ErrorCode: 404, + }, // 4 + { + "/unexpected/{myparam_:thisianunexpected}", false, + []ast.ParamStatement{ + { + Src: "{myparam_:thisianunexpected}", + Name: "myparam_", + Type: nil, + ErrorCode: 404, + }, }, - }}, // 5 - {"/p2/{myparam2}", true, - []ast.ParamStatement{{ - Src: "{myparam2}", - Name: "myparam2", // we now allow integers to the parameter names. - Type: paramTypeString, - ErrorCode: 404, + }, // 5 + { + "/p2/{myparam2}", true, + []ast.ParamStatement{ + { + Src: "{myparam2}", + Name: "myparam2", // we now allow integers to the parameter names. + Type: paramTypeString, + ErrorCode: 404, + }, }, - }}, // 6 - {"/assets/{file:path}/invalid", false, // path should be in the end segment - []ast.ParamStatement{{ - Src: "{file:path}", - Name: "file", - Type: paramTypePath, - ErrorCode: 404, + }, // 6 + { + "/assets/{file:path}/invalid", false, // path should be in the end segment + []ast.ParamStatement{ + { + Src: "{file:path}", + Name: "file", + Type: paramTypePath, + ErrorCode: 404, + }, }, - }}, // 7 + }, // 7 } for i, tt := range tests { statements, err := Parse(tt.path, testParamTypes) diff --git a/middleware/basicauth/basicauth.go b/middleware/basicauth/basicauth.go index 3016f4b4..ab5a1a07 100644 --- a/middleware/basicauth/basicauth.go +++ b/middleware/basicauth/basicauth.go @@ -107,7 +107,6 @@ func (b *basicAuthMiddleware) askForCredentials(ctx context.Context) { // Serve the actual middleware func (b *basicAuthMiddleware) Serve(ctx context.Context) { - auth, found := b.findAuth(ctx.GetHeader("Authorization")) if !found { b.askForCredentials(ctx) diff --git a/middleware/i18n/i18n.go b/middleware/i18n/i18n.go index 9f3175cf..93b9495e 100644 --- a/middleware/i18n/i18n.go +++ b/middleware/i18n/i18n.go @@ -82,7 +82,7 @@ func New(c Config) context.Handler { } i := &i18nMiddleware{config: c} firstlanguage := "" - //load the files + // load the files for k, langFileOrFiles := range c.Languages { // remove all spaces. langFileOrFiles = strings.Replace(langFileOrFiles, " ", "", -1) diff --git a/middleware/logger/logger.go b/middleware/logger/logger.go index 324c92ad..91766c55 100644 --- a/middleware/logger/logger.go +++ b/middleware/logger/logger.go @@ -41,7 +41,7 @@ func (l *requestLoggerMiddleware) ServeHTTP(ctx context.Context) { } } - //all except latency to string + // all except latency to string var status, ip, method, path string var latency time.Duration var startTime, endTime time.Time @@ -49,7 +49,7 @@ func (l *requestLoggerMiddleware) ServeHTTP(ctx context.Context) { ctx.Next() - //no time.Since in order to format it well after + // no time.Since in order to format it well after endTime = time.Now() latency = endTime.Sub(startTime) @@ -126,7 +126,6 @@ func (l *requestLoggerMiddleware) ServeHTTP(ctx context.Context) { // Columnize formats the given arguments as columns and returns the formatted output, // note that it appends a new line to the end. func Columnize(nowFormatted string, latency time.Duration, status, ip, method, path string, message interface{}, headerMessage interface{}) string { - titles := "Time | Status | Latency | IP | Method | Path" line := fmt.Sprintf("%s | %v | %4v | %s | %s | %s", nowFormatted, status, latency, ip, method, path) if message != nil { diff --git a/middleware/recaptcha/recaptcha.go b/middleware/recaptcha/recaptcha.go index d56e5da8..0c39ff25 100644 --- a/middleware/recaptcha/recaptcha.go +++ b/middleware/recaptcha/recaptcha.go @@ -65,7 +65,6 @@ func SiteFerify(ctx context.Context, secret string) (response Response) { // optional: let's no track our users "remoteip": {ctx.RemoteAddr()}, }, ) - if err != nil { response.ErrorCodes = append(response.ErrorCodes, err.Error()) return diff --git a/middleware/recover/recover.go b/middleware/recover/recover.go index 54da827f..b0974d11 100644 --- a/middleware/recover/recover.go +++ b/middleware/recover/recover.go @@ -35,7 +35,6 @@ func New() context.Handler { _, f, l, got := runtime.Caller(i) if !got { break - } stacktrace += fmt.Sprintf("%s:%d\n", f, l) diff --git a/mvc/controller.go b/mvc/controller.go index a372db9e..8c10d49b 100644 --- a/mvc/controller.go +++ b/mvc/controller.go @@ -491,5 +491,4 @@ func (c *ControllerActivator) handlerOf(m reflect.Method, funcDependencies []ref hero.DispatchFuncResult(ctx, errorHandler, ctrl.Method(m.Index).Call(emptyIn)) } - } diff --git a/mvc/controller_test.go b/mvc/controller_test.go index eb41ab7a..5575f421 100644 --- a/mvc/controller_test.go +++ b/mvc/controller_test.go @@ -23,27 +23,35 @@ var writeMethod = func(ctx context.Context) { func (c *testController) Get() { writeMethod(c.Ctx) } + func (c *testController) Post() { writeMethod(c.Ctx) } + func (c *testController) Put() { writeMethod(c.Ctx) } + func (c *testController) Delete() { writeMethod(c.Ctx) } + func (c *testController) Connect() { writeMethod(c.Ctx) } + func (c *testController) Head() { writeMethod(c.Ctx) } + func (c *testController) Patch() { writeMethod(c.Ctx) } + func (c *testController) Options() { writeMethod(c.Ctx) } + func (c *testController) Trace() { writeMethod(c.Ctx) } @@ -333,7 +341,7 @@ func (c *testCtrl0) EndRequest(ctx context.Context) { ctx.Writef(c.TitlePointer.title) } - //should be the same as `.testCtrl000.testCtrl0000.EndRequest(ctx)` + // should be the same as `.testCtrl000.testCtrl0000.EndRequest(ctx)` c.testCtrl00.EndRequest(ctx) } @@ -441,7 +449,6 @@ func TestControllerRelPathFromFunc(t *testing.T) { Body().Equal("GET:/42") e.GET("/anything/here").Expect().Status(iris.StatusOK). Body().Equal("GET:/anything/here") - } type testControllerActivateListener struct { diff --git a/mvc/go19.go b/mvc/go19.go index ab834727..0ab7cf2c 100644 --- a/mvc/go19.go +++ b/mvc/go19.go @@ -14,8 +14,6 @@ type ( View = hero.View ) -var ( - // Try is a type alias for the `hero#Try`, - // useful to return a result based on two cases: failure(including panics) and a succeess. - Try = hero.Try -) +// Try is a type alias for the `hero#Try`, +// useful to return a result based on two cases: failure(including panics) and a succeess. +var Try = hero.Try diff --git a/mvc/mvc.go b/mvc/mvc.go index cf9fb8b4..a58c2859 100644 --- a/mvc/mvc.go +++ b/mvc/mvc.go @@ -13,21 +13,19 @@ import ( "github.com/kataras/golog" ) -var ( - // HeroDependencies let you share bindable dependencies between - // package-level hero's registered dependencies and all MVC instances that comes later. - // - // `hero.Register(...)` - // `myMVC := mvc.New(app.Party(...))` - // the "myMVC" registers the dependencies provided by the `hero.Register` func - // automatically. - // - // Set it to false to disable that behavior, you have to use the `mvc#Register` - // even if you had register dependencies with the `hero` package. - // - // Defaults to true. - HeroDependencies = true -) +// HeroDependencies let you share bindable dependencies between +// package-level hero's registered dependencies and all MVC instances that comes later. +// +// `hero.Register(...)` +// `myMVC := mvc.New(app.Party(...))` +// the "myMVC" registers the dependencies provided by the `hero.Register` func +// automatically. +// +// Set it to false to disable that behavior, you have to use the `mvc#Register` +// even if you had register dependencies with the `hero` package. +// +// Defaults to true. +var HeroDependencies = true // Application is the high-level component of the "mvc" package. // It's the API that you will be using to register controllers among with their diff --git a/sessions/config.go b/sessions/config.go index 19760f58..b47579ff 100644 --- a/sessions/config.go +++ b/sessions/config.go @@ -120,7 +120,6 @@ type ( // Validate corrects missing fields configuration fields and returns the right configuration func (c Config) Validate() Config { - if c.Cookie == "" { c.Cookie = DefaultCookieName } diff --git a/sessions/sessiondb/badger/database.go b/sessions/sessiondb/badger/database.go index ca4b1ac8..84c8b0f6 100644 --- a/sessions/sessiondb/badger/database.go +++ b/sessions/sessiondb/badger/database.go @@ -62,7 +62,6 @@ func New(directoryPath string) (*Database, error) { opts := badger.DefaultOptions(directoryPath) service, err := badger.Open(opts) - if err != nil { golog.Errorf("unable to initialize the badger-based session database: %v", err) return nil, err @@ -97,7 +96,6 @@ func (db *Database) Acquire(sid string, expires time.Duration) sessions.LifeTime if err == badger.ErrKeyNotFound { // create it and set the expiration, we don't care about the value there. err = txn.SetEntry(badger.NewEntry(bsid, bsid).WithTTL(expires)) - } } @@ -192,7 +190,6 @@ func (db *Database) Visit(sid string, cb func(key string, value interface{})) { err := item.Value(func(valueBytes []byte) error { return sessions.DefaultTranscoder.Unmarshal(valueBytes, &value) }) - if err != nil { golog.Error(err) continue diff --git a/sessions/sessiondb/boltdb/database.go b/sessions/sessiondb/boltdb/database.go index b1b2bb64..e2859095 100644 --- a/sessions/sessiondb/boltdb/database.go +++ b/sessions/sessiondb/boltdb/database.go @@ -55,7 +55,6 @@ func New(path string, fileMode os.FileMode) (*Database, error) { service, err := bolt.Open(path, fileMode, &bolt.Options{Timeout: 20 * time.Second}, ) - if err != nil { golog.Errorf("unable to initialize the BoltDB-based session database: %v", err) return nil, err @@ -203,7 +202,6 @@ func (db *Database) Acquire(sid string, expires time.Duration) (lifetime session _, err = root.CreateBucketIfNotExists(bsid) return }) - if err != nil { golog.Debugf("unable to acquire session '%s': %v", sid, err) return sessions.LifeTime{} @@ -285,7 +283,6 @@ func (db *Database) Get(sid string, key string) (value interface{}) { return sessions.DefaultTranscoder.Unmarshal(valueBytes, &value) }) - if err != nil { golog.Debugf("session '%s' key '%s' not found", sid, key) } diff --git a/sessions/sessiondb/redis/database.go b/sessions/sessiondb/redis/database.go index 8b511317..847dcbb5 100644 --- a/sessions/sessiondb/redis/database.go +++ b/sessions/sessiondb/redis/database.go @@ -134,7 +134,6 @@ func (db *Database) Acquire(sid string, expires time.Duration) sessions.LifeTime if !hasExpiration { return sessions.LifeTime{} - } return sessions.LifeTime{Time: time.Now().Add(time.Duration(seconds) * time.Second)} diff --git a/sessions/sessiondb/redis/driver_radix.go b/sessions/sessiondb/redis/driver_radix.go index e379b8db..dc69886f 100644 --- a/sessions/sessiondb/redis/driver_radix.go +++ b/sessions/sessiondb/redis/driver_radix.go @@ -114,13 +114,12 @@ func (r *RadixDriver) Set(key string, value interface{}, secondsLifetime int64) } // Get returns value, err by its key -//returns nil and a filled error if something bad happened. +// returns nil and a filled error if something bad happened. func (r *RadixDriver) Get(key string) (interface{}, error) { var redisVal interface{} mn := radix.MaybeNil{Rcv: &redisVal} err := r.pool.Do(radix.Cmd(&mn, "GET", r.Config.Prefix+key)) - if err != nil { return nil, err } @@ -197,7 +196,6 @@ func (r *RadixDriver) GetAll() (interface{}, error) { var redisVal []interface{} mn := radix.MaybeNil{Rcv: &redisVal} err := r.pool.Do(radix.Cmd(&mn, "SCAN", strconv.Itoa(0))) // 0 -> cursor - if err != nil { return nil, err } diff --git a/sessions/sessiondb/redis/driver_redigo.go b/sessions/sessiondb/redis/driver_redigo.go index 675ba58f..55faab52 100644 --- a/sessions/sessiondb/redis/driver_redigo.go +++ b/sessions/sessiondb/redis/driver_redigo.go @@ -70,7 +70,7 @@ func (r *RedigoDriver) Set(key string, value interface{}, secondsLifetime int64) } // Get returns value, err by its key -//returns nil and a filled error if something bad happened. +// returns nil and a filled error if something bad happened. func (r *RedigoDriver) Get(key string) (interface{}, error) { c := r.pool.Get() defer c.Close() @@ -79,7 +79,6 @@ func (r *RedigoDriver) Get(key string) (interface{}, error) { } redisVal, err := c.Do("GET", r.Config.Prefix+key) - if err != nil { return nil, err } @@ -108,7 +107,6 @@ func (r *RedigoDriver) TTL(key string) (seconds int64, hasExpiration bool, found func (r *RedigoDriver) updateTTLConn(c redis.Conn, key string, newSecondsLifeTime int64) error { reply, err := c.Do("EXPIRE", r.Config.Prefix+key, newSecondsLifeTime) - if err != nil { return err } @@ -175,7 +173,6 @@ func (r *RedigoDriver) GetAll() (interface{}, error) { } redisVal, err := c.Do("SCAN", 0) // 0 -> cursor - if err != nil { return nil, err } @@ -234,7 +231,7 @@ func (r *RedigoDriver) GetKeys(prefix string) ([]string, error) { // GetBytes returns value, err by its key // you can use utils.Deserialize((.GetBytes("yourkey"),&theobject{}) -//returns nil and a filled error if something wrong happens +// returns nil and a filled error if something wrong happens func (r *RedigoDriver) GetBytes(key string) ([]byte, error) { c := r.pool.Get() defer c.Close() @@ -243,7 +240,6 @@ func (r *RedigoDriver) GetBytes(key string) ([]byte, error) { } redisVal, err := c.Do("GET", r.Config.Prefix+key) - if err != nil { return nil, err } diff --git a/typescript/config.go b/typescript/config.go index 187972b4..ba9c359f 100644 --- a/typescript/config.go +++ b/typescript/config.go @@ -105,8 +105,8 @@ func (tsconfig *Tsconfig) CompilerArgs() []string { var valueField string // only if it's string or int we need to put that if valueFieldG.Kind() == reflect.String { - //if valueFieldG.String() != "" { - //valueField = strconv.QuoteToASCII(valueFieldG.String()) + // if valueFieldG.String() != "" { + // valueField = strconv.QuoteToASCII(valueFieldG.String()) // } valueField = valueFieldG.String() } else if valueFieldG.Kind() == reflect.Int { @@ -174,7 +174,6 @@ func DefaultTsconfig() Tsconfig { }, Exclude: []string{"node_modules"}, } - } // DefaultConfig returns the default Options of the Typescript adaptor diff --git a/typescript/editor/editor.go b/typescript/editor/editor.go index 020427f7..090bf493 100644 --- a/typescript/editor/editor.go +++ b/typescript/editor/editor.go @@ -52,10 +52,8 @@ type ( } ) -var ( - // NoOpLogger can be used as the logger argument, it prints nothing. - NoOpLogger = func(string, ...interface{}) {} -) +// NoOpLogger can be used as the logger argument, it prints nothing. +var NoOpLogger = func(string, ...interface{}) {} // New creates and returns an Editor Plugin instance func New(cfg ...Config) *Editor { diff --git a/typescript/npm/exec.go b/typescript/npm/exec.go index d26bf889..cb3d9a3c 100644 --- a/typescript/npm/exec.go +++ b/typescript/npm/exec.go @@ -7,10 +7,8 @@ import ( "strings" ) -var ( - // PathSeparator is the string of os.PathSeparator - PathSeparator = string(os.PathSeparator) -) +// PathSeparator is the string of os.PathSeparator +var PathSeparator = string(os.PathSeparator) type ( // Cmd is a custom struch which 'implements' the *exec.Cmd @@ -24,7 +22,7 @@ type ( // // In typical use, both Path and args are set by calling Command. func (cmd *Cmd) Arguments(args ...string) *Cmd { - cmd.Cmd.Args = append(cmd.Cmd.Args[0:1], args...) //we need the first argument which is the command + cmd.Cmd.Args = append(cmd.Cmd.Args[0:1], args...) // we need the first argument which is the command return cmd } @@ -36,7 +34,7 @@ func (cmd *Cmd) AppendArguments(args ...string) *Cmd { // ResetArguments resets the arguments func (cmd *Cmd) ResetArguments() *Cmd { - cmd.Args = cmd.Args[0:1] //keep only the first because is the command + cmd.Args = cmd.Args[0:1] // keep only the first because is the command return cmd } @@ -58,12 +56,12 @@ func CommandBuilder(command string, args ...string) *Cmd { return &Cmd{Cmd: exec.Command(command, args...)} } -//the below is just for exec.Command: +// the below is just for exec.Command: // Command executes a command in shell and returns it's output, it's block version func Command(command string, a ...string) (output string, err error) { var out []byte - //if no args given, try to get them from the command + // if no args given, try to get them from the command if len(a) == 0 { commandArgs := strings.Split(command, " ") for _, commandArg := range commandArgs { diff --git a/typescript/npm/npm.go b/typescript/npm/npm.go index a6e6e71d..6137e808 100644 --- a/typescript/npm/npm.go +++ b/typescript/npm/npm.go @@ -7,11 +7,9 @@ import ( "time" ) -var ( - // nodeModulesPath is the path of the root npm modules - // Ex: C:\\Users\\iris\\AppData\\Roaming\\npm\\node_modules - nodeModulesPath string -) +// nodeModulesPath is the path of the root npm modules +// Ex: C:\\Users\\iris\\AppData\\Roaming\\npm\\node_modules +var nodeModulesPath string type ( // NodeModuleResult holds Message and Error, if error != nil then the npm command has failed @@ -26,7 +24,7 @@ type ( // NodeModulesPath sets the root directory for the node_modules and returns that func NodeModulesPath() string { if nodeModulesPath == "" { - nodeModulesPath = MustCommand("npm", "root", "-g") //here it ends with \n we have to remove it + nodeModulesPath = MustCommand("npm", "root", "-g") // here it ends with \n we have to remove it nodeModulesPath = nodeModulesPath[0 : len(nodeModulesPath)-1] } return nodeModulesPath @@ -64,11 +62,10 @@ func NodeModuleInstall(moduleName string) NodeModuleResult { case v := <-finish: { if v { - print("\010\010\010") //remove the loading chars + print("\010\010\010") // remove the loading chars close(finish) return } - } default: print("\010\010-") @@ -84,7 +81,6 @@ func NodeModuleInstall(moduleName string) NodeModuleResult { print("|") } } - }() out, err := Command("npm", "install", moduleName, "-g") finish <- true @@ -93,7 +89,6 @@ func NodeModuleInstall(moduleName string) NodeModuleResult { } return success("\n%s installed %s", moduleName, out) - } // NodeModuleUnistall removes a module @@ -103,7 +98,6 @@ func NodeModuleUnistall(moduleName string) NodeModuleResult { return fail("Error unstalling module %s. Trace: %s", moduleName, err.Error()) } return success("\n %s unistalled %s", moduleName, out) - } // NodeModuleAbs returns the absolute path of the global node_modules directory + relative @@ -113,8 +107,8 @@ func NodeModuleAbs(relativePath string) string { // NodeModuleExists returns true if a module exists // here we have two options -//1 . search by command something like npm -ls -g --depth=x -//2. search on files, we choose the second +// 1 . search by command something like npm -ls -g --depth=x +// 2. search on files, we choose the second func NodeModuleExists(execPath string) bool { if !filepath.IsAbs(execPath) { execPath = NodeModuleAbs(execPath) diff --git a/typescript/typescript.go b/typescript/typescript.go index 6e671e6c..705d9926 100644 --- a/typescript/typescript.go +++ b/typescript/typescript.go @@ -32,10 +32,8 @@ func New(cfg ...Config) *Typescript { return &Typescript{Config: &c} } -var ( - // NoOpLogger can be used as the logger argument, it prints nothing. - NoOpLogger = func(string, ...interface{}) {} -) +// NoOpLogger can be used as the logger argument, it prints nothing. +var NoOpLogger = func(string, ...interface{}) {} // Run starts the typescript filewatcher watcher and the typescript compiler. func (t *Typescript) Run(logger func(format string, a ...interface{})) { @@ -68,7 +66,7 @@ func (t *Typescript) Run(logger func(format string, a ...interface{})) { func (t *Typescript) start() { if t.hasTypescriptFiles() { - //Can't check if permission denied returns always exists = true.... + // Can't check if permission denied returns always exists = true.... if !npm.NodeModuleExists(t.Config.Bin) { t.log("installing typescript, please wait...") @@ -85,7 +83,7 @@ func (t *Typescript) start() { watchedProjects := 0 // typescript project (.tsconfig) found for _, project := range projects { - cmd := npm.CommandBuilder("node", t.Config.Bin, "-p", project[0:strings.LastIndex(project, npm.PathSeparator)]) //remove the /tsconfig.json) + cmd := npm.CommandBuilder("node", t.Config.Bin, "-p", project[0:strings.LastIndex(project, npm.PathSeparator)]) // remove the /tsconfig.json) projectConfig, perr := FromFile(project) if perr != nil { t.log("error while trying to read tsconfig: %s", perr.Error()) @@ -114,7 +112,7 @@ func (t *Typescript) start() { } return } - //search for standalone typescript (.ts) files and compile them + // search for standalone typescript (.ts) files and compile them files := t.getTypescriptFiles() if len(files) > 0 { /* watchedFiles := 0 @@ -144,12 +142,11 @@ func (t *Typescript) start() { go func() { compilerMsgB, _ := cmd.Output() compilerMsg := string(compilerMsgB) - cmd.Args = cmd.Args[0 : len(cmd.Args)-1] //remove the last, which is the file + cmd.Args = cmd.Args[0 : len(cmd.Args)-1] // remove the last, which is the file if strings.Contains(compilerMsg, "error") { t.log(compilerMsg) } - }() } @@ -211,7 +208,7 @@ func (t *Typescript) getTypescriptProjects() []string { ignoreFolders := t.getIgnoreFolders() root := t.Config.Dir - //t.logger.Printf("\nSearching for typescript projects in %s", root) + // t.logger.Printf("\nSearching for typescript projects in %s", root) // ignore error filepath.Walk(root, func(path string, fi os.FileInfo, err error) error { @@ -225,7 +222,7 @@ func (t *Typescript) getTypescriptProjects() []string { } if strings.HasSuffix(path, npm.PathSeparator+"tsconfig.json") { - //t.logger.Printf("\nTypescript project found in %s", path) + // t.logger.Printf("\nTypescript project found in %s", path) projects = append(projects, path) } @@ -253,7 +250,7 @@ func (t *Typescript) getTypescriptFiles() []string { } if strings.HasSuffix(path, ".ts") { - //t.logger.Printf("\nTypescript file found in %s", path) + // t.logger.Printf("\nTypescript file found in %s", path) files = append(files, path) } diff --git a/versioning/versioning_test.go b/versioning/versioning_test.go index 4f7d5600..1554b957 100644 --- a/versioning/versioning_test.go +++ b/versioning/versioning_test.go @@ -31,6 +31,7 @@ func TestIf(t *testing.T) { t.Fatalf("expected %s to be %s", "1.2.3", "> 1.2") } } + func TestNewMatcher(t *testing.T) { app := iris.New() diff --git a/view/amber.go b/view/amber.go index 9e040dc5..c295a1d0 100644 --- a/view/amber.go +++ b/view/amber.go @@ -114,7 +114,7 @@ func (s *AmberEngine) loadDirectory() error { funcs[k] = v } - amber.FuncMap = funcs //set the funcs + amber.FuncMap = funcs // set the funcs opt.Ext = extension templates, err := amber.CompileDir(dir, opt, amber.DefaultOptions) // this returns the map with stripped extension, we want extension so we copy the map @@ -154,7 +154,7 @@ func (s *AmberEngine) loadAssets() error { virtualDirectory = virtualDirectory[1:] } } - amber.FuncMap = funcs //set the funcs + amber.FuncMap = funcs // set the funcs names := namesFn() @@ -177,7 +177,6 @@ func (s *AmberEngine) loadAssets() error { name := filepath.ToSlash(rel) tmpl, err := amber.CompileData(buf, name, amber.DefaultOptions) - if err != nil { return err } diff --git a/view/django.go b/view/django.go index 0455e4d7..c814444f 100644 --- a/view/django.go +++ b/view/django.go @@ -199,7 +199,6 @@ func (s *DjangoEngine) RegisterTag(tagName string, fn TagParser) error { // // Returns an error if something bad happens, user is responsible to catch it. func (s *DjangoEngine) Load() error { - if s.assetFn != nil && s.namesFn != nil { // embedded return s.loadAssets() @@ -237,7 +236,6 @@ func (s *DjangoEngine) loadDirectory() (templateErr error) { // them should be treat as normal. // If is a dir, return immediately (dir is not a valid golang template). if info == nil || info.IsDir() { - } else { rel, err := filepath.Rel(dir, path) @@ -272,7 +270,6 @@ func (s *DjangoEngine) loadDirectory() (templateErr error) { // loadAssets loads the templates by binary (go-bindata for embedded). func (s *DjangoEngine) loadAssets() error { - virtualDirectory, virtualExtension := s.directory, s.extension assetFn, namesFn := s.assetFn, s.namesFn diff --git a/view/handlebars.go b/view/handlebars.go index 14f15c18..829f7835 100644 --- a/view/handlebars.go +++ b/view/handlebars.go @@ -118,7 +118,6 @@ func (s *HandlebarsEngine) Load() error { // loadDirectory builds the handlebars templates from directory. func (s *HandlebarsEngine) loadDirectory() error { - // register the global helpers on the first load if len(s.templateCache) == 0 && s.helpers != nil { raymond.RegisterHelpers(s.helpers) @@ -260,7 +259,7 @@ func (s *HandlebarsEngine) ExecuteWriter(w io.Writer, filename string, layout st binding := bindingData if isLayout { var context map[string]interface{} - if m, is := binding.(map[string]interface{}); is { //handlebars accepts maps, + if m, is := binding.(map[string]interface{}); is { // handlebars accepts maps, context = m } else { return fmt.Errorf("Please provide a map[string]interface{} type as the binding instead of the %#v", binding) @@ -279,7 +278,6 @@ func (s *HandlebarsEngine) ExecuteWriter(w io.Writer, filename string, layout st } res, err := tmpl.Exec(binding) - if err != nil { return err } diff --git a/view/html.go b/view/html.go index af01217c..eefacb3d 100644 --- a/view/html.go +++ b/view/html.go @@ -269,10 +269,10 @@ func (s *HTMLEngine) loadDirectory() error { templateErr = err return err } - //s.mu.Lock() + // s.mu.Lock() // Add our funcmaps. _, err = tmpl.Funcs(emptyFuncs).Funcs(s.funcs).Parse(contents) - //s.mu.Unlock() + // s.mu.Unlock() if err != nil { templateErr = err return err @@ -409,10 +409,10 @@ func (s *HTMLEngine) layoutFuncsFor(name string, binding interface{}) { } return "", nil }, - //partial related to current page, - //it would be easier for adding pages' style/script inline - //for example when using partial_r '.script' in layout.html - //templates/users/index.html would load templates/users/index.script.html + // partial related to current page, + // it would be easier for adding pages' style/script inline + // for example when using partial_r '.script' in layout.html + // templates/users/index.html would load templates/users/index.script.html "partial_r": func(partialName string) (template.HTML, error) { ext := filepath.Ext(name) root := name[:len(name)-len(ext)] diff --git a/view/view.go b/view/view.go index 284ebed1..22ea3689 100644 --- a/view/view.go +++ b/view/view.go @@ -37,9 +37,7 @@ func (v *View) Len() int { return len(v.engines) } -var ( - errNoViewEngineForExt = errors.New("no view engine found for '%s'") -) +var errNoViewEngineForExt = errors.New("no view engine found for '%s'") // ExecuteWriter calls the correct view Engine's ExecuteWriter func func (v *View) ExecuteWriter(w io.Writer, filename string, layout string, bindingData interface{}) error {