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.
@ -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

@ -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

@ -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,7 +34,6 @@ 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")

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)
@ -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,7 +89,6 @@ 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.
@ -106,7 +105,7 @@ var (
// 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.
ParamResolvers = map[reflect.Type]func(paramIndex int) interface{}{ var 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 {
@ -206,7 +205,6 @@ var (
} }
}, },
} }
)
// 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.
Prefix = "" var 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

@ -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
defaultServerAddr = defaultServerHostname + ":" + strconv.Itoa(defaultServerPort) var 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,11 +17,10 @@ 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".
AllMethods = []string{ var AllMethods = []string{
http.MethodGet, http.MethodGet,
http.MethodPost, http.MethodPost,
http.MethodPut, http.MethodPut,
@ -32,7 +31,6 @@ var (
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

@ -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.
Version = "11.2.8" const 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,
[]ast.ParamStatement{
{
Src: "{id:int min(1) max(5) else 404}", Src: "{id:int min(1) max(5) else 404}",
Name: "id", Name: "id",
Type: paramTypeNumber, Type: paramTypeNumber,
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 },
{"/admin/{id:uint64 range(1,5)}", true, }, // 0
[]ast.ParamStatement{{ {
"/admin/{id:uint64 range(1,5)}", true,
[]ast.ParamStatement{
{
Src: "{id:uint64 range(1,5)}", Src: "{id:uint64 range(1,5)}",
Name: "id", Name: "id",
Type: paramTypeUint64, Type: paramTypeUint64,
Funcs: []ast.ParamFunc{ Funcs: []ast.ParamFunc{
{ {
Name: "range", Name: "range",
Args: []string{"1", "5"}}, Args: []string{"1", "5"},
},
}, },
ErrorCode: 404, ErrorCode: 404,
}, },
}}, // 1 },
{"/files/{file:path contains(.)}", true, }, // 1
[]ast.ParamStatement{{ {
"/files/{file:path contains(.)}", true,
[]ast.ParamStatement{
{
Src: "{file:path contains(.)}", Src: "{file:path contains(.)}",
Name: "file", Name: "file",
Type: paramTypePath, Type: paramTypePath,
Funcs: []ast.ParamFunc{ Funcs: []ast.ParamFunc{
{ {
Name: "contains", Name: "contains",
Args: []string{"."}}, Args: []string{"."},
},
}, },
ErrorCode: 404, ErrorCode: 404,
}, },
}}, // 2 },
{"/profile/{username:alphabetical}", true, }, // 2
[]ast.ParamStatement{{ {
"/profile/{username:alphabetical}", true,
[]ast.ParamStatement{
{
Src: "{username:alphabetical}", Src: "{username:alphabetical}",
Name: "username", Name: "username",
Type: paramTypeAlphabetical, Type: paramTypeAlphabetical,
ErrorCode: 404, ErrorCode: 404,
}, },
}}, // 3 },
{"/something/here/{myparam}", true, }, // 3
[]ast.ParamStatement{{ {
"/something/here/{myparam}", true,
[]ast.ParamStatement{
{
Src: "{myparam}", Src: "{myparam}",
Name: "myparam", Name: "myparam",
Type: paramTypeString, Type: paramTypeString,
ErrorCode: 404, ErrorCode: 404,
}, },
}}, // 4 },
{"/unexpected/{myparam_:thisianunexpected}", false, }, // 4
[]ast.ParamStatement{{ {
"/unexpected/{myparam_:thisianunexpected}", false,
[]ast.ParamStatement{
{
Src: "{myparam_:thisianunexpected}", Src: "{myparam_:thisianunexpected}",
Name: "myparam_", Name: "myparam_",
Type: nil, Type: nil,
ErrorCode: 404, ErrorCode: 404,
}, },
}}, // 5 },
{"/p2/{myparam2}", true, }, // 5
[]ast.ParamStatement{{ {
"/p2/{myparam2}", true,
[]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: paramTypeString, Type: paramTypeString,
ErrorCode: 404, ErrorCode: 404,
}, },
}}, // 6 },
{"/assets/{file:path}/invalid", false, // path should be in the end segment }, // 6
[]ast.ParamStatement{{ {
"/assets/{file:path}/invalid", false, // path should be in the end segment
[]ast.ParamStatement{
{
Src: "{file:path}", Src: "{file:path}",
Name: "file", Name: "file",
Type: paramTypePath, Type: paramTypePath,
ErrorCode: 404, 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

@ -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)
} }
@ -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.
Try = hero.Try var Try = hero.Try
)

View File

@ -13,7 +13,6 @@ 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.
// //
@ -26,8 +25,7 @@ var (
// 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.
HeroDependencies = true var 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

@ -120,7 +120,6 @@ func (r *RadixDriver) Get(key string) (interface{}, error) {
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
} }

View File

@ -79,7 +79,6 @@ func (r *RedigoDriver) Get(key string) (interface{}, error) {
} }
redisVal, err := c.Do("GET", r.Config.Prefix+key) redisVal, err := c.Do("GET", r.Config.Prefix+key)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -108,7 +107,6 @@ func (r *RedigoDriver) TTL(key string) (seconds int64, hasExpiration bool, found
func (r *RedigoDriver) updateTTLConn(c redis.Conn, key string, newSecondsLifeTime int64) error { func (r *RedigoDriver) updateTTLConn(c redis.Conn, key string, newSecondsLifeTime int64) error {
reply, err := c.Do("EXPIRE", r.Config.Prefix+key, newSecondsLifeTime) reply, err := c.Do("EXPIRE", r.Config.Prefix+key, newSecondsLifeTime)
if err != nil { if err != nil {
return err return err
} }
@ -175,7 +173,6 @@ func (r *RedigoDriver) GetAll() (interface{}, error) {
} }
redisVal, err := c.Do("SCAN", 0) // 0 -> cursor redisVal, err := c.Do("SCAN", 0) // 0 -> cursor
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -243,7 +240,6 @@ func (r *RedigoDriver) GetBytes(key string) ([]byte, error) {
} }
redisVal, err := c.Do("GET", r.Config.Prefix+key) redisVal, err := c.Do("GET", r.Config.Prefix+key)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -174,7 +174,6 @@ func DefaultTsconfig() Tsconfig {
}, },
Exclude: []string{"node_modules"}, Exclude: []string{"node_modules"},
} }
} }
// DefaultConfig returns the default Options of the Typescript adaptor // DefaultConfig returns the default Options of the Typescript adaptor

View File

@ -52,10 +52,8 @@ type (
} }
) )
var (
// NoOpLogger can be used as the logger argument, it prints nothing. // NoOpLogger can be used as the logger argument, it prints nothing.
NoOpLogger = func(string, ...interface{}) {} var NoOpLogger = func(string, ...interface{}) {}
)
// New creates and returns an Editor Plugin instance // New creates and returns an Editor Plugin instance
func New(cfg ...Config) *Editor { func New(cfg ...Config) *Editor {

View File

@ -7,10 +7,8 @@ import (
"strings" "strings"
) )
var (
// PathSeparator is the string of os.PathSeparator // PathSeparator is the string of os.PathSeparator
PathSeparator = string(os.PathSeparator) var PathSeparator = string(os.PathSeparator)
)
type ( type (
// Cmd is a custom struch which 'implements' the *exec.Cmd // Cmd is a custom struch which 'implements' the *exec.Cmd

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