mirror of
https://github.com/kataras/iris.git
synced 2025-02-02 15:30:36 +01:00
formatting
Former-commit-id: 037081db5d6d4434e873ca8b75334ee43e046b6a
This commit is contained in:
parent
00967408dc
commit
07046ab978
|
@ -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.",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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 {
|
||||
|
|
|
@ -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) {
|
||||
|
|
|
@ -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",
|
||||
|
|
|
@ -6,7 +6,6 @@ import (
|
|||
)
|
||||
|
||||
func main() {
|
||||
|
||||
app := iris.New()
|
||||
|
||||
// 1
|
||||
|
|
|
@ -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) {
|
||||
|
|
|
@ -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 {
|
||||
|
|
|
@ -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())
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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))
|
||||
|
||||
}
|
||||
|
|
|
@ -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: <b>" + err.Error() + "</b>")
|
||||
|
|
|
@ -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
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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",
|
||||
|
|
|
@ -37,5 +37,4 @@ func UserList(userList []string, buffer *bytes.Buffer) {
|
|||
</body>
|
||||
</html>
|
||||
`)
|
||||
|
||||
}
|
||||
|
|
|
@ -40,5 +40,4 @@ func UserListToWriter(userList []string, w io.Writer) (int, error) {
|
|||
</html>
|
||||
`)
|
||||
return w.Write(_buffer.Bytes())
|
||||
|
||||
}
|
||||
|
|
|
@ -42,7 +42,6 @@ func main() {
|
|||
s.Publish("messages", &sse.Event{
|
||||
Data: []byte("third message"),
|
||||
})
|
||||
|
||||
}() // ...
|
||||
|
||||
app.Run(iris.Addr(":8080"), iris.WithoutServerError(iris.ErrServerClosed))
|
||||
|
|
|
@ -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())
|
||||
|
|
|
@ -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)
|
||||
|
||||
}
|
||||
|
|
|
@ -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{
|
||||
|
|
|
@ -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.")
|
||||
|
|
|
@ -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)
|
||||
|
||||
}
|
||||
|
|
|
@ -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) {
|
||||
|
|
|
@ -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"),
|
||||
|
|
|
@ -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"))
|
||||
|
||||
}
|
||||
|
|
|
@ -16,7 +16,6 @@ func main() {
|
|||
})
|
||||
|
||||
app.Get("/change", func(ctx iris.Context) {
|
||||
|
||||
if none.IsOnline() {
|
||||
none.Method = iris.MethodNone
|
||||
} else {
|
||||
|
|
|
@ -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)
|
||||
})
|
||||
|
||||
|
|
|
@ -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)
|
||||
})
|
||||
|
||||
|
|
|
@ -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)
|
||||
})
|
||||
|
||||
|
|
|
@ -46,12 +46,12 @@ func main() {
|
|||
ctx.HTML("</ul>")
|
||||
})
|
||||
|
||||
//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) {
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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:
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -54,5 +54,4 @@ func TestSubdomainWWW(t *testing.T) {
|
|||
Status(httptest.StatusOK).
|
||||
Body().Equal(test.response())
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -27,5 +27,4 @@ func TestNewApp(t *testing.T) {
|
|||
// with invalid basic auth
|
||||
e.GET("/admin/settings").WithBasicAuth("invalidusername", "invalidpassword").
|
||||
Expect().Status(httptest.StatusUnauthorized)
|
||||
|
||||
}
|
||||
|
|
|
@ -375,5 +375,4 @@ func getTopicConsumeSSEHandler(ctx iris.Context) {
|
|||
flusher.Flush()
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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())
|
||||
|
|
|
@ -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")
|
||||
|
|
|
@ -99,7 +99,6 @@ func newApp(db *DB) *iris.Application {
|
|||
ctx.ViewData("FORM_RESULT",
|
||||
template.HTML("<pre><a target='_new' href='"+shortenURL+"'>"+shortenURL+" </a></pre>"))
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -73,5 +73,4 @@ func TestURLShortener(t *testing.T) {
|
|||
}
|
||||
|
||||
time.Sleep(1 * time.Second)
|
||||
|
||||
}
|
||||
|
|
|
@ -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 {
|
||||
|
|
|
@ -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/
|
||||
|
|
|
@ -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) {
|
||||
|
|
|
@ -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"},
|
||||
|
|
|
@ -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")
|
||||
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
|
|
1
cache/browser_test.go
vendored
1
cache/browser_test.go
vendored
|
@ -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()
|
||||
|
||||
|
|
3
cache/cache_test.go
vendored
3
cache/cache_test.go
vendored
|
@ -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)
|
||||
|
|
1
cache/client/handler.go
vendored
1
cache/client/handler.go
vendored
|
@ -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()))
|
||||
|
||||
}
|
||||
|
|
1
cache/client/rule/chained.go
vendored
1
cache/client/rule/chained.go
vendored
|
@ -36,7 +36,6 @@ func Chained(rule Rule, next ...Rule) Rule {
|
|||
}
|
||||
|
||||
return c
|
||||
|
||||
}
|
||||
|
||||
// Claim validator
|
||||
|
|
1
cache/entry/entry.go
vendored
1
cache/entry/entry.go
vendored
|
@ -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{}
|
||||
}
|
||||
|
|
1
cache/uri/uribuilder.go
vendored
1
cache/uri/uribuilder.go
vendored
|
@ -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)
|
||||
|
|
|
@ -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) {
|
||||
|
|
|
@ -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.
|
||||
|
|
|
@ -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
|
||||
}
|
||||
|
|
|
@ -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) <T> {
|
||||
// return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(<T>)
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// 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) <T> {
|
||||
// return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(<T>)
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// 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.
|
||||
|
|
|
@ -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).
|
||||
|
|
|
@ -298,7 +298,6 @@ func (w *responseWriter) WriteTo(to ResponseWriter) {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
// the body is not copied, this writer doesn't support recording
|
||||
}
|
||||
|
|
|
@ -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 {
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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
|
||||
}
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -36,7 +36,6 @@ func TestFromStd(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestFromStdWithNext(t *testing.T) {
|
||||
|
||||
basicauth := "secret"
|
||||
passed := "ok"
|
||||
|
||||
|
|
|
@ -76,7 +76,6 @@ func (m myTestTask) OnServe(host TaskHost) {
|
|||
time.AfterFunc(startDelay, func() {
|
||||
m.logger.Println("restart")
|
||||
host.Serve() // restart
|
||||
|
||||
})
|
||||
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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 {
|
||||
|
|
|
@ -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
|
||||
}
|
||||
|
|
|
@ -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())
|
||||
|
|
|
@ -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.
|
||||
|
|
|
@ -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"
|
||||
}
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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
|
||||
}{
|
||||
|
|
|
@ -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")
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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.
|
||||
//
|
||||
|
|
|
@ -88,7 +88,8 @@ func defaultErrorCodeHandlers() *ErrorCodeHandlers {
|
|||
for _, statusCode := range []int{
|
||||
http.StatusNotFound,
|
||||
http.StatusMethodNotAllowed,
|
||||
http.StatusInternalServerError} {
|
||||
http.StatusInternalServerError,
|
||||
} {
|
||||
chs.Register(statusCode, statusText(statusCode))
|
||||
}
|
||||
|
||||
|
|
|
@ -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) {
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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.
|
||||
|
|
|
@ -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
|
||||
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
|
||||
}
|
||||
|
|
6
iris.go
6
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
|
||||
|
|
|
@ -69,7 +69,6 @@ func resolveTokenType(ch byte) token.Type {
|
|||
default:
|
||||
return token.IDENT //
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// NextToken returns the next token in the series of characters.
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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 {
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -491,5 +491,4 @@ func (c *ControllerActivator) handlerOf(m reflect.Method, funcDependencies []ref
|
|||
|
||||
hero.DispatchFuncResult(ctx, errorHandler, ctrl.Method(m.Index).Call(emptyIn))
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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 {
|
||||
|
|
|
@ -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
|
||||
|
|
28
mvc/mvc.go
28
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
|
||||
|
|
|
@ -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
|
||||
}
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
|
|
|
@ -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)}
|
||||
|
|
|
@ -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
|
||||
}
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user