formatting

Former-commit-id: 037081db5d6d4434e873ca8b75334ee43e046b6a
This commit is contained in:
Gerasimos (Makis) Maropoulos 2019-08-17 10:06:20 +03:00
parent 00967408dc
commit 07046ab978
112 changed files with 477 additions and 517 deletions

View File

@ -13,7 +13,8 @@ func (c *HomeController) GetAbout() mvc.Result {
Name: "about.html", Name: "about.html",
Data: map[string]interface{}{ Data: map[string]interface{}{
"Title": "About Page", "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", Name: "contact.html",
Data: map[string]interface{}{ Data: map[string]interface{}{
"Title": "Contact Page", "Title": "Contact Page",
"Message": "Your application description page."}, "Message": "Your application description page.",
},
} }
} }

View File

@ -179,7 +179,6 @@ var SetState = func(ctx iris.Context) string {
} }
return "state" return "state"
} }
// GetState gets the state returned by the provider during the callback. // 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"), 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"), 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 // does not allow to put custom ports in redirection uri
yahoo.New(os.Getenv("YAHOO_KEY"), os.Getenv("YAHOO_SECRET"), "http://localhost.com"), 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"), 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"), 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"), 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 // By default paypal production auth urls will be used, please set PAYPAL_ENV=sandbox as environment variable for testing
//in sandbox environment // in sandbox environment
paypal.New(os.Getenv("PAYPAL_KEY"), os.Getenv("PAYPAL_SECRET"), "http://localhost:3000/auth/paypal/callback"), 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"), 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"), 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), 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"), 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")), 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"), 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 // start of the router
app.Get("/auth/{provider}/callback", func(ctx iris.Context) { app.Get("/auth/{provider}/callback", func(ctx iris.Context) {
user, err := CompleteUserAuth(ctx) user, err := CompleteUserAuth(ctx)
if err != nil { if err != nil {
ctx.StatusCode(iris.StatusInternalServerError) ctx.StatusCode(iris.StatusInternalServerError)
@ -394,7 +392,6 @@ func main() {
}) })
app.Get("/", func(ctx iris.Context) { app.Get("/", func(ctx iris.Context) {
ctx.ViewData("", providerIndex) ctx.ViewData("", providerIndex)
if err := ctx.View("index.html"); err != nil { if err := ctx.View("index.html"); err != nil {

View File

@ -71,7 +71,6 @@ func TestCasbinWrapper(t *testing.T) {
for _, tt := range ttAdminDeleted { for _, tt := range ttAdminDeleted {
check(e, tt.method, tt.path, tt.username, tt.status) check(e, tt.method, tt.path, tt.username, tt.status)
} }
} }
func check(e *httptest.Expect, method, path, username string, status int) { func check(e *httptest.Expect, method, path, username string, status int) {

View File

@ -57,7 +57,7 @@ func (r resource) loadFromBase(dir string) string {
} }
func TestFileServerBasic(t *testing.T) { func TestFileServerBasic(t *testing.T) {
var urls = []resource{ urls := []resource{
"/static/css/main.css", "/static/css/main.css",
"/static/js/jquery-2.1.1.js", "/static/js/jquery-2.1.1.js",
"/static/favicon.ico", "/static/favicon.ico",

View File

@ -6,7 +6,6 @@ import (
) )
func main() { func main() {
app := iris.New() app := iris.New()
// 1 // 1

View File

@ -45,7 +45,6 @@ func TestListenAddr(t *testing.T) {
if got := log.String(); !strings.Contains(got, expectedMessage) { if got := log.String(); !strings.Contains(got, expectedMessage) {
t.Fatalf("expecting to log to contains the:\n'%s'\ninstead of:\n'%s'", expectedMessage, got) t.Fatalf("expecting to log to contains the:\n'%s'\ninstead of:\n'%s'", expectedMessage, got)
} }
} }
func TestListenAddrWithoutServerErr(t *testing.T) { func TestListenAddrWithoutServerErr(t *testing.T) {

View File

@ -131,7 +131,6 @@ func main() {
// hooks right into validator and you can combine with validation tags and still have a // hooks right into validator and you can combine with validation tags and still have a
// common error output format. // common error output format.
func UserStructLevelValidation(sl validator.StructLevel) { func UserStructLevelValidation(sl validator.StructLevel) {
user := sl.Current().Interface().(User) user := sl.Current().Interface().(User)
if len(user.FirstName) == 0 && len(user.LastName) == 0 { if len(user.FirstName) == 0 && len(user.LastName) == 0 {

View File

@ -32,7 +32,6 @@ type Person struct {
func MyHandler2(ctx iris.Context) { func MyHandler2(ctx iris.Context) {
var persons []Person var persons []Person
err := ctx.ReadJSON(&persons) err := ctx.ReadJSON(&persons)
if err != nil { if err != nil {
ctx.StatusCode(iris.StatusBadRequest) ctx.StatusCode(iris.StatusBadRequest)
ctx.WriteString(err.Error()) ctx.WriteString(err.Error())

View File

@ -20,7 +20,6 @@ func main() {
ctx.WriteString(`The body was empty ctx.WriteString(`The body was empty
or iris.WithoutBodyConsumptionOnUnmarshal option is missing from app.Run. or iris.WithoutBodyConsumptionOnUnmarshal option is missing from app.Run.
Check the terminal window for any queries logs.`) Check the terminal window for any queries logs.`)
} else { } else {
ctx.WriteString("OK body is still:\n") ctx.WriteString("OK body is still:\n")
ctx.Write(body) ctx.Write(body)

View File

@ -20,7 +20,7 @@ func main() {
// Query appends the url query to the Path. // Query appends the url query to the Path.
Query: true, Query: true,
//Columns: true, // Columns: true,
// if !empty then its contents derives from `ctx.Values().Get("logger_message") // if !empty then its contents derives from `ctx.Values().Get("logger_message")
// will be added to the logs. // will be added to the logs.
@ -62,5 +62,4 @@ func main() {
// http://lcoalhost:8080/notfoundhere // http://lcoalhost:8080/notfoundhere
// see the output on the console. // see the output on the console.
app.Run(iris.Addr(":8080"), iris.WithoutServerError(iris.ErrServerClosed)) app.Run(iris.Addr(":8080"), iris.WithoutServerError(iris.ErrServerClosed))
} }

View File

@ -113,7 +113,6 @@ func main() {
// assuming that you have a folder named 'uploads' // assuming that you have a folder named 'uploads'
out, err := os.OpenFile("./uploads/"+fname, out, err := os.OpenFile("./uploads/"+fname,
os.O_WRONLY|os.O_CREATE, 0666) os.O_WRONLY|os.O_CREATE, 0666)
if err != nil { if err != nil {
ctx.StatusCode(iris.StatusInternalServerError) ctx.StatusCode(iris.StatusInternalServerError)
ctx.HTML("Error while uploading: <b>" + err.Error() + "</b>") ctx.HTML("Error while uploading: <b>" + err.Error() + "</b>")

View File

@ -84,7 +84,6 @@ func saveUploadedFile(fh *multipart.FileHeader, destDirectory string) (int64, er
out, err := os.OpenFile(filepath.Join(destDirectory, fh.Filename), out, err := os.OpenFile(filepath.Join(destDirectory, fh.Filename),
os.O_WRONLY|os.O_CREATE, os.FileMode(0666)) os.O_WRONLY|os.O_CREATE, os.FileMode(0666))
if err != nil { if err != nil {
return 0, err return 0, err
} }

View File

@ -74,5 +74,4 @@ func TestContentNegotiation(t *testing.T) {
if expected, got := expectedHTMLResponse, string(rawResponse); expected != got { if expected, got := expectedHTMLResponse, string(rawResponse); expected != got {
t.Fatalf("expected response to be:\n%s but got:\n%s", expected, got) t.Fatalf("expected response to be:\n%s but got:\n%s", expected, got)
} }
} }

View File

@ -14,14 +14,13 @@ import (
// Read more at https://github.com/shiyanhui/hero/hero // Read more at https://github.com/shiyanhui/hero/hero
func main() { func main() {
app := iris.New() app := iris.New()
app.Get("/users", func(ctx iris.Context) { app.Get("/users", func(ctx iris.Context) {
ctx.Gzip(true) ctx.Gzip(true)
ctx.ContentType("text/html") ctx.ContentType("text/html")
var userList = []string{ userList := []string{
"Alice", "Alice",
"Bob", "Bob",
"Tom", "Tom",

View File

@ -37,5 +37,4 @@ func UserList(userList []string, buffer *bytes.Buffer) {
</body> </body>
</html> </html>
`) `)
} }

View File

@ -40,5 +40,4 @@ func UserListToWriter(userList []string, w io.Writer) (int, error) {
</html> </html>
`) `)
return w.Write(_buffer.Bytes()) return w.Write(_buffer.Bytes())
} }

View File

@ -42,7 +42,6 @@ func main() {
s.Publish("messages", &sse.Event{ s.Publish("messages", &sse.Event{
Data: []byte("third message"), Data: []byte("third message"),
}) })
}() // ... }() // ...
app.Run(iris.Addr(":8080"), iris.WithoutServerError(iris.ErrServerClosed)) app.Run(iris.Addr(":8080"), iris.WithoutServerError(iris.ErrServerClosed))

View File

@ -14,11 +14,12 @@ func newApp() *iris.Application {
Languages: map[string]string{ Languages: map[string]string{
"en-US": "./locales/locale_en-US.ini", "en-US": "./locales/locale_en-US.ini",
"el-GR": "./locales/locale_el-GR.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.Use(globalLocale)
app.Get("/", func(ctx iris.Context) { app.Get("/", func(ctx iris.Context) {
// it tries to find the language by: // it tries to find the language by:
// ctx.Values().GetString("language") // ctx.Values().GetString("language")
// if that was empty then // if that was empty then
@ -47,7 +48,9 @@ func newApp() *iris.Application {
URLParameter: "lang", URLParameter: "lang",
Languages: map[string]string{ Languages: map[string]string{
"en-US": "./locales/locale_multi_first_en-US.ini, ./locales/locale_multi_second_en-US.ini", "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) { app.Get("/multi", multiLocale, func(ctx iris.Context) {
language := ctx.Values().GetString(ctx.Application().ConfigurationReadOnly().GetTranslateLanguageContextKey()) language := ctx.Values().GetString(ctx.Application().ConfigurationReadOnly().GetTranslateLanguageContextKey())

View File

@ -45,5 +45,4 @@ func TestI18n(t *testing.T) {
Body().Equal(elgrMulti) Body().Equal(elgrMulti)
e.GET("/multi").WithQueryString("lang=en-US").Expect().Status(httptest.StatusOK). e.GET("/multi").WithQueryString("lang=en-US").Expect().Status(httptest.StatusOK).
Body().Equal(enusMulti) Body().Equal(enusMulti)
} }

View File

@ -96,7 +96,6 @@ func (c *UserController) PostRegister() mvc.Result {
// but it's good to know you can set a custom code; // but it's good to know you can set a custom code;
// Code: 303, // Code: 303,
} }
} }
var loginStaticView = mvc.View{ var loginStaticView = mvc.View{

View File

@ -71,7 +71,6 @@ func newApp() *iris.Application {
// Pssst, don't forget dynamic-path example for more "magic"! // Pssst, don't forget dynamic-path example for more "magic"!
app.Get("/api/users/{userid:uint64 min(1)}", func(ctx iris.Context) { app.Get("/api/users/{userid:uint64 min(1)}", func(ctx iris.Context) {
userID, err := ctx.Params().GetUint64("userid") userID, err := ctx.Params().GetUint64("userid")
if err != nil { if err != nil {
ctx.Writef("error while trying to parse userid parameter," + 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.") "this will never happen if :uint64 is being used because if it's not a valid uint64 it will fire Not Found automatically.")

View File

@ -85,5 +85,4 @@ func TestRoutingBasic(t *testing.T) {
e.Request("GET", "/").WithURL("http://any-subdomain-here.example.com").Expect().Status(httptest.StatusOK). e.Request("GET", "/").WithURL("http://any-subdomain-here.example.com").Expect().Status(httptest.StatusOK).
Body().Equal(expectedSubdomainWildcardIndexResponse) Body().Equal(expectedSubdomainWildcardIndexResponse)
} }

View File

@ -11,7 +11,6 @@ import (
// You can use the .WrapRouter to add custom logic when or when not the router should // 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. // be executed in order to execute the registered routes' handlers.
func newApp() *iris.Application { func newApp() *iris.Application {
app := iris.New() app := iris.New()
app.OnErrorCode(iris.StatusNotFound, func(ctx iris.Context) { app.OnErrorCode(iris.StatusNotFound, func(ctx iris.Context) {

View File

@ -75,7 +75,7 @@ func TestRouting(t *testing.T) {
app := newApp() app := newApp()
e := httptest.New(t, app) e := httptest.New(t, app)
var tests = []troute{ tests := []troute{
// GET // GET
newTroute("GET", "", "/healthcheck", httptest.StatusOK), newTroute("GET", "", "/healthcheck", httptest.StatusOK),
newTroute("GET", "", "/games/{gameID}/clans", httptest.StatusOK, "gameID", "42"), newTroute("GET", "", "/games/{gameID}/clans", httptest.StatusOK, "gameID", "42"),

View File

@ -36,5 +36,4 @@ func main() {
// See view/template_html_4 example for more reverse routing examples // See view/template_html_4 example for more reverse routing examples
// using the reverse router component and the {{url}} and {{urlpath}} template functions. // using the reverse router component and the {{url}} and {{urlpath}} template functions.
app.Run(iris.Addr(":8080")) app.Run(iris.Addr(":8080"))
} }

View File

@ -16,7 +16,6 @@ func main() {
}) })
app.Get("/change", func(ctx iris.Context) { app.Get("/change", func(ctx iris.Context) {
if none.IsOnline() { if none.IsOnline() {
none.Method = iris.MethodNone none.Method = iris.MethodNone
} else { } else {

View File

@ -41,10 +41,10 @@ func main() {
}) })
app.Get("/set", func(ctx iris.Context) { app.Get("/set", func(ctx iris.Context) {
s := sess.Start(ctx) s := sess.Start(ctx)
//set session values // set session values
s.Set("name", "iris") 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")) 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) { 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) sess.Destroy(ctx)
}) })

View File

@ -42,10 +42,10 @@ func main() {
}) })
app.Get("/set", func(ctx iris.Context) { app.Get("/set", func(ctx iris.Context) {
s := sess.Start(ctx) s := sess.Start(ctx)
//set session values // set session values
s.Set("name", "iris") 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")) 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) { 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) sess.Destroy(ctx)
}) })

View File

@ -60,10 +60,10 @@ func main() {
}) })
app.Get("/set", func(ctx iris.Context) { app.Get("/set", func(ctx iris.Context) {
s := sess.Start(ctx) s := sess.Start(ctx)
//set session values // set session values
s.Set("name", "iris") 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")) 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) { 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) sess.Destroy(ctx)
}) })

View File

@ -46,12 +46,12 @@ func main() {
ctx.HTML("</ul>") ctx.HTML("</ul>")
}) })
//set session values. // set session values.
app.Get("/set", func(ctx iris.Context) { app.Get("/set", func(ctx iris.Context) {
session := sessions.Get(ctx) session := sessions.Get(ctx)
session.Set("name", "iris") session.Set("name", "iris")
//test if set here. // test if set here.
ctx.Writef("All ok session set to: %s", session.GetString("name")) ctx.Writef("All ok session set to: %s", session.GetString("name"))
// Set will set the value as-it-is, // Set will set the value as-it-is,
@ -97,7 +97,7 @@ func main() {
}) })
app.Get("/destroy", func(ctx iris.Context) { 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) // sess.Destroy(ctx)
// or // or
sessions.Get(ctx).Destroy() sessions.Get(ctx).Destroy()
@ -123,7 +123,6 @@ func main() {
// try to change it, if we used `Set` instead of `SetImmutable` this // 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. // change will affect the underline array of the session's value "businessEdit", but now it will not.
businessGet[0].Name = "Gabriel" businessGet[0].Name = "Gabriel"
}) })
app.Get("/get_immutable", func(ctx iris.Context) { app.Get("/get_immutable", func(ctx iris.Context) {

View File

@ -12,7 +12,6 @@ var (
) )
func secret(ctx iris.Context) { func secret(ctx iris.Context) {
// Check if user is authenticated // Check if user is authenticated
if auth, _ := sess.Start(ctx).GetBoolean("authenticated"); !auth { if auth, _ := sess.Start(ctx).GetBoolean("authenticated"); !auth {
ctx.StatusCode(iris.StatusForbidden) ctx.StatusCode(iris.StatusForbidden)

View File

@ -34,12 +34,11 @@ func newApp() *iris.Application {
ctx.Writef("You should navigate to the /set, /get, /delete, /clear,/destroy instead") ctx.Writef("You should navigate to the /set, /get, /delete, /clear,/destroy instead")
}) })
app.Get("/set", func(ctx iris.Context) { app.Get("/set", func(ctx iris.Context) {
// set session values
//set session values
s := mySessions.Start(ctx) s := mySessions.Start(ctx)
s.Set("name", "iris") s.Set("name", "iris")
//test if set here // test if set here
ctx.Writef("All ok session set to: %s", s.GetString("name")) 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) { 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) mySessions.Destroy(ctx)
}) })
// Note about destroy: // Note about destroy:

View File

@ -26,5 +26,4 @@ func TestSubdomainRedirectWWW(t *testing.T) {
for _, test := range tests { for _, test := range tests {
e.GET(test.path).Expect().Status(httptest.StatusOK).Body().Equal(test.response) e.GET(test.path).Expect().Status(httptest.StatusOK).Body().Equal(test.response)
} }
} }

View File

@ -54,5 +54,4 @@ func TestSubdomainWWW(t *testing.T) {
Status(httptest.StatusOK). Status(httptest.StatusOK).
Body().Equal(test.response()) Body().Equal(test.response())
} }
} }

View File

@ -27,5 +27,4 @@ func TestNewApp(t *testing.T) {
// with invalid basic auth // with invalid basic auth
e.GET("/admin/settings").WithBasicAuth("invalidusername", "invalidpassword"). e.GET("/admin/settings").WithBasicAuth("invalidusername", "invalidpassword").
Expect().Status(httptest.StatusUnauthorized) Expect().Status(httptest.StatusUnauthorized)
} }

View File

@ -375,5 +375,4 @@ func getTopicConsumeSSEHandler(ctx iris.Context) {
flusher.Flush() flusher.Flush()
} }
} }
} }

View File

@ -32,7 +32,6 @@ type uploadedFiles struct {
} }
func scanUploads(dir string) *uploadedFiles { func scanUploads(dir string) *uploadedFiles {
f := new(uploadedFiles) f := new(uploadedFiles)
lindex := dir[len(dir)-1] lindex := dir[len(dir)-1]
@ -54,7 +53,6 @@ func scanUploads(dir string) *uploadedFiles {
func (f *uploadedFiles) scan(dir string) { func (f *uploadedFiles) scan(dir string) {
f.dir = dir f.dir = dir
filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { 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 it's directory or a thumbnail we saved earlier, skip it.
if info.IsDir() || strings.HasPrefix(info.Name(), "thumbnail_") { if info.IsDir() || strings.HasPrefix(info.Name(), "thumbnail_") {
return nil return nil
@ -117,7 +115,6 @@ func (f *uploadedFiles) createThumbnail(uf uploadedFile) {
png.Encode(out, resized) png.Encode(out, resized)
} }
// and so on... you got the point, this code can be simplify, as a practise. // and so on... you got the point, this code can be simplify, as a practise.
} }
func main() { func main() {
@ -152,7 +149,6 @@ func main() {
// assuming that you have a folder named 'uploads' // assuming that you have a folder named 'uploads'
out, err := os.OpenFile(uploadsDir+fname, out, err := os.OpenFile(uploadsDir+fname,
os.O_WRONLY|os.O_CREATE, 0666) os.O_WRONLY|os.O_CREATE, 0666)
if err != nil { if err != nil {
ctx.StatusCode(iris.StatusInternalServerError) ctx.StatusCode(iris.StatusInternalServerError)
ctx.Application().Logger().Warnf("Error while preparing the new file: %v", err.Error()) ctx.Application().Logger().Warnf("Error while preparing the new file: %v", err.Error())

View File

@ -26,7 +26,7 @@ import (
const version = "0.0.1" const version = "0.0.1"
func init() { func init() {
var envFileName = ".env" envFileName := ".env"
flagset := flag.CommandLine flagset := flag.CommandLine
flagset.StringVar(&envFileName, "env", envFileName, "the env file which web app will use to extract its environment variables") flagset.StringVar(&envFileName, "env", envFileName, "the env file which web app will use to extract its environment variables")

View File

@ -99,7 +99,6 @@ func newApp(db *DB) *iris.Application {
ctx.ViewData("FORM_RESULT", ctx.ViewData("FORM_RESULT",
template.HTML("<pre><a target='_new' href='"+shortenURL+"'>"+shortenURL+" </a></pre>")) template.HTML("<pre><a target='_new' href='"+shortenURL+"'>"+shortenURL+" </a></pre>"))
} }
} }
} }

View File

@ -73,5 +73,4 @@ func TestURLShortener(t *testing.T) {
} }
time.Sleep(1 * time.Second) time.Sleep(1 * time.Second)
} }

View File

@ -20,9 +20,7 @@ type Store interface {
Close() // release the store or ignore Close() // release the store or ignore
} }
var ( var tableURLs = []byte("urls")
tableURLs = []byte("urls")
)
// DB representation of a Store. // DB representation of a Store.
// Only one table/bucket which contains the urls, so it's not a fully Database, // 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 // create the buckets here
var tables = [...][]byte{ tables := [...][]byte{
tableURLs, tableURLs,
} }
@ -160,7 +158,6 @@ func (d *DB) GetByValue(value string) (keys []string) {
// Len returns all the "shorted" urls length // Len returns all the "shorted" urls length
func (d *DB) Len() (num int) { func (d *DB) Len() (num int) {
d.db.View(func(tx *bolt.Tx) error { d.db.View(func(tx *bolt.Tx) error {
// Assume bucket exists and has keys // Assume bucket exists and has keys
b := tx.Bucket(tableURLs) b := tx.Bucket(tableURLs)
if b == nil { if b == nil {

View File

@ -14,11 +14,9 @@ func main() {
// - {{ current }} // - {{ current }}
app.RegisterView(iris.HTML("./templates", ".html")) app.RegisterView(iris.HTML("./templates", ".html"))
app.Get("/", func(ctx iris.Context) { app.Get("/", func(ctx iris.Context) {
ctx.ViewData("Name", "iris") // the .Name inside the ./templates/hi.html ctx.ViewData("Name", "iris") // the .Name inside the ./templates/hi.html
ctx.Gzip(true) // enable gzip for big files ctx.Gzip(true) // enable gzip for big files
ctx.View("hi.html") // render the template with the file name relative to the './templates' ctx.View("hi.html") // render the template with the file name relative to the './templates'
}) })
// http://localhost:8080/ // http://localhost:8080/

View File

@ -59,7 +59,6 @@ func main() {
// http://localhost:8080 // http://localhost:8080
// http://localhost:8080/redirect/my-page1 // http://localhost:8080/redirect/my-page1
app.Run(iris.Addr(":8080")) app.Run(iris.Addr(":8080"))
} }
func writePathHandler(ctx iris.Context) { func writePathHandler(ctx iris.Context) {

View File

@ -91,7 +91,7 @@ func main() {
}) })
app.RegisterView(tmpl) // <-- 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-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-2": {Text: "Add an add todo page to the example project"},
"example-todo-3": {Text: "Add an update todo page to the example project"}, "example-todo-3": {Text: "Add an update todo page to the example project"},

View File

@ -25,5 +25,4 @@ func index(ctx iris.Context) {
// Q: why need extension .pug? // Q: why need extension .pug?
// A: Because you can register more than one view engine per Iris application. // A: Because you can register more than one view engine per Iris application.
ctx.View("index.pug") ctx.View("index.pug")
} }

View File

@ -34,7 +34,6 @@ func main() {
RefTitle: "Iris web framework", RefTitle: "Iris web framework",
RefLink: "https://iris-go.com", RefLink: "https://iris-go.com",
}) })
if err != nil { if err != nil {
app.Logger().Errorf("error from app.View: %v", err) app.Logger().Errorf("error from app.View: %v", err)
} }

View File

@ -76,6 +76,7 @@ func TestCache304(t *testing.T) {
r = e.GET("/").Expect().Status(httptest.StatusOK) r = e.GET("/").Expect().Status(httptest.StatusOK)
r.Body().Equal("send") r.Body().Equal("send")
} }
func TestETag(t *testing.T) { func TestETag(t *testing.T) {
t.Parallel() t.Parallel()

3
cache/cache_test.go vendored
View File

@ -104,7 +104,6 @@ func TestClientNoCache(t *testing.T) {
if err := runTest(e, "/", &n, expectedBodyStr, "/nocache"); err != nil { if err := runTest(e, "/", &n, expectedBodyStr, "/nocache"); err != nil {
t.Fatalf(t.Name()+": %v", err) t.Fatalf(t.Name()+": %v", err)
} }
} }
func TestCache(t *testing.T) { func TestCache(t *testing.T) {
@ -136,7 +135,6 @@ func TestCache(t *testing.T) {
if err := runTest(e, "/other", &n2, expectedBodyStr2, ""); err != nil { if err := runTest(e, "/other", &n2, expectedBodyStr2, ""); err != nil {
t.Fatalf(t.Name()+" other: %v", err) t.Fatalf(t.Name()+" other: %v", err)
} }
} }
func TestCacheHandlerParallel(t *testing.T) { func TestCacheHandlerParallel(t *testing.T) {
@ -185,7 +183,6 @@ func TestCacheValidator(t *testing.T) {
atomic.AddUint32(&n, 1) atomic.AddUint32(&n, 1)
ctx.Header("DONT", "DO not cache that response even if it was claimed") ctx.Header("DONT", "DO not cache that response even if it was claimed")
ctx.Write([]byte(expectedBodyStr)) ctx.Write([]byte(expectedBodyStr))
}) })
e := httptest.New(t, app) e := httptest.New(t, app)

View File

@ -168,5 +168,4 @@ func (h *Handler) ServeHTTP(ctx context.Context) {
// fmt.Printf("key: %s\n", key) // fmt.Printf("key: %s\n", key)
// fmt.Printf("write content type: %s\n", response.Headers()["ContentType"]) // fmt.Printf("write content type: %s\n", response.Headers()["ContentType"])
// fmt.Printf("write body len: %d\n", len(response.Body())) // fmt.Printf("write body len: %d\n", len(response.Body()))
} }

View File

@ -36,7 +36,6 @@ func Chained(rule Rule, next ...Rule) Rule {
} }
return c return c
} }
// Claim validator // Claim validator

View File

@ -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 // to re-set the response with the new handler's content result
func (e *Entry) Reset(statusCode int, headers map[string][]string, func (e *Entry) Reset(statusCode int, headers map[string][]string,
body []byte, lifeChanger LifeChanger) { body []byte, lifeChanger LifeChanger) {
if e.response == nil { if e.response == nil {
e.response = &Response{} e.response = &Response{}
} }

View File

@ -71,7 +71,6 @@ func (r URIBuilder) String() string {
} }
func (r URIBuilder) build() string { func (r URIBuilder) build() string {
remoteURL := r.serverAddr 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) // fasthttp appends the "/" in the last uri (with query args also, that's probably a fasthttp bug which I'll fix later)

View File

@ -223,7 +223,6 @@ Other:
if expected, got := "Iris: https://github.com/kataras/iris", c.Other["MyServerName"]; expected != got { 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) t.Fatalf("error on TestConfigurationYAML: Expected Other['MyServerName'] %s but got %s", expected, got)
} }
} }
func TestConfigurationTOML(t *testing.T) { func TestConfigurationTOML(t *testing.T) {

View File

@ -2110,9 +2110,7 @@ func GetForm(r *http.Request, postMaxMemory int64, resetBody bool) (form map[str
} }
} }
var ( var bodyCopy []byte
bodyCopy []byte
)
if resetBody { if resetBody {
// on POST, PUT and PATCH it will read the form values from request body otherwise from URL queries. // 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), out, err := os.OpenFile(filepath.Join(destDirectory, fh.Filename),
os.O_WRONLY|os.O_CREATE, os.FileMode(0666)) os.O_WRONLY|os.O_CREATE, os.FileMode(0666))
if err != nil { if err != nil {
return 0, err 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 // Example: https://github.com/kataras/iris/blob/master/_examples/http_request/read-json/main.go
func (ctx *context) ReadJSON(outPtr interface{}) error { func (ctx *context) ReadJSON(outPtr interface{}) error {
var unmarshaler = json.Unmarshal unmarshaler := json.Unmarshal
if ctx.shouldOptimize() { if ctx.shouldOptimize() {
unmarshaler = jsoniter.Unmarshal unmarshaler = jsoniter.Unmarshal
} }
@ -2814,9 +2811,7 @@ func (ctx *context) ClientSupportsGzip() bool {
return false return false
} }
var ( var errClientDoesNotSupportGzip = errors.New("client doesn't support gzip compression")
errClientDoesNotSupportGzip = errors.New("client doesn't support gzip compression")
)
// WriteGzip accepts bytes, which are compressed to gzip format and sent to the client. // 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) // 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 options.StreamingJSON {
if ctx.shouldOptimize() { if ctx.shouldOptimize() {
var jsoniterConfig = jsoniter.Config{ jsoniterConfig := jsoniter.Config{
EscapeHTML: !options.UnescapeHTML, EscapeHTML: !options.UnescapeHTML,
IndentionStep: 4, IndentionStep: 4,
}.Froze() }.Froze()
@ -3194,9 +3189,7 @@ func (ctx *context) JSON(v interface{}, opts ...JSON) (n int, err error) {
return n, err return n, err
} }
var ( var finishCallbackB = []byte(");")
finishCallbackB = []byte(");")
)
// WriteJSONP marshals the given interface object and writes the JSON response to the writer. // 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) { func WriteJSONP(writer io.Writer, v interface{}, options JSONP, enableOptimization ...bool) (int, error) {
@ -4081,9 +4074,7 @@ func (n *NegotiationAcceptBuilder) EncodingGzip() *NegotiationAcceptBuilder {
// | Serve files | // | Serve files |
// +------------------------------------------------------------+ // +------------------------------------------------------------+
var ( var errServeContent = errors.New("while trying to serve content to the client. Trace %s")
errServeContent = errors.New("while trying to serve content to the client. Trace %s")
)
// ServeContent serves content, headers are autoset // ServeContent serves content, headers are autoset
// receives three parameters, it's low-level function, instead you can use .ServeFile(string,bool)/SendFile(string,string) // 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, // when the response writer is recording the status code, body, headers and so on,
// else returns nil and false. // else returns nil and false.
func (ctx *context) IsRecording() (*ResponseRecorder, bool) { func (ctx *context) IsRecording() (*ResponseRecorder, bool) {
//NOTE: // NOTE:
// two return values in order to minimize the if statement: // two return values in order to minimize the if statement:
// if (Recording) then writer = Recorder() // if (Recording) then writer = Recorder()
// instead we do: recorder,ok = Recording() // 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) // 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 // this is tricky but nessecery if we want ctx.FireStatusCode to work inside transactions
t.Context().ResetResponseWriter(ctx.writer) t.Context().ResetResponseWriter(ctx.writer)
}() }()
// run the worker with its context clone inside. // run the worker with its context clone inside.

View File

@ -133,7 +133,6 @@ func (w *GzipResponseWriter) WriteString(s string) (n int, err error) {
if w.ResponseWriter.Header()[ContentTypeHeaderKey] == nil { if w.ResponseWriter.Header()[ContentTypeHeaderKey] == nil {
w.ResponseWriter.Header().Set(ContentTypeHeaderKey, ContentTextHeaderValue) w.ResponseWriter.Header().Set(ContentTypeHeaderKey, ContentTextHeaderValue)
} }
} }
return return
} }

View File

@ -89,124 +89,122 @@ func (r RequestParams) GetIntUnslashed(key string) (int, bool) {
return -1, false return -1, false
} }
var ( // ParamResolvers is the global param resolution for a parameter type for a specific go std or custom type.
// 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.
// Key is the specific type, which should be unique. // The value is a function which accepts the parameter index
// The value is a function which accepts the parameter index // and it should return the value as the parameter type evaluator expects it.
// and it should return the value as the parameter type evaluator expects it. // i.e [reflect.TypeOf("string")] = func(paramIndex int) interface{} {
// i.e [reflect.TypeOf("string")] = func(paramIndex int) interface{} { // return func(ctx Context) <T> {
// return func(ctx Context) <T> { // return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(<T>)
// return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(<T>) // }
// } // }
// } //
// // Read https://github.com/kataras/iris/tree/master/_examples/routing/macros for more details.
// Read https://github.com/kataras/iris/tree/master/_examples/routing/macros for more details. // Checks for total available request parameters length
// Checks for total available request parameters length // and parameter index based on the hero/mvc function added
// and parameter index based on the hero/mvc function added // in order to support the MVC.HandleMany("GET", "/path/{ps}/{pssecond} /path/{ps}")
// in order to support the MVC.HandleMany("GET", "/path/{ps}/{pssecond} /path/{ps}") // when on the second requested path, the 'pssecond' should be empty.
// when on the second requested path, the 'pssecond' should be empty. var ParamResolvers = map[reflect.Type]func(paramIndex int) interface{}{
ParamResolvers = map[reflect.Type]func(paramIndex int) interface{}{ reflect.TypeOf(""): func(paramIndex int) interface{} {
reflect.TypeOf(""): func(paramIndex int) interface{} { return func(ctx Context) string {
return func(ctx Context) string { if ctx.Params().Len() <= paramIndex {
if ctx.Params().Len() <= paramIndex { return ""
return ""
}
return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(string)
} }
}, 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 { reflect.TypeOf(int(1)): func(paramIndex int) interface{} {
return 0 return func(ctx Context) int {
} if ctx.Params().Len() <= paramIndex {
// v, _ := ctx.Params().GetEntryAt(paramIndex).IntDefault(0) return 0
// return v
return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(int)
} }
}, // v, _ := ctx.Params().GetEntryAt(paramIndex).IntDefault(0)
reflect.TypeOf(int8(1)): func(paramIndex int) interface{} { // return v
return func(ctx Context) int8 { return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(int)
if ctx.Params().Len() <= paramIndex { }
return 0 },
} reflect.TypeOf(int8(1)): func(paramIndex int) interface{} {
return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(int8) return func(ctx Context) int8 {
if ctx.Params().Len() <= paramIndex {
return 0
} }
}, 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 { reflect.TypeOf(int16(1)): func(paramIndex int) interface{} {
return 0 return func(ctx Context) int16 {
} if ctx.Params().Len() <= paramIndex {
return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(int16) return 0
} }
}, 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 { reflect.TypeOf(int32(1)): func(paramIndex int) interface{} {
return 0 return func(ctx Context) int32 {
} if ctx.Params().Len() <= paramIndex {
return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(int32) return 0
} }
}, 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 { reflect.TypeOf(int64(1)): func(paramIndex int) interface{} {
return 0 return func(ctx Context) int64 {
} if ctx.Params().Len() <= paramIndex {
return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(int64) return 0
} }
}, 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 { reflect.TypeOf(uint(1)): func(paramIndex int) interface{} {
return 0 return func(ctx Context) uint {
} if ctx.Params().Len() <= paramIndex {
return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(uint) return 0
} }
}, 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 { reflect.TypeOf(uint8(1)): func(paramIndex int) interface{} {
return 0 return func(ctx Context) uint8 {
} if ctx.Params().Len() <= paramIndex {
return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(uint8) return 0
} }
}, 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 { reflect.TypeOf(uint16(1)): func(paramIndex int) interface{} {
return 0 return func(ctx Context) uint16 {
} if ctx.Params().Len() <= paramIndex {
return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(uint16) return 0
} }
}, 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 { reflect.TypeOf(uint32(1)): func(paramIndex int) interface{} {
return 0 return func(ctx Context) uint32 {
} if ctx.Params().Len() <= paramIndex {
return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(uint32) return 0
} }
}, 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 { reflect.TypeOf(uint64(1)): func(paramIndex int) interface{} {
return 0 return func(ctx Context) uint64 {
} if ctx.Params().Len() <= paramIndex {
return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(uint64) return 0
} }
}, return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(uint64)
reflect.TypeOf(true): func(paramIndex int) interface{} { }
return func(ctx Context) bool { },
if ctx.Params().Len() <= paramIndex { reflect.TypeOf(true): func(paramIndex int) interface{} {
return false return func(ctx Context) bool {
} if ctx.Params().Len() <= paramIndex {
return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(bool) 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 // 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. // and the parameter's index based on the registered path.

View File

@ -188,7 +188,6 @@ func (w *ResponseRecorder) Clone() ResponseWriter {
// WriteTo writes a response writer (temp: status code, headers and body) to another response writer // WriteTo writes a response writer (temp: status code, headers and body) to another response writer
func (w *ResponseRecorder) WriteTo(res ResponseWriter) { func (w *ResponseRecorder) WriteTo(res ResponseWriter) {
if to, ok := res.(*ResponseRecorder); ok { if to, ok := res.(*ResponseRecorder); ok {
// set the status code, to is first ( probably an error? (context.StatusCodeNotSuccessful, defaults to < 200 || >= 400). // set the status code, to is first ( probably an error? (context.StatusCodeNotSuccessful, defaults to < 200 || >= 400).

View File

@ -298,7 +298,6 @@ func (w *responseWriter) WriteTo(to ResponseWriter) {
} }
} }
} }
} }
// the body is not copied, this writer doesn't support recording // the body is not copied, this writer doesn't support recording
} }

View File

@ -8,10 +8,8 @@ import (
"github.com/iris-contrib/go.uuid" "github.com/iris-contrib/go.uuid"
) )
var ( // Prefix the error prefix, applies to each error's message.
// Prefix the error prefix, applies to each error's message. var Prefix = ""
Prefix = ""
)
// Error holds the error message, this message never really changes // Error holds the error message, this message never really changes
type Error struct { type Error struct {

View File

@ -14,7 +14,6 @@ var userMail = "user1@mail.go"
var expectedUserAlreadyExists = "User with mail: user1@mail.go already exists" var expectedUserAlreadyExists = "User with mail: user1@mail.go already exists"
func ExampleError() { func ExampleError() {
fmt.Print(errUserAlreadyExists.Format(userMail).Append("Please change your mail addr")) fmt.Print(errUserAlreadyExists.Format(userMail).Append("Please change your mail addr"))
// Output: // Output:
@ -38,7 +37,6 @@ func TestFormat(t *testing.T) {
} }
func TestAppendErr(t *testing.T) { func TestAppendErr(t *testing.T) {
errChangeMailMsg := "Please change your mail addr" errChangeMailMsg := "Please change your mail addr"
errChangeMail := fmt.Errorf(errChangeMailMsg) // test go standard error errChangeMail := fmt.Errorf(errChangeMailMsg) // test go standard error
errAppended := errUserAlreadyExists.AppendErr(errChangeMail) errAppended := errUserAlreadyExists.AppendErr(errChangeMail)

View File

@ -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. // 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 { func (r *Reporter) Add(format string, a ...interface{}) bool {
if format == "" && len(a) == 0 { if format == "" && len(a) == 0 {
return false return false
} }

View File

@ -26,7 +26,7 @@ func FromStd(handler interface{}) context.Handler {
case context.Handler: case context.Handler:
{ {
// //
//it's already a iris handler // it's already a iris handler
// //
return handler.(context.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 // FromStdWithNext receives a standar handler - middleware form - and returns a

View File

@ -36,7 +36,6 @@ func TestFromStd(t *testing.T) {
} }
func TestFromStdWithNext(t *testing.T) { func TestFromStdWithNext(t *testing.T) {
basicauth := "secret" basicauth := "secret"
passed := "ok" passed := "ok"

View File

@ -76,7 +76,6 @@ func (m myTestTask) OnServe(host TaskHost) {
time.AfterFunc(startDelay, func() { time.AfterFunc(startDelay, func() {
m.logger.Println("restart") m.logger.Println("restart")
host.Serve() // restart host.Serve() // restart
}) })
} }

View File

@ -20,7 +20,6 @@ const (
) )
func newTester(t *testing.T, baseURL string, handler http.Handler) *httpexpect.Expect { func newTester(t *testing.T, baseURL string, handler http.Handler) *httpexpect.Expect {
var transporter http.RoundTripper var transporter http.RoundTripper
if strings.HasPrefix(baseURL, "http") { // means we are testing real serve time 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 // http routing
var (
expectedBody = "this is the response body\n" expectedBody := "this is the response body\n"
)
mux := http.NewServeMux() mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { 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) t.Fatalf("expected hello Task's message to be '%s' but got '%s'", expectedHelloMessage, got)
} }
} }
func TestSupervisor(t *testing.T) { func TestSupervisor(t *testing.T) {
testSupervisor(t, func(srv *http.Server, tasks []func(TaskHost)) *Supervisor { testSupervisor(t, func(srv *http.Server, tasks []func(TaskHost)) *Supervisor {
su := New(srv) su := New(srv)

View File

@ -30,7 +30,6 @@ var IsLoopbackSubdomain = func(s string) bool {
if !strings.Contains(machineHostname, ".") { // if machine name's is not a loopback by itself if !strings.Contains(machineHostname, ".") { // if machine name's is not a loopback by itself
valid = s == machineHostname valid = s == machineHostname
} }
} }
return valid return valid
} }
@ -96,10 +95,8 @@ const (
defaultServerPort = 8080 defaultServerPort = 8080
) )
var ( // defaultServerAddr the default server addr which is: localhost:8080
// defaultServerAddr the default server addr which is: localhost:8080 var defaultServerAddr = defaultServerHostname + ":" + strconv.Itoa(defaultServerPort)
defaultServerAddr = defaultServerHostname + ":" + strconv.Itoa(defaultServerPort)
)
// ResolveAddr tries to convert a given string to an address which is compatible with net.Listener and server // ResolveAddr tries to convert a given string to an address which is compatible with net.Listener and server
func ResolveAddr(addr string) string { func ResolveAddr(addr string) string {

View File

@ -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. // TLS returns a new TLS Listener and an error on failure.
func TLS(addr, certFile, keyFile string) (net.Listener, error) { func TLS(addr, certFile, keyFile string) (net.Listener, error) {
if certFile == "" || keyFile == "" { if certFile == "" || keyFile == "" {
return nil, errCertKeyMissing return nil, errCertKeyMissing
} }

View File

@ -17,22 +17,20 @@ import (
// to store the "offline" routes. // to store the "offline" routes.
const MethodNone = "NONE" const MethodNone = "NONE"
var ( // AllMethods contains the valid http methods:
// AllMethods contains the valid http methods: // "GET", "POST", "PUT", "DELETE", "CONNECT", "HEAD",
// "GET", "POST", "PUT", "DELETE", "CONNECT", "HEAD", // "PATCH", "OPTIONS", "TRACE".
// "PATCH", "OPTIONS", "TRACE". var AllMethods = []string{
AllMethods = []string{ http.MethodGet,
http.MethodGet, http.MethodPost,
http.MethodPost, http.MethodPut,
http.MethodPut, http.MethodDelete,
http.MethodDelete, http.MethodConnect,
http.MethodConnect, http.MethodHead,
http.MethodHead, http.MethodPatch,
http.MethodPatch, http.MethodOptions,
http.MethodOptions, http.MethodTrace,
http.MethodTrace, }
}
)
// repository passed to all parties(subrouters), it's the object witch keeps // repository passed to all parties(subrouters), it's the object witch keeps
// all the routes. // all the routes.
@ -403,7 +401,6 @@ func (api *APIBuilder) HandleMany(methodOrMulti string, relativePathorMulti stri
} }
routes = append(routes, api.Handle(method, p, handlers...)) routes = append(routes, api.Handle(method, p, handlers...))
} }
} }
} }
return return
@ -433,7 +430,6 @@ func (api *APIBuilder) HandleDir(requestPath, directory string, opts ...DirOptio
// and we need that path to call the `StripPrefix`. // and we need that path to call the `StripPrefix`.
if _, fullpath := splitSubdomainAndPath(joinPath(api.relativePath, requestPath)); fullpath != "/" { if _, fullpath := splitSubdomainAndPath(joinPath(api.relativePath, requestPath)); fullpath != "/" {
h = StripPrefix(fullpath, h) h = StripPrefix(fullpath, h)
} }
requestPath = joinPath(requestPath, WildcardFileParam()) requestPath = joinPath(requestPath, WildcardFileParam())

View File

@ -179,7 +179,6 @@ func (h *routerHandler) HandleRequest(ctx context.Context) {
method := ctx.Method() method := ctx.Method()
path := ctx.Path() path := ctx.Path()
if !ctx.Application().ConfigurationReadOnly().GetDisablePathCorrection() { if !ctx.Application().ConfigurationReadOnly().GetDisablePathCorrection() {
if len(path) > 1 && strings.HasSuffix(path, "/") { if len(path) > 1 && strings.HasSuffix(path, "/") {
// Remove trailing slash and client-permanent rule for redirection, // Remove trailing slash and client-permanent rule for redirection,
// if confgiuration allows that and path has an extra slash. // if confgiuration allows that and path has an extra slash.

View File

@ -581,7 +581,6 @@ func TypeByExtension(ext string) (typ string) {
// mime.TypeByExtension returns as text/plain; | charset=utf-8 the static .js (not always) // 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 == "text/plain" || typ == "text/plain; charset=utf-8") {
if ext == ".js" { if ext == ".js" {
typ = "application/javascript" typ = "application/javascript"
} }

View File

@ -9,26 +9,44 @@ func TestCleanPath(t *testing.T) {
path string path string
expected string expected string
}{ }{
{"/", {
"/"}, "/",
{"noslashPrefix", "/",
"/noslashPrefix"}, },
{"slashSuffix/", {
"/slashSuffix"}, "noslashPrefix",
{"noSlashPrefixAndslashSuffix/", "/noslashPrefix",
"/noSlashPrefixAndslashSuffix"}, },
{
"slashSuffix/",
"/slashSuffix",
},
{
"noSlashPrefixAndslashSuffix/",
"/noSlashPrefixAndslashSuffix",
},
// don't do any clean up inside {}, // don't do any clean up inside {},
// fixes #927. // fixes #927.
{"/total/{year:string regexp(\\d{4})}", {
"/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})}",
"/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})}"}, "/total/{year:string regexp(\\d{4})}/more",
{"/single_no_params", "/total/{year:string regexp(\\d{4})}/more",
"/single_no_params"}, },
{"/single/{id:uint64}", {
"/single/{id:uint64}"}, "/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 { for i, tt := range tests {
@ -43,18 +61,30 @@ func TestSplitPath(t *testing.T) {
path string path string
expected []string expected []string
}{ }{
{"/v2/stores/{id:string format(uuid)} /v3", {
[]string{"/v2/stores/{id:string format(uuid)}", "/v3"}}, "/v2/stores/{id:string format(uuid)} /v3",
{"/user/{id:uint64} /admin/{id:uint64}", []string{"/v2/stores/{id:string format(uuid)}", "/v3"},
[]string{"/user/{id:uint64}", "/admin/{id:uint64}"}}, },
{"/users/{id:int} /admins/{id:int64}", {
[]string{"/users/{id:int}", "/admins/{id:int64}"}}, "/user/{id:uint64} /admin/{id:uint64}",
{"/user /admin", []string{"/user/{id:uint64}", "/admin/{id:uint64}"},
[]string{"/user", "/admin"}}, },
{"/single_no_params", {
[]string{"/single_no_params"}}, "/users/{id:int} /admins/{id:int64}",
{"/single/{id:int}", []string{"/users/{id:int}", "/admins/{id:int64}"},
[]string{"/single/{id:int}"}}, },
{
"/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 { equalSlice := func(s1 []string, s2 []string) bool {
@ -78,6 +108,7 @@ func TestSplitPath(t *testing.T) {
} }
} }
} }
func TestSplitSubdomainAndPath(t *testing.T) { func TestSplitSubdomainAndPath(t *testing.T) {
tests := []struct { tests := []struct {
original string original string

View File

@ -51,7 +51,6 @@ type Route struct {
// handlers are being changed to validate the macros at serve time, if needed. // handlers are being changed to validate the macros at serve time, if needed.
func NewRoute(method, subdomain, unparsedPath, mainHandlerName string, func NewRoute(method, subdomain, unparsedPath, mainHandlerName string,
handlers context.Handlers, macros macro.Macros) (*Route, error) { handlers context.Handlers, macros macro.Macros) (*Route, error) {
tmpl, err := macro.Parse(unparsedPath, macros) tmpl, err := macro.Parse(unparsedPath, macros)
if err != nil { if err != nil {
return nil, err return nil, err

View File

@ -3,13 +3,13 @@
package router package router
import ( import (
"github.com/kataras/iris/macro"
"testing" "testing"
"github.com/kataras/iris/macro"
) )
func TestRouteStaticPath(t *testing.T) { func TestRouteStaticPath(t *testing.T) {
var tests = []struct { tests := []struct {
tmpl string tmpl string
static string static string
}{ }{

View File

@ -42,7 +42,6 @@ func (router *Router) RefreshRouter() error {
// //
// Use of RefreshRouter to re-build the router if needed. // Use of RefreshRouter to re-build the router if needed.
func (router *Router) BuildRouter(cPool *context.Pool, requestHandler RequestHandler, routesProvider RoutesProvider, force bool) error { func (router *Router) BuildRouter(cPool *context.Pool, requestHandler RequestHandler, routesProvider RoutesProvider, force bool) error {
if requestHandler == nil { if requestHandler == nil {
return errors.New("router: request handler is nil") return errors.New("router: request handler is nil")
} }

View File

@ -76,6 +76,7 @@ func TestMiddlewareByRouteDef(t *testing.T) {
testResponse(t, app, "/mypath") testResponse(t, app, "/mypath")
} }
func TestMiddlewareByUseAndDoneDef(t *testing.T) { func TestMiddlewareByUseAndDoneDef(t *testing.T) {
app := iris.New() app := iris.New()
app.Use(firstUseGlobalHandler, secondUseGlobalHandler, firstUseHandler, secondUseHandler) app.Use(firstUseGlobalHandler, secondUseGlobalHandler, firstUseHandler, secondUseHandler)

View File

@ -52,7 +52,7 @@ func h3(ctx context.Context) {
} }
func TestRouterWildcardDifferentPrefixPath(t *testing.T) { func TestRouterWildcardDifferentPrefixPath(t *testing.T) {
var tt = []testRoute{ tt := []testRoute{
{"GET", "/s/{p:path}", h, []testRouteRequest{ {"GET", "/s/{p:path}", h, []testRouteRequest{
{"GET", "", "/s/that/is/wildcard", iris.StatusOK, same_as_request_path}, {"GET", "", "/s/that/is/wildcard", iris.StatusOK, same_as_request_path},
{"GET", "", "/s/ok", 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) { func TestRouterWildcardAndStatic(t *testing.T) {
var tt = []testRoute{ tt := []testRoute{
{"GET", "/some/{p:path}", h2, []testRouteRequest{ {"GET", "/some/{p:path}", h2, []testRouteRequest{
{"GET", "", "/some/that/is/wildcard", iris.StatusForbidden, same_as_request_path}, {"GET", "", "/some/that/is/wildcard", iris.StatusForbidden, same_as_request_path},
{"GET", "", "/some/did", 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) { func TestRouterWildcardRootMany(t *testing.T) {
var tt = []testRoute{ tt := []testRoute{
// all routes will be handlded by "h" because we added wildcard to root, // 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. // this feature is very important and can remove noumerous of previous hacks on our apps.
{"GET", "/{p:path}", h, []testRouteRequest{ {"GET", "/{p:path}", h, []testRouteRequest{
@ -121,7 +121,7 @@ func TestRouterWildcardRootMany(t *testing.T) {
} }
func TestRouterWildcardRootManyAndRootStatic(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, // 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. // this feature is very important and can remove noumerous of previous hacks on our apps.
// //

View File

@ -88,7 +88,8 @@ func defaultErrorCodeHandlers() *ErrorCodeHandlers {
for _, statusCode := range []int{ for _, statusCode := range []int{
http.StatusNotFound, http.StatusNotFound,
http.StatusMethodNotAllowed, http.StatusMethodNotAllowed,
http.StatusInternalServerError} { http.StatusInternalServerError,
} {
chs.Register(statusCode, statusText(statusCode)) chs.Register(statusCode, statusText(statusCode))
} }

View File

@ -61,7 +61,6 @@ func TestOnAnyErrorCode(t *testing.T) {
Body().Equal(http.StatusText(iris.StatusNotAcceptable)) Body().Equal(http.StatusText(iris.StatusNotAcceptable))
checkAndClearBuf(t, buff, expectedPrintBeforeExecuteErr) checkAndClearBuf(t, buff, expectedPrintBeforeExecuteErr)
} }
func checkAndClearBuf(t *testing.T, buff *bytes.Buffer, expected string) { func checkAndClearBuf(t *testing.T, buff *bytes.Buffer, expected string) {

View File

@ -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 // again, a next value even with the same type is able to be
// used to other input arg. One value per input argument, order // used to other input arg. One value per input argument, order
// matters if same type of course. // matters if same type of course.
//if len(values) > j+1 { // if len(values) > j+1 {
values = append(values[:j], 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. // the binded values to the func's inputs.
b, err := MakeBindObject(value, s.goodFunc) b, err := MakeBindObject(value, s.goodFunc)
if err != nil { if err != nil {
return false return false
} }
@ -197,7 +196,6 @@ func (s *FuncInjector) Inject(in *[]reflect.Value, ctx ...reflect.Value) {
// input.InputIndex, v.String(), v.Type().Name()) // input.InputIndex, v.String(), v.Type().Name())
args[input.InputIndex] = v args[input.InputIndex] = v
}) })
} }
*in = args *in = args

View File

@ -124,9 +124,8 @@ func (bv *Values) AddOnce(value interface{}) bool {
} }
func (bv *Values) addIfNotExists(v reflect.Value) 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) { if !goodVal(v) {
return false return false

View File

@ -95,7 +95,6 @@ func DispatchErr(ctx context.Context, status int, err error) {
// commonly used data to the response writer with a smart way. // commonly used data to the response writer with a smart way.
func DispatchCommon(ctx context.Context, func DispatchCommon(ctx context.Context,
statusCode int, contentType string, content []byte, v interface{}, err error, found bool) { statusCode int, contentType string, content []byte, v interface{}, err error, found bool) {
// if we have a false boolean as a return value // if we have a false boolean as a return value
// then skip everything and fire a not found, // then skip everything and fire a not found,
// we even don't care about the given status code or the object or the content. // we even don't care about the given status code or the object or the content.

View File

@ -11,9 +11,7 @@ import (
"github.com/kataras/golog" "github.com/kataras/golog"
) )
var ( var contextTyp = reflect.TypeOf((*context.Context)(nil)).Elem()
contextTyp = reflect.TypeOf((*context.Context)(nil)).Elem()
)
// IsContext returns true if the "inTyp" is a type of Context. // IsContext returns true if the "inTyp" is a type of Context.
func IsContext(inTyp reflect.Type) bool { func IsContext(inTyp reflect.Type) bool {
@ -95,5 +93,4 @@ func makeHandler(handler interface{}, values ...reflect.Value) (context.Handler,
} }
return h, nil return h, nil
} }

View File

@ -44,5 +44,4 @@ func TestPathParams(t *testing.T) {
if got != expected { if got != expected {
t.Fatalf("expected the params 'firstname' + 'lastname' to be '%s' but got '%s'", expected, got) t.Fatalf("expected the params 'firstname' + 'lastname' to be '%s' but got '%s'", expected, got)
} }
} }

View File

@ -35,10 +35,8 @@ import (
"github.com/kataras/iris/middleware/recover" "github.com/kataras/iris/middleware/recover"
) )
var ( // Version is the current version number of the Iris Web Framework.
// Version is the current version number of the Iris Web Framework. const Version = "11.2.8"
Version = "11.2.8"
)
// HTTP status codes as registered with IANA. // HTTP status codes as registered with IANA.
// See: http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml // See: http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml

View File

@ -69,7 +69,6 @@ func resolveTokenType(ch byte) token.Type {
default: default:
return token.IDENT // return token.IDENT //
} }
} }
// NextToken returns the next token in the series of characters. // NextToken returns the next token in the series of characters.

View File

@ -93,7 +93,8 @@ func TestParseParam(t *testing.T) {
valid bool valid bool
expectedStatement ast.ParamStatement expectedStatement ast.ParamStatement
}{ }{
{true, {
true,
ast.ParamStatement{ ast.ParamStatement{
Src: "{id:int min(1) max(5) else 404}", Src: "{id:int min(1) max(5) else 404}",
Name: "id", Name: "id",
@ -101,15 +102,19 @@ func TestParseParam(t *testing.T) {
Funcs: []ast.ParamFunc{ Funcs: []ast.ParamFunc{
{ {
Name: "min", Name: "min",
Args: []string{"1"}}, Args: []string{"1"},
},
{ {
Name: "max", Name: "max",
Args: []string{"5"}}, Args: []string{"5"},
},
}, },
ErrorCode: 404, ErrorCode: 404,
}}, // 0 },
}, // 0
{true, {
true,
ast.ParamStatement{ ast.ParamStatement{
// test alias of int. // test alias of int.
Src: "{id:number range(1,5)}", Src: "{id:number range(1,5)}",
@ -118,11 +123,14 @@ func TestParseParam(t *testing.T) {
Funcs: []ast.ParamFunc{ Funcs: []ast.ParamFunc{
{ {
Name: "range", Name: "range",
Args: []string{"1", "5"}}, Args: []string{"1", "5"},
},
}, },
ErrorCode: 404, ErrorCode: 404,
}}, // 1 },
{true, }, // 1
{
true,
ast.ParamStatement{ ast.ParamStatement{
Src: "{file:path contains(.)}", Src: "{file:path contains(.)}",
Name: "file", Name: "file",
@ -130,84 +138,107 @@ func TestParseParam(t *testing.T) {
Funcs: []ast.ParamFunc{ Funcs: []ast.ParamFunc{
{ {
Name: "contains", Name: "contains",
Args: []string{"."}}, Args: []string{"."},
},
}, },
ErrorCode: 404, ErrorCode: 404,
}}, // 2 },
{true, }, // 2
{
true,
ast.ParamStatement{ ast.ParamStatement{
Src: "{username:alphabetical}", Src: "{username:alphabetical}",
Name: "username", Name: "username",
Type: mustLookupParamType("alphabetical"), Type: mustLookupParamType("alphabetical"),
ErrorCode: 404, ErrorCode: 404,
}}, // 3 },
{true, }, // 3
{
true,
ast.ParamStatement{ ast.ParamStatement{
Src: "{myparam}", Src: "{myparam}",
Name: "myparam", Name: "myparam",
Type: mustLookupParamType("string"), Type: mustLookupParamType("string"),
ErrorCode: 404, ErrorCode: 404,
}}, // 4 },
{false, }, // 4
{
false,
ast.ParamStatement{ ast.ParamStatement{
Src: "{myparam_:thisianunexpected}", Src: "{myparam_:thisianunexpected}",
Name: "myparam_", Name: "myparam_",
Type: nil, Type: nil,
ErrorCode: 404, ErrorCode: 404,
}}, // 5 },
{true, }, // 5
{
true,
ast.ParamStatement{ ast.ParamStatement{
Src: "{myparam2}", Src: "{myparam2}",
Name: "myparam2", // we now allow integers to the parameter names. Name: "myparam2", // we now allow integers to the parameter names.
Type: ast.GetMasterParamType(testParamTypes...), Type: ast.GetMasterParamType(testParamTypes...),
ErrorCode: 404, ErrorCode: 404,
}}, // 6 },
{true, }, // 6
{
true,
ast.ParamStatement{ ast.ParamStatement{
Src: "{id:int even()}", // test param funcs without any arguments (LPAREN peek for RPAREN) Src: "{id:int even()}", // test param funcs without any arguments (LPAREN peek for RPAREN)
Name: "id", Name: "id",
Type: mustLookupParamType("number"), Type: mustLookupParamType("number"),
Funcs: []ast.ParamFunc{ Funcs: []ast.ParamFunc{
{ {
Name: "even"}, Name: "even",
},
}, },
ErrorCode: 404, ErrorCode: 404,
}}, // 7 },
{true, }, // 7
{
true,
ast.ParamStatement{ ast.ParamStatement{
Src: "{id:int64 else 404}", Src: "{id:int64 else 404}",
Name: "id", Name: "id",
Type: mustLookupParamType("int64"), Type: mustLookupParamType("int64"),
ErrorCode: 404, ErrorCode: 404,
}}, // 8 },
{true, }, // 8
{
true,
ast.ParamStatement{ ast.ParamStatement{
Src: "{id:long else 404}", // backwards-compatible test. Src: "{id:long else 404}", // backwards-compatible test.
Name: "id", Name: "id",
Type: mustLookupParamType("int64"), Type: mustLookupParamType("int64"),
ErrorCode: 404, ErrorCode: 404,
}}, // 9 },
{true, }, // 9
{
true,
ast.ParamStatement{ ast.ParamStatement{
Src: "{id:long else 404}", Src: "{id:long else 404}",
Name: "id", Name: "id",
Type: mustLookupParamType("int64"), // backwards-compatible test of LookupParamType. Type: mustLookupParamType("int64"), // backwards-compatible test of LookupParamType.
ErrorCode: 404, ErrorCode: 404,
}}, // 10 },
{true, }, // 10
{
true,
ast.ParamStatement{ ast.ParamStatement{
Src: "{has:bool else 404}", Src: "{has:bool else 404}",
Name: "has", Name: "has",
Type: mustLookupParamType("bool"), Type: mustLookupParamType("bool"),
ErrorCode: 404, ErrorCode: 404,
}}, // 11 },
{true, }, // 11
{
true,
ast.ParamStatement{ ast.ParamStatement{
Src: "{has:boolean else 404}", // backwards-compatible test. Src: "{has:boolean else 404}", // backwards-compatible test.
Name: "has", Name: "has",
Type: mustLookupParamType("bool"), Type: mustLookupParamType("bool"),
ErrorCode: 404, ErrorCode: 404,
}}, // 12 },
}, // 12
} }
@ -237,88 +268,116 @@ func TestParse(t *testing.T) {
valid bool valid bool
expectedStatements []ast.ParamStatement expectedStatements []ast.ParamStatement
}{ }{
{"/api/users/{id:int min(1) max(5) else 404}", true, {
[]ast.ParamStatement{{ "/api/users/{id:int min(1) max(5) else 404}", true,
Src: "{id:int min(1) max(5) else 404}", []ast.ParamStatement{
Name: "id", {
Type: paramTypeNumber, Src: "{id:int min(1) max(5) else 404}",
Funcs: []ast.ParamFunc{ Name: "id",
{ Type: paramTypeNumber,
Name: "min", Funcs: []ast.ParamFunc{
Args: []string{"1"}}, {
{ Name: "min",
Name: "max", Args: []string{"1"},
Args: []string{"5"}}, },
{
Name: "max",
Args: []string{"5"},
},
},
ErrorCode: 404,
}, },
ErrorCode: 404,
}, },
}}, // 0 }, // 0
{"/admin/{id:uint64 range(1,5)}", true, {
[]ast.ParamStatement{{ "/admin/{id:uint64 range(1,5)}", true,
Src: "{id:uint64 range(1,5)}", []ast.ParamStatement{
Name: "id", {
Type: paramTypeUint64, Src: "{id:uint64 range(1,5)}",
Funcs: []ast.ParamFunc{ Name: "id",
{ Type: paramTypeUint64,
Name: "range", Funcs: []ast.ParamFunc{
Args: []string{"1", "5"}}, {
Name: "range",
Args: []string{"1", "5"},
},
},
ErrorCode: 404,
}, },
ErrorCode: 404,
}, },
}}, // 1 }, // 1
{"/files/{file:path contains(.)}", true, {
[]ast.ParamStatement{{ "/files/{file:path contains(.)}", true,
Src: "{file:path contains(.)}", []ast.ParamStatement{
Name: "file", {
Type: paramTypePath, Src: "{file:path contains(.)}",
Funcs: []ast.ParamFunc{ Name: "file",
{ Type: paramTypePath,
Name: "contains", Funcs: []ast.ParamFunc{
Args: []string{"."}}, {
Name: "contains",
Args: []string{"."},
},
},
ErrorCode: 404,
}, },
ErrorCode: 404,
}, },
}}, // 2 }, // 2
{"/profile/{username:alphabetical}", true, {
[]ast.ParamStatement{{ "/profile/{username:alphabetical}", true,
Src: "{username:alphabetical}", []ast.ParamStatement{
Name: "username", {
Type: paramTypeAlphabetical, Src: "{username:alphabetical}",
ErrorCode: 404, Name: "username",
Type: paramTypeAlphabetical,
ErrorCode: 404,
},
}, },
}}, // 3 }, // 3
{"/something/here/{myparam}", true, {
[]ast.ParamStatement{{ "/something/here/{myparam}", true,
Src: "{myparam}", []ast.ParamStatement{
Name: "myparam", {
Type: paramTypeString, Src: "{myparam}",
ErrorCode: 404, Name: "myparam",
Type: paramTypeString,
ErrorCode: 404,
},
}, },
}}, // 4 }, // 4
{"/unexpected/{myparam_:thisianunexpected}", false, {
[]ast.ParamStatement{{ "/unexpected/{myparam_:thisianunexpected}", false,
Src: "{myparam_:thisianunexpected}", []ast.ParamStatement{
Name: "myparam_", {
Type: nil, Src: "{myparam_:thisianunexpected}",
ErrorCode: 404, Name: "myparam_",
Type: nil,
ErrorCode: 404,
},
}, },
}}, // 5 }, // 5
{"/p2/{myparam2}", true, {
[]ast.ParamStatement{{ "/p2/{myparam2}", true,
Src: "{myparam2}", []ast.ParamStatement{
Name: "myparam2", // we now allow integers to the parameter names. {
Type: paramTypeString, Src: "{myparam2}",
ErrorCode: 404, Name: "myparam2", // we now allow integers to the parameter names.
Type: paramTypeString,
ErrorCode: 404,
},
}, },
}}, // 6 }, // 6
{"/assets/{file:path}/invalid", false, // path should be in the end segment {
[]ast.ParamStatement{{ "/assets/{file:path}/invalid", false, // path should be in the end segment
Src: "{file:path}", []ast.ParamStatement{
Name: "file", {
Type: paramTypePath, Src: "{file:path}",
ErrorCode: 404, Name: "file",
Type: paramTypePath,
ErrorCode: 404,
},
}, },
}}, // 7 }, // 7
} }
for i, tt := range tests { for i, tt := range tests {
statements, err := Parse(tt.path, testParamTypes) statements, err := Parse(tt.path, testParamTypes)

View File

@ -107,7 +107,6 @@ func (b *basicAuthMiddleware) askForCredentials(ctx context.Context) {
// Serve the actual middleware // Serve the actual middleware
func (b *basicAuthMiddleware) Serve(ctx context.Context) { func (b *basicAuthMiddleware) Serve(ctx context.Context) {
auth, found := b.findAuth(ctx.GetHeader("Authorization")) auth, found := b.findAuth(ctx.GetHeader("Authorization"))
if !found { if !found {
b.askForCredentials(ctx) b.askForCredentials(ctx)

View File

@ -82,7 +82,7 @@ func New(c Config) context.Handler {
} }
i := &i18nMiddleware{config: c} i := &i18nMiddleware{config: c}
firstlanguage := "" firstlanguage := ""
//load the files // load the files
for k, langFileOrFiles := range c.Languages { for k, langFileOrFiles := range c.Languages {
// remove all spaces. // remove all spaces.
langFileOrFiles = strings.Replace(langFileOrFiles, " ", "", -1) langFileOrFiles = strings.Replace(langFileOrFiles, " ", "", -1)

View File

@ -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 status, ip, method, path string
var latency time.Duration var latency time.Duration
var startTime, endTime time.Time var startTime, endTime time.Time
@ -49,7 +49,7 @@ func (l *requestLoggerMiddleware) ServeHTTP(ctx context.Context) {
ctx.Next() 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() endTime = time.Now()
latency = endTime.Sub(startTime) 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, // Columnize formats the given arguments as columns and returns the formatted output,
// note that it appends a new line to the end. // 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 { func Columnize(nowFormatted string, latency time.Duration, status, ip, method, path string, message interface{}, headerMessage interface{}) string {
titles := "Time | Status | Latency | IP | Method | Path" titles := "Time | Status | Latency | IP | Method | Path"
line := fmt.Sprintf("%s | %v | %4v | %s | %s | %s", nowFormatted, status, latency, ip, method, path) line := fmt.Sprintf("%s | %v | %4v | %s | %s | %s", nowFormatted, status, latency, ip, method, path)
if message != nil { if message != nil {

View File

@ -65,7 +65,6 @@ func SiteFerify(ctx context.Context, secret string) (response Response) {
// optional: let's no track our users "remoteip": {ctx.RemoteAddr()}, // optional: let's no track our users "remoteip": {ctx.RemoteAddr()},
}, },
) )
if err != nil { if err != nil {
response.ErrorCodes = append(response.ErrorCodes, err.Error()) response.ErrorCodes = append(response.ErrorCodes, err.Error())
return return

View File

@ -35,7 +35,6 @@ func New() context.Handler {
_, f, l, got := runtime.Caller(i) _, f, l, got := runtime.Caller(i)
if !got { if !got {
break break
} }
stacktrace += fmt.Sprintf("%s:%d\n", f, l) stacktrace += fmt.Sprintf("%s:%d\n", f, l)

View File

@ -491,5 +491,4 @@ func (c *ControllerActivator) handlerOf(m reflect.Method, funcDependencies []ref
hero.DispatchFuncResult(ctx, errorHandler, ctrl.Method(m.Index).Call(emptyIn)) hero.DispatchFuncResult(ctx, errorHandler, ctrl.Method(m.Index).Call(emptyIn))
} }
} }

View File

@ -23,27 +23,35 @@ var writeMethod = func(ctx context.Context) {
func (c *testController) Get() { func (c *testController) Get() {
writeMethod(c.Ctx) writeMethod(c.Ctx)
} }
func (c *testController) Post() { func (c *testController) Post() {
writeMethod(c.Ctx) writeMethod(c.Ctx)
} }
func (c *testController) Put() { func (c *testController) Put() {
writeMethod(c.Ctx) writeMethod(c.Ctx)
} }
func (c *testController) Delete() { func (c *testController) Delete() {
writeMethod(c.Ctx) writeMethod(c.Ctx)
} }
func (c *testController) Connect() { func (c *testController) Connect() {
writeMethod(c.Ctx) writeMethod(c.Ctx)
} }
func (c *testController) Head() { func (c *testController) Head() {
writeMethod(c.Ctx) writeMethod(c.Ctx)
} }
func (c *testController) Patch() { func (c *testController) Patch() {
writeMethod(c.Ctx) writeMethod(c.Ctx)
} }
func (c *testController) Options() { func (c *testController) Options() {
writeMethod(c.Ctx) writeMethod(c.Ctx)
} }
func (c *testController) Trace() { func (c *testController) Trace() {
writeMethod(c.Ctx) writeMethod(c.Ctx)
} }
@ -333,7 +341,7 @@ func (c *testCtrl0) EndRequest(ctx context.Context) {
ctx.Writef(c.TitlePointer.title) 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) c.testCtrl00.EndRequest(ctx)
} }
@ -441,7 +449,6 @@ func TestControllerRelPathFromFunc(t *testing.T) {
Body().Equal("GET:/42") Body().Equal("GET:/42")
e.GET("/anything/here").Expect().Status(iris.StatusOK). e.GET("/anything/here").Expect().Status(iris.StatusOK).
Body().Equal("GET:/anything/here") Body().Equal("GET:/anything/here")
} }
type testControllerActivateListener struct { type testControllerActivateListener struct {

View File

@ -14,8 +14,6 @@ type (
View = hero.View View = hero.View
) )
var ( // Try is a type alias for the `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.
// useful to return a result based on two cases: failure(including panics) and a succeess. var Try = hero.Try
Try = hero.Try
)

View File

@ -13,21 +13,19 @@ import (
"github.com/kataras/golog" "github.com/kataras/golog"
) )
var ( // HeroDependencies let you share bindable dependencies between
// HeroDependencies let you share bindable dependencies between // package-level hero's registered dependencies and all MVC instances that comes later.
// package-level hero's registered dependencies and all MVC instances that comes later. //
// // `hero.Register(...)`
// `hero.Register(...)` // `myMVC := mvc.New(app.Party(...))`
// `myMVC := mvc.New(app.Party(...))` // the "myMVC" registers the dependencies provided by the `hero.Register` func
// the "myMVC" registers the dependencies provided by the `hero.Register` func // automatically.
// automatically. //
// // Set it to false to disable that behavior, you have to use the `mvc#Register`
// 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.
// even if you had register dependencies with the `hero` package. //
// // Defaults to true.
// Defaults to true. var HeroDependencies = true
HeroDependencies = true
)
// Application is the high-level component of the "mvc" package. // 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 // It's the API that you will be using to register controllers among with their

View File

@ -120,7 +120,6 @@ type (
// Validate corrects missing fields configuration fields and returns the right configuration // Validate corrects missing fields configuration fields and returns the right configuration
func (c Config) Validate() Config { func (c Config) Validate() Config {
if c.Cookie == "" { if c.Cookie == "" {
c.Cookie = DefaultCookieName c.Cookie = DefaultCookieName
} }

View File

@ -62,7 +62,6 @@ func New(directoryPath string) (*Database, error) {
opts := badger.DefaultOptions(directoryPath) opts := badger.DefaultOptions(directoryPath)
service, err := badger.Open(opts) service, err := badger.Open(opts)
if err != nil { if err != nil {
golog.Errorf("unable to initialize the badger-based session database: %v", err) golog.Errorf("unable to initialize the badger-based session database: %v", err)
return nil, err return nil, err
@ -97,7 +96,6 @@ func (db *Database) Acquire(sid string, expires time.Duration) sessions.LifeTime
if err == badger.ErrKeyNotFound { if err == badger.ErrKeyNotFound {
// create it and set the expiration, we don't care about the value there. // create it and set the expiration, we don't care about the value there.
err = txn.SetEntry(badger.NewEntry(bsid, bsid).WithTTL(expires)) 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 { err := item.Value(func(valueBytes []byte) error {
return sessions.DefaultTranscoder.Unmarshal(valueBytes, &value) return sessions.DefaultTranscoder.Unmarshal(valueBytes, &value)
}) })
if err != nil { if err != nil {
golog.Error(err) golog.Error(err)
continue continue

View File

@ -55,7 +55,6 @@ func New(path string, fileMode os.FileMode) (*Database, error) {
service, err := bolt.Open(path, fileMode, service, err := bolt.Open(path, fileMode,
&bolt.Options{Timeout: 20 * time.Second}, &bolt.Options{Timeout: 20 * time.Second},
) )
if err != nil { if err != nil {
golog.Errorf("unable to initialize the BoltDB-based session database: %v", err) golog.Errorf("unable to initialize the BoltDB-based session database: %v", err)
return nil, err return nil, err
@ -203,7 +202,6 @@ func (db *Database) Acquire(sid string, expires time.Duration) (lifetime session
_, err = root.CreateBucketIfNotExists(bsid) _, err = root.CreateBucketIfNotExists(bsid)
return return
}) })
if err != nil { if err != nil {
golog.Debugf("unable to acquire session '%s': %v", sid, err) golog.Debugf("unable to acquire session '%s': %v", sid, err)
return sessions.LifeTime{} return sessions.LifeTime{}
@ -285,7 +283,6 @@ func (db *Database) Get(sid string, key string) (value interface{}) {
return sessions.DefaultTranscoder.Unmarshal(valueBytes, &value) return sessions.DefaultTranscoder.Unmarshal(valueBytes, &value)
}) })
if err != nil { if err != nil {
golog.Debugf("session '%s' key '%s' not found", sid, key) golog.Debugf("session '%s' key '%s' not found", sid, key)
} }

View File

@ -134,7 +134,6 @@ func (db *Database) Acquire(sid string, expires time.Duration) sessions.LifeTime
if !hasExpiration { if !hasExpiration {
return sessions.LifeTime{} return sessions.LifeTime{}
} }
return sessions.LifeTime{Time: time.Now().Add(time.Duration(seconds) * time.Second)} return sessions.LifeTime{Time: time.Now().Add(time.Duration(seconds) * time.Second)}

View File

@ -114,13 +114,12 @@ func (r *RadixDriver) Set(key string, value interface{}, secondsLifetime int64)
} }
// Get returns value, err by its key // 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) { func (r *RadixDriver) Get(key string) (interface{}, error) {
var redisVal interface{} var redisVal interface{}
mn := radix.MaybeNil{Rcv: &redisVal} mn := radix.MaybeNil{Rcv: &redisVal}
err := r.pool.Do(radix.Cmd(&mn, "GET", r.Config.Prefix+key)) err := r.pool.Do(radix.Cmd(&mn, "GET", r.Config.Prefix+key))
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -197,7 +196,6 @@ func (r *RadixDriver) GetAll() (interface{}, error) {
var redisVal []interface{} var redisVal []interface{}
mn := radix.MaybeNil{Rcv: &redisVal} mn := radix.MaybeNil{Rcv: &redisVal}
err := r.pool.Do(radix.Cmd(&mn, "SCAN", strconv.Itoa(0))) // 0 -> cursor err := r.pool.Do(radix.Cmd(&mn, "SCAN", strconv.Itoa(0))) // 0 -> cursor
if err != nil { if err != nil {
return nil, err return nil, err
} }

Some files were not shown because too many files have changed in this diff Show More