1
0
mirror of https://github.com/kataras/iris.git synced 2026-01-08 04:21:57 +00:00

Add notes for the new lead maintainer of the open-source iris project and align with @get-ion/ion by @hiveminded

Former-commit-id: da4f38eb9034daa49446df3ee529423b98f9b331
This commit is contained in:
kataras
2017-07-10 18:32:42 +03:00
parent 2d4c2779a7
commit 9f85b74fc9
344 changed files with 4842 additions and 5174 deletions

49
middleware/README.md Normal file
View File

@@ -0,0 +1,49 @@
Built'n Handlers
------------
| Middleware | Example |
| -----------|-------------|
| [basic authentication](basicauth) | [iris/_examples/authentication/basicauth](https://github.com/kataras/iris/tree/master/_examples/authentication/basicauth) |
| [localization and internationalization](i18n) | [iris/_examples/miscellaneous/i81n](https://github.com/kataras/iris/tree/master/_examples/miscellaneous/i18n) |
| [request logger](logger) | [iris/_examples/http_request/request-logger](https://github.com/kataras/iris/tree/master/_examples/http_request/request-logger) |
| [profiling (pprof)](pprof) | [iris/_examples/miscellaneous/pprof](https://github.com/kataras/iris/tree/master/_examples/miscellaneous/pprof) |
| [recovery](recover) | [iris/_examples/miscellaneous/recover](https://github.com/kataras/iris/tree/master/_examples/miscellaneous/recover) |
Experimental Handlers
------------
Most of the experimental handlers are ported to work with _iris_'s handler form, from third-party sources.
| Middleware | Description | Example |
| -----------|--------|-------------|
| [jwt](https://github.com/iris-contrib/middleware/tree/master/jwt) | Middleware checks for a JWT on the `Authorization` header on incoming requests and decodes it. | [iris-contrib/middleware/jwt/_example](https://github.com/iris-contrib/middleware/tree/master/jwt/_example) |
| [cors](https://github.com/iris-contrib/middleware/tree/master/cors) | HTTP Access Control. | [iris-contrib/middleware/cors/_example](https://github.com/iris-contrib/middleware/tree/master/cors/_example) |
| [secure](https://github.com/iris-contrib/middleware/tree/master/secure) | Middleware that implements a few quick security wins. | [iris-contrib/middleware/secure/_example](https://github.com/iris-contrib/middleware/tree/master/secure/_example/main.go) |
| [tollbooth](https://github.com/iris-contrib/middleware/tree/master/tollboothic) | Generic middleware to rate-limit HTTP requests. | [iris-contrib/middleware/tollbooth/_examples/limit-handler](https://github.com/iris-contrib/middleware/tree/master/tollbooth/_examples/limit-handler) |
| [cloudwatch](https://github.com/iris-contrib/middleware/tree/master/cloudwatch) | AWS cloudwatch metrics middleware. |[iris-contrib/middleware/cloudwatch/_example](https://github.com/iris-contrib/middleware/tree/master/cloudwatch/_example) |
| [new relic](https://github.com/iris-contrib/middleware/tree/master/newrelic) | Official [New Relic Go Agent](https://github.com/newrelic/go-agent). | [iris-contrib/middleware/newrelic/_example](https://github.com/iris-contrib/middleware/tree/master/newrelic/_example) |
| [prometheus](https://github.com/iris-contrib/middleware/tree/master/prometheus)| Easily create metrics endpoint for the [prometheus](http://prometheus.io) instrumentation tool | [iris-contrib/middleware/prometheus/_example](https://github.com/iris-contrib/middleware/tree/master/prometheus/_example) |
Third-Party Handlers
------------
iris has its own middleware form of `func(ctx context.Context)` but it's also compatible with all `net/http` middleware forms. See [here](https://github.com/kataras/iris/tree/master/_examples/convert-handlers).
Here's a small list of useful third-party handlers:
| Middleware | Description |
| -----------|-------------|
| [goth](https://github.com/markbates/goth) | OAuth, OAuth2 authentication. [Example](https://github.com/kataras/iris/tree/master/_examples/authentication/oauth2) |
| [binding](https://github.com/mholt/binding) | Data binding from HTTP requests into structs |
| [csp](https://github.com/awakenetworks/csp) | [Content Security Policy](https://www.w3.org/TR/CSP2/) (CSP) support |
| [delay](https://github.com/jeffbmartinez/delay) | Add delays/latency to endpoints. Useful when testing effects of high latency |
| [onthefly](https://github.com/xyproto/onthefly) | Generate TinySVG, HTML and CSS on the fly |
| [permissions2](https://github.com/xyproto/permissions2) | Cookies, users and permissions |
| [RestGate](https://github.com/pjebs/restgate) | Secure authentication for REST API endpoints |
| [stats](https://github.com/thoas/stats) | Store information about your web application (response time, etc.) |
| [VanGoH](https://github.com/auroratechnologies/vangoh) | Configurable [AWS-Style](http://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html) HMAC authentication middleware |
| [xrequestid](https://github.com/pilu/xrequestid) | Middleware that assigns a random X-Request-Id header to each request |
| [digits](https://github.com/bamarni/digits) | Middleware that handles [Twitter Digits](https://get.digits.com/) authentication |
> Feel free to put up your own middleware in this list!

View File

@@ -1,10 +1,8 @@
// Copyright 2017 Gerasimos Maropoulos, ΓΜ. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package basicauth provides http basic authentication via middleware. See _examples/beginner/basicauth
// Package basicauth provides http basic authentication via middleware. See _examples/authentication/basicauth
package basicauth
// test file: ../../_examples/authentication/basicauth/main_test.go
import (
"encoding/base64"
"strconv"

View File

@@ -1,67 +0,0 @@
// black-box testing
package basicauth_test
import (
"testing"
"github.com/kataras/iris"
"github.com/kataras/iris/context"
"github.com/kataras/iris/httptest"
"github.com/kataras/iris/middleware/basicauth"
)
func buildApp() *iris.Application {
app := iris.New()
authConfig := basicauth.Config{
Users: map[string]string{"myusername": "mypassword"},
}
authentication := basicauth.New(authConfig)
app.Get("/", func(ctx context.Context) { ctx.Redirect("/admin") })
// to party
needAuth := app.Party("/admin", authentication)
{
//http://localhost:8080/admin
needAuth.Get("/", h)
// http://localhost:8080/admin/profile
needAuth.Get("/profile", h)
// http://localhost:8080/admin/settings
needAuth.Get("/settings", h)
}
return app
}
func h(ctx context.Context) {
username, password, _ := ctx.Request().BasicAuth()
// third parameter it will be always true because the middleware
// makes sure for that, otherwise this handler will not be executed.
ctx.Writef("%s %s:%s", ctx.Path(), username, password)
}
func TestBasicAuth(t *testing.T) {
app := buildApp()
e := httptest.New(t, app)
// redirects to /admin without basic auth
e.GET("/").Expect().Status(iris.StatusUnauthorized)
// without basic auth
e.GET("/admin").Expect().Status(iris.StatusUnauthorized)
// with valid basic auth
e.GET("/admin").WithBasicAuth("myusername", "mypassword").Expect().
Status(iris.StatusOK).Body().Equal("/admin myusername:mypassword")
e.GET("/admin/profile").WithBasicAuth("myusername", "mypassword").Expect().
Status(iris.StatusOK).Body().Equal("/admin/profile myusername:mypassword")
e.GET("/admin/settings").WithBasicAuth("myusername", "mypassword").Expect().
Status(iris.StatusOK).Body().Equal("/admin/settings myusername:mypassword")
// with invalid basic auth
e.GET("/admin/settings").WithBasicAuth("invalidusername", "invalidpassword").
Expect().Status(iris.StatusUnauthorized)
}

View File

@@ -1,7 +1,3 @@
// Copyright 2017 Gerasimos Maropoulos, ΓΜ. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package basicauth
import (

View File

@@ -1,4 +1,4 @@
// Package i18n provides internalization and localization via middleware. See _examples/intermediate/i18n
// Package i18n provides internalization and localization via middleware. See _examples/miscellaneous/i18n
package i18n
import (
@@ -9,6 +9,7 @@ import (
"github.com/kataras/iris/context"
)
// test file: ../../_examples/miscellaneous/i18n/main_test.go
type i18nMiddleware struct {
config Config
}
@@ -23,7 +24,6 @@ func (i *i18nMiddleware) ServeHTTP(ctx context.Context) {
if ctx.Values().GetString(langKey) == "" {
// try to get by url parameter
language = ctx.URLParam(i.config.URLParameter)
if language == "" {
// then try to take the lang field from the cookie
language = ctx.GetCookie(langKey)
@@ -44,9 +44,16 @@ func (i *i18nMiddleware) ServeHTTP(ctx context.Context) {
if language == "" {
language = i.config.Default
}
ctx.Values().Set(langKey, language)
}
locale := i18n.Locale{Lang: language}
// if unexpected language given, the middleware will transtlate to the default language, the language key should be
// also this language instead of the user-given
if indexLang := locale.Index(); indexLang == -1 {
locale.Lang = i.config.Default
}
ctx.Values().Set(langKey, locale.Lang)
translateFuncKey := ctx.Application().ConfigurationReadOnly().GetTranslateFunctionContextKey()
ctx.Values().Set(translateFuncKey, locale.Tr)
ctx.Next()
@@ -73,13 +80,13 @@ func New(c Config) context.Handler {
}
err := i18n.SetMessage(k, v)
if err != nil && err != i18n.ErrLangAlreadyExist {
panic("Iris i18n Middleware: Failed to set locale file" + k + " Error:" + err.Error())
panic("iris i18n Middleware: Failed to set locale file" + k + " Error:" + err.Error())
}
if firstlanguage == "" {
firstlanguage = k
}
}
// if not default language setted then set to the first of the i.options.Languages
// if not default language setted then set to the first of the i.config.Languages
if c.Default == "" {
c.Default = firstlanguage
}
@@ -88,8 +95,8 @@ func New(c Config) context.Handler {
return i.ServeHTTP
}
// TranslatedMap returns translated map[string]interface{} from i18n structure
func TranslatedMap(sourceInterface interface{}, ctx context.Context) map[string]interface{} {
// TranslatedMap returns translated map[string]interface{} from i18n structure.
func TranslatedMap(ctx context.Context, sourceInterface interface{}) map[string]interface{} {
iType := reflect.TypeOf(sourceInterface).Elem()
result := make(map[string]interface{})

View File

@@ -1,7 +1,3 @@
// Copyright 2017 Gerasimos Maropoulos, ΓΜ. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package logger
// Config are the options of the logger middlweare

View File

@@ -1,8 +1,4 @@
// Copyright 2017 Gerasimos Maropoulos, ΓΜ. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package logger provides request logging via middleware. See _examples/beginner/request-logger
// Package logger provides request logging via middleware. See _examples/http_request/request-logger
package logger
import (
@@ -49,7 +45,7 @@ func (l *requestLoggerMiddleware) ServeHTTP(ctx context.Context) {
}
//finally print the logs, no new line, the framework's logger is responsible how to render each log.
ctx.Application().Log("%v %4v %s %s %s", status, latency, ip, method, path)
ctx.Application().Logger().Infof("%v %4v %s %s %s", status, latency, ip, method, path)
}
// New creates and returns a new request logger middleware.

View File

@@ -1,8 +1,4 @@
// Copyright 2017 Gerasimos Maropoulos, ΓΜ. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package pprof provides native pprof support via middleware. See _examples/beginner/pprof
// Package pprof provides native pprof support via middleware. See _examples/miscellaneous/pprof
package pprof
import (

View File

@@ -1,8 +1,4 @@
// Copyright 2017 Gerasimos Maropoulos, ΓΜ. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package recover provides recovery for specific routes or for the whole app via middleware. See _examples/beginner/recover
// Package recover provides recovery for specific routes or for the whole app via middleware. See _examples/miscellaneous/recover
package recover
import (
@@ -23,9 +19,9 @@ func getRequestLogs(ctx context.Context) string {
return fmt.Sprintf("%v %s %s %s", status, path, method, ip)
}
// New returns a new recover middleware
// it logs to the LoggerOut iris' configuration field if its IsDeveloper configuration field is enabled.
// otherwise it just continues to serve
// New returns a new recover middleware,
// it recovers from panics and logs
// the panic message to the application's logger "Warn" level.
func New() context.Handler {
return func(ctx context.Context) {
defer func() {
@@ -49,12 +45,11 @@ func New() context.Handler {
logMessage := fmt.Sprintf("Recovered from a route's Handler('%s')\n", ctx.HandlerName())
logMessage += fmt.Sprintf("At Request: %s\n", getRequestLogs(ctx))
logMessage += fmt.Sprintf("Trace: %s\n", err)
logMessage += fmt.Sprintf("\n%s\n", stacktrace)
ctx.Application().Log(logMessage)
logMessage += fmt.Sprintf("\n%s", stacktrace)
ctx.Application().Logger().Warnln(logMessage)
ctx.StopExecution()
ctx.StatusCode(500)
ctx.StopExecution()
}
}()