mirror of
https://github.com/kataras/iris.git
synced 2026-01-10 13:35:59 +00:00
20 days of unstoppable work. Waiting fo go 1.8, I didn't finish yet, some touches remains.
Former-commit-id: ed84f99c89f43fe5e980a8e6d0ee22c186f0e1b9
This commit is contained in:
@@ -1,84 +0,0 @@
|
||||
# Middleware
|
||||
|
||||
We should mention that Iris is compatible with **ALL** net/http middleware out there,
|
||||
You are not restricted to so-called 'iris-made' middleware. They do exists, mostly, for your learning curve.
|
||||
|
||||
Navigate through [iris-contrib/middleware](https://github.com/iris-contrib/through) repository to view iris-made 'middleware'.
|
||||
|
||||
> By the word 'middleware', we mean a single or a collection of route handlers which may execute before/or after the main route handler.
|
||||
|
||||
|
||||
## Installation
|
||||
|
||||
```sh
|
||||
$ go get github.com/iris-contrib/middleware/...
|
||||
```
|
||||
|
||||
## How can I register a middleware?
|
||||
|
||||
```go
|
||||
app := iris.New()
|
||||
/* per root path and all its children */
|
||||
app.Use(logger)
|
||||
|
||||
/* execute always last */
|
||||
// app.Done(logger)
|
||||
|
||||
/* per-route, order matters. */
|
||||
// app.Get("/", logger, indexHandler)
|
||||
|
||||
/* per party (group of routes) */
|
||||
// userRoutes := app.Party("/user", logger)
|
||||
// userRoutes.Post("/login", loginAuthHandler)
|
||||
```
|
||||
|
||||
## How 'hard' is to create an Iris middleware?
|
||||
|
||||
```go
|
||||
myMiddleware := func(ctx *iris.Context){
|
||||
/* using ctx.Set you can transfer ANY data between handlers,
|
||||
use ctx.Get("welcomed") to get its value on the next handler(s).
|
||||
*/
|
||||
ctx.Set("welcomed", true)
|
||||
|
||||
println("My middleware!")
|
||||
}
|
||||
```
|
||||
> func(ctx *iris.Context) is just the `iris.HandlerFunc` signature which implements the `iris.Handler`/ `Serve(Context)` method.
|
||||
|
||||
```go
|
||||
app := iris.New()
|
||||
/* root path and all its children */
|
||||
app.UseFunc(myMiddleware)
|
||||
|
||||
app.Get("/", indexHandler)
|
||||
```
|
||||
|
||||
## Convert `http.Handler` to `iris.Handler` using the `iris.ToHandler`
|
||||
|
||||
```go
|
||||
// ToHandler converts different type styles of handlers that you
|
||||
// used to use (usually with third-party net/http middleware) to an iris.HandlerFunc.
|
||||
//
|
||||
// Supported types:
|
||||
// - .ToHandler(h http.Handler)
|
||||
// - .ToHandler(func(w http.ResponseWriter, r *http.Request))
|
||||
// - .ToHandler(func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc))
|
||||
func ToHandler(handler interface{}) HandlerFunc
|
||||
```
|
||||
|
||||
|
||||
```go
|
||||
app := iris.New()
|
||||
|
||||
sillyHTTPHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
|
||||
println(r.RequestURI)
|
||||
})
|
||||
|
||||
app.Use(iris.ToHandler(sillyHTTPHandler))
|
||||
```
|
||||
|
||||
|
||||
## What next?
|
||||
|
||||
Read more about [iris.Handler](https://docs.iris-go.com/using-handlers.html), [iris.HandlerFunc](https://docs.iris-go.com/using-handlerfuncs.html) and [Middleware](https://docs.iris-go.com/middleware.html).
|
||||
56
middleware/basicauth/_example/main.go
Normal file
56
middleware/basicauth/_example/main.go
Normal file
@@ -0,0 +1,56 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/middleware/basicauth"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(httprouter.New()) // adapt a router first of all
|
||||
|
||||
authConfig := basicauth.Config{
|
||||
Users: map[string]string{"myusername": "mypassword", "mySecondusername": "mySecondpassword"},
|
||||
Realm: "Authorization Required", // defaults to "Authorization Required"
|
||||
ContextKey: "mycustomkey", // defaults to "user"
|
||||
Expires: time.Duration(30) * time.Minute,
|
||||
}
|
||||
|
||||
authentication := basicauth.New(authConfig)
|
||||
app.Get("/", func(ctx *iris.Context) { ctx.Redirect("/admin") })
|
||||
// to global app.Use(authentication) (or app.UseGlobal before the .Listen)
|
||||
// to routes
|
||||
/*
|
||||
app.Get("/mysecret", authentication, func(ctx *iris.Context) {
|
||||
username := ctx.GetString("mycustomkey") // the Contextkey from the authConfig
|
||||
ctx.Writef("Hello authenticated user: %s ", username)
|
||||
})
|
||||
*/
|
||||
|
||||
// to party
|
||||
|
||||
needAuth := app.Party("/admin", authentication)
|
||||
{
|
||||
//http://localhost:8080/admin
|
||||
needAuth.Get("/", func(ctx *iris.Context) {
|
||||
username := ctx.GetString("mycustomkey") // the Contextkey from the authConfig
|
||||
ctx.Writef("Hello authenticated user: %s from: %s ", username, ctx.Path())
|
||||
})
|
||||
// http://localhost:8080/admin/profile
|
||||
needAuth.Get("/profile", func(ctx *iris.Context) {
|
||||
username := ctx.GetString("mycustomkey") // the Contextkey from the authConfig
|
||||
ctx.Writef("Hello authenticated user: %s from: %s ", username, ctx.Path())
|
||||
})
|
||||
// http://localhost:8080/admin/settings
|
||||
needAuth.Get("/settings", func(ctx *iris.Context) {
|
||||
username := authConfig.User(ctx) // shortcut for ctx.GetString("mycustomkey")
|
||||
ctx.Writef("Hello authenticated user: %s from: %s ", username, ctx.Path())
|
||||
})
|
||||
}
|
||||
|
||||
// open http://localhost:8080/admin
|
||||
app.Listen(":8080")
|
||||
}
|
||||
131
middleware/basicauth/basicauth.go
Normal file
131
middleware/basicauth/basicauth.go
Normal file
@@ -0,0 +1,131 @@
|
||||
package basicauth
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
)
|
||||
|
||||
// +------------------------------------------------------------+
|
||||
// | Middleware usage |
|
||||
// +------------------------------------------------------------+
|
||||
//
|
||||
// import "gopkg.in/kataras/iris.v6/middleware/basicauth"
|
||||
//
|
||||
// app := iris.New()
|
||||
// authentication := basicauth.Default(map[string]string{"myusername": "mypassword", "mySecondusername": "mySecondpassword"})
|
||||
// app.Get("/dashboard", authentication, func(ctx *iris.Context){})
|
||||
//
|
||||
// for more configuration basicauth.New(basicauth.Config{...})
|
||||
// see _example
|
||||
|
||||
type (
|
||||
encodedUser struct {
|
||||
HeaderValue string
|
||||
Username string
|
||||
logged bool
|
||||
expires time.Time
|
||||
}
|
||||
encodedUsers []encodedUser
|
||||
|
||||
basicAuthMiddleware struct {
|
||||
config Config
|
||||
// these are filled from the config.Users map at the startup
|
||||
auth encodedUsers
|
||||
realmHeaderValue string
|
||||
expireEnabled bool // if the config.Expires is a valid date, default disabled
|
||||
}
|
||||
)
|
||||
|
||||
//
|
||||
|
||||
// New takes one parameter, the Config returns a HandlerFunc
|
||||
// use: iris.UseFunc(New(...)), iris.Get(...,New(...),...)
|
||||
func New(c Config) iris.HandlerFunc {
|
||||
b := &basicAuthMiddleware{config: DefaultConfig().MergeSingle(c)}
|
||||
b.init()
|
||||
return b.Serve
|
||||
}
|
||||
|
||||
// Default takes one parameter, the users returns a HandlerFunc
|
||||
// use: iris.UseFunc(Default(...)), iris.Get(...,Default(...),...)
|
||||
func Default(users map[string]string) iris.HandlerFunc {
|
||||
c := DefaultConfig()
|
||||
c.Users = users
|
||||
return New(c)
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
// User returns the user from context key same as 'ctx.GetString("user")' but cannot be used by the developer, use the basicauth.Config.User func instead.
|
||||
func (b *basicAuthMiddleware) User(ctx *iris.Context) string {
|
||||
return b.config.User(ctx)
|
||||
}
|
||||
|
||||
func (b *basicAuthMiddleware) init() {
|
||||
// pass the encoded users from the user's config's Users value
|
||||
b.auth = make(encodedUsers, 0, len(b.config.Users))
|
||||
|
||||
for k, v := range b.config.Users {
|
||||
fullUser := k + ":" + v
|
||||
header := "Basic " + base64.StdEncoding.EncodeToString([]byte(fullUser))
|
||||
b.auth = append(b.auth, encodedUser{HeaderValue: header, Username: k, logged: false, expires: DefaultExpireTime})
|
||||
}
|
||||
|
||||
// set the auth realm header's value
|
||||
b.realmHeaderValue = "Basic realm=" + strconv.Quote(b.config.Realm)
|
||||
|
||||
if b.config.Expires > 0 {
|
||||
b.expireEnabled = true
|
||||
}
|
||||
}
|
||||
|
||||
func (b *basicAuthMiddleware) findAuth(headerValue string) (auth *encodedUser, found bool) {
|
||||
if len(headerValue) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
for _, user := range b.auth {
|
||||
if user.HeaderValue == headerValue {
|
||||
auth = &user
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func (b *basicAuthMiddleware) askForCredentials(ctx *iris.Context) {
|
||||
ctx.SetHeader("WWW-Authenticate", b.realmHeaderValue)
|
||||
ctx.SetStatusCode(iris.StatusUnauthorized)
|
||||
}
|
||||
|
||||
// Serve the actual middleware
|
||||
func (b *basicAuthMiddleware) Serve(ctx *iris.Context) {
|
||||
|
||||
if auth, found := b.findAuth(ctx.RequestHeader("Authorization")); !found {
|
||||
b.askForCredentials(ctx)
|
||||
// don't continue to the next handler
|
||||
} else {
|
||||
// all ok set the context's value in order to be getable from the next handler
|
||||
ctx.Set(b.config.ContextKey, auth.Username)
|
||||
if b.expireEnabled {
|
||||
|
||||
if auth.logged == false {
|
||||
auth.expires = time.Now().Add(b.config.Expires)
|
||||
auth.logged = true
|
||||
}
|
||||
|
||||
if time.Now().After(auth.expires) {
|
||||
b.askForCredentials(ctx) // ask for authentication again
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
ctx.Next() // continue
|
||||
}
|
||||
|
||||
}
|
||||
48
middleware/basicauth/config.go
Normal file
48
middleware/basicauth/config.go
Normal file
@@ -0,0 +1,48 @@
|
||||
package basicauth
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/imdario/mergo"
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
)
|
||||
|
||||
const (
|
||||
// DefaultBasicAuthRealm is "Authorization Required"
|
||||
DefaultBasicAuthRealm = "Authorization Required"
|
||||
// DefaultBasicAuthContextKey is the "auth"
|
||||
// this key is used to do context.Set("user", theUsernameFromBasicAuth)
|
||||
DefaultBasicAuthContextKey = "user"
|
||||
)
|
||||
|
||||
// DefaultExpireTime zero time
|
||||
var DefaultExpireTime time.Time // 0001-01-01 00:00:00 +0000 UTC
|
||||
|
||||
// Config the configs for the basicauth middleware
|
||||
type Config struct {
|
||||
// Users a map of login and the value (username/password)
|
||||
Users map[string]string
|
||||
// Realm http://tools.ietf.org/html/rfc2617#section-1.2. Default is "Authorization Required"
|
||||
Realm string
|
||||
// ContextKey the key for ctx.GetString(...). Default is 'user'
|
||||
ContextKey string
|
||||
// Expires expiration duration, default is 0 never expires
|
||||
Expires time.Duration
|
||||
}
|
||||
|
||||
// DefaultConfig returns the default configs for the BasicAuth middleware
|
||||
func DefaultConfig() Config {
|
||||
return Config{make(map[string]string), DefaultBasicAuthRealm, DefaultBasicAuthContextKey, 0}
|
||||
}
|
||||
|
||||
// MergeSingle merges the default with the given config and returns the result
|
||||
func (c Config) MergeSingle(cfg Config) (config Config) {
|
||||
config = cfg
|
||||
mergo.Merge(&config, c)
|
||||
return
|
||||
}
|
||||
|
||||
// User returns the user from context key same as 'ctx.GetString("user")' but cannot be used by the developer, this is only here in order to understand how you can get the authenticated username
|
||||
func (c Config) User(ctx *iris.Context) string {
|
||||
return ctx.GetString(c.ContextKey)
|
||||
}
|
||||
167
middleware/i18n/LICENSE
Normal file
167
middleware/i18n/LICENSE
Normal file
@@ -0,0 +1,167 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction, and
|
||||
distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by the copyright
|
||||
owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all other entities
|
||||
that control, are controlled by, or are under common control with that entity.
|
||||
For the purposes of this definition, "control" means (i) the power, direct or
|
||||
indirect, to cause the direction or management of such entity, whether by
|
||||
contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity exercising
|
||||
permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications, including
|
||||
but not limited to software source code, documentation source, and configuration
|
||||
files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical transformation or
|
||||
translation of a Source form, including but not limited to compiled object code,
|
||||
generated documentation, and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or Object form, made
|
||||
available under the License, as indicated by a copyright notice that is included
|
||||
in or attached to the work (an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object form, that
|
||||
is based on (or derived from) the Work and for which the editorial revisions,
|
||||
annotations, elaborations, or other modifications represent, as a whole, an
|
||||
original work of authorship. For the purposes of this License, Derivative Works
|
||||
shall not include works that remain separable from, or merely link (or bind by
|
||||
name) to the interfaces of, the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including the original version
|
||||
of the Work and any modifications or additions to that Work or Derivative Works
|
||||
thereof, that is intentionally submitted to Licensor for inclusion in the Work
|
||||
by the copyright owner or by an individual or Legal Entity authorized to submit
|
||||
on behalf of the copyright owner. For the purposes of this definition,
|
||||
"submitted" means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems, and
|
||||
issue tracking systems that are managed by, or on behalf of, the Licensor for
|
||||
the purpose of discussing and improving the Work, but excluding communication
|
||||
that is conspicuously marked or otherwise designated in writing by the copyright
|
||||
owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
|
||||
of whom a Contribution has been received by Licensor and subsequently
|
||||
incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License.
|
||||
|
||||
Subject to the terms and conditions of this License, each Contributor hereby
|
||||
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
|
||||
irrevocable copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the Work and such
|
||||
Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License.
|
||||
|
||||
Subject to the terms and conditions of this License, each Contributor hereby
|
||||
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
|
||||
irrevocable (except as stated in this section) patent license to make, have
|
||||
made, use, offer to sell, sell, import, and otherwise transfer the Work, where
|
||||
such license applies only to those patent claims licensable by such Contributor
|
||||
that are necessarily infringed by their Contribution(s) alone or by combination
|
||||
of their Contribution(s) with the Work to which such Contribution(s) was
|
||||
submitted. If You institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work or a
|
||||
Contribution incorporated within the Work constitutes direct or contributory
|
||||
patent infringement, then any patent licenses granted to You under this License
|
||||
for that Work shall terminate as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution.
|
||||
|
||||
You may reproduce and distribute copies of the Work or Derivative Works thereof
|
||||
in any medium, with or without modifications, and in Source or Object form,
|
||||
provided that You meet the following conditions:
|
||||
|
||||
You must give any other recipients of the Work or Derivative Works a copy of
|
||||
this License; and
|
||||
You must cause any modified files to carry prominent notices stating that You
|
||||
changed the files; and
|
||||
You must retain, in the Source form of any Derivative Works that You distribute,
|
||||
all copyright, patent, trademark, and attribution notices from the Source form
|
||||
of the Work, excluding those notices that do not pertain to any part of the
|
||||
Derivative Works; and
|
||||
If the Work includes a "NOTICE" text file as part of its distribution, then any
|
||||
Derivative Works that You distribute must include a readable copy of the
|
||||
attribution notices contained within such NOTICE file, excluding those notices
|
||||
that do not pertain to any part of the Derivative Works, in at least one of the
|
||||
following places: within a NOTICE text file distributed as part of the
|
||||
Derivative Works; within the Source form or documentation, if provided along
|
||||
with the Derivative Works; or, within a display generated by the Derivative
|
||||
Works, if and wherever such third-party notices normally appear. The contents of
|
||||
the NOTICE file are for informational purposes only and do not modify the
|
||||
License. You may add Your own attribution notices within Derivative Works that
|
||||
You distribute, alongside or as an addendum to the NOTICE text from the Work,
|
||||
provided that such additional attribution notices cannot be construed as
|
||||
modifying the License.
|
||||
You may add Your own copyright statement to Your modifications and may provide
|
||||
additional or different license terms and conditions for use, reproduction, or
|
||||
distribution of Your modifications, or for any such Derivative Works as a whole,
|
||||
provided Your use, reproduction, and distribution of the Work otherwise complies
|
||||
with the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions.
|
||||
|
||||
Unless You explicitly state otherwise, any Contribution intentionally submitted
|
||||
for inclusion in the Work by You to the Licensor shall be under the terms and
|
||||
conditions of this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify the terms of
|
||||
any separate license agreement you may have executed with Licensor regarding
|
||||
such Contributions.
|
||||
|
||||
6. Trademarks.
|
||||
|
||||
This License does not grant permission to use the trade names, trademarks,
|
||||
service marks, or product names of the Licensor, except as required for
|
||||
reasonable and customary use in describing the origin of the Work and
|
||||
reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty.
|
||||
|
||||
Unless required by applicable law or agreed to in writing, Licensor provides the
|
||||
Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
|
||||
including, without limitation, any warranties or conditions of TITLE,
|
||||
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
|
||||
solely responsible for determining the appropriateness of using or
|
||||
redistributing the Work and assume any risks associated with Your exercise of
|
||||
permissions under this License.
|
||||
|
||||
8. Limitation of Liability.
|
||||
|
||||
In no event and under no legal theory, whether in tort (including negligence),
|
||||
contract, or otherwise, unless required by applicable law (such as deliberate
|
||||
and grossly negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special, incidental,
|
||||
or consequential damages of any character arising as a result of this License or
|
||||
out of the use or inability to use the Work (including but not limited to
|
||||
damages for loss of goodwill, work stoppage, computer failure or malfunction, or
|
||||
any and all other commercial damages or losses), even if such Contributor has
|
||||
been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability.
|
||||
|
||||
While redistributing the Work or Derivative Works thereof, You may choose to
|
||||
offer, and charge a fee for, acceptance of support, warranty, indemnity, or
|
||||
other liability obligations and/or rights consistent with this License. However,
|
||||
in accepting such obligations, You may act only on Your own behalf and on Your
|
||||
sole responsibility, not on behalf of any other Contributor, and only if You
|
||||
agree to indemnify, defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason of your
|
||||
accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
69
middleware/i18n/README.md
Normal file
69
middleware/i18n/README.md
Normal file
@@ -0,0 +1,69 @@
|
||||
## Middleware information
|
||||
|
||||
This folder contains a middleware for internationalization uses a third-party package named i81n.
|
||||
|
||||
More can be found here:
|
||||
[https://github.com/Unknwon/i18n](https://github.com/Unknwon/i18n)
|
||||
|
||||
## Install
|
||||
|
||||
```sh
|
||||
$ go get -u github.com/iris-contrib/middleware/i18n
|
||||
```
|
||||
|
||||
## Description
|
||||
|
||||
Package i18n is for app Internationalization and Localization.
|
||||
|
||||
|
||||
## How to use
|
||||
|
||||
Create folder named 'locales'
|
||||
```
|
||||
///Files:
|
||||
|
||||
./locales/locale_en-US.ini
|
||||
./locales/locale_el-US.ini
|
||||
```
|
||||
Contents on locale_en-US:
|
||||
```
|
||||
hi = hello, %s
|
||||
```
|
||||
Contents on locale_el-GR:
|
||||
```
|
||||
hi = <20><><EFBFBD><EFBFBD>, %s
|
||||
```
|
||||
|
||||
```go
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/iris-contrib/middleware/i18n"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
iris.UseFunc(i18n.New(i18n.Config{Default: "en-US",
|
||||
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"}}))
|
||||
// or iris.Use(i18n.I18nHandler(....))
|
||||
// or iris.Get("/",i18n.I18n(....), func (ctx *iris.Context){})
|
||||
|
||||
iris.Get("/", func(ctx *iris.Context) {
|
||||
hi := ctx.GetFmt("translate")("hi", "maki") // hi is the key, 'maki' is the %s, the second parameter is optional
|
||||
language := ctx.Get("language") // language is the language key, example 'en-US'
|
||||
|
||||
ctx.Write("From the language %s translated output: %s", language, hi)
|
||||
})
|
||||
|
||||
iris.Listen(":8080")
|
||||
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### [For a working example, click here](https://github.com/kataras/iris/tree/examples/middleware_internationalization_i18n)
|
||||
1
middleware/i18n/_example/locales/locale_el-GR.ini
Normal file
1
middleware/i18n/_example/locales/locale_el-GR.ini
Normal file
@@ -0,0 +1 @@
|
||||
hi = Γεια, %s
|
||||
1
middleware/i18n/_example/locales/locale_en-US.ini
Normal file
1
middleware/i18n/_example/locales/locale_en-US.ini
Normal file
@@ -0,0 +1 @@
|
||||
hi = hello, %s
|
||||
1
middleware/i18n/_example/locales/locale_zh-CN.ini
Normal file
1
middleware/i18n/_example/locales/locale_zh-CN.ini
Normal file
@@ -0,0 +1 @@
|
||||
hi = 您好,%s
|
||||
50
middleware/i18n/_example/main.go
Normal file
50
middleware/i18n/_example/main.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/middleware/i18n"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(httprouter.New()) // adapt a router first of all
|
||||
|
||||
app.Use(i18n.New(i18n.Config{
|
||||
Default: "en-US",
|
||||
URLParameter: "lang",
|
||||
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"}}))
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
|
||||
// it tries to find the language by:
|
||||
// ctx.Get("language") , that should be setted on other middleware before the i18n middleware*
|
||||
// if that was empty then
|
||||
// it tries to find from the URLParameter setted on the configuration
|
||||
// if not found then
|
||||
// it tries to find the language by the "lang" cookie
|
||||
// if didn't found then it it set to the Default setted on the configuration
|
||||
|
||||
// hi is the key, 'kataras' is the %s on the .ini file
|
||||
// the second parameter is optional
|
||||
|
||||
// hi := ctx.Translate("hi", "kataras")
|
||||
// or:
|
||||
hi := i18n.Translate(ctx, "hi", "kataras")
|
||||
|
||||
language := ctx.Get(iris.TranslateLanguageContextKey) // language is the language key, example 'en-US'
|
||||
|
||||
// The first succeed language found saved at the cookie with name ("language"),
|
||||
// you can change that by changing the value of the: iris.TranslateLanguageContextKey
|
||||
ctx.Writef("From the language %s translated output: %s", language, hi)
|
||||
})
|
||||
|
||||
// go to http://localhost:8080/?lang=el-GR
|
||||
// or http://localhost:8080
|
||||
// or http://localhost:8080/?lang=zh-CN
|
||||
app.Listen(":8080")
|
||||
|
||||
}
|
||||
18
middleware/i18n/config.go
Normal file
18
middleware/i18n/config.go
Normal file
@@ -0,0 +1,18 @@
|
||||
package i18n
|
||||
|
||||
// Config the i18n options
|
||||
type Config struct {
|
||||
// Default set it if you want a default language
|
||||
//
|
||||
// Checked: Configuration state, not at runtime
|
||||
Default string
|
||||
// URLParameter is the name of the url parameter which the language can be indentified
|
||||
//
|
||||
// Checked: Serving state, runtime
|
||||
URLParameter string
|
||||
// Languages is a map[string]string which the key is the language i81n and the value is the file location
|
||||
//
|
||||
// Example of key is: 'en-US'
|
||||
// Example of value is: './locales/en-US.ini'
|
||||
Languages map[string]string
|
||||
}
|
||||
101
middleware/i18n/i18n.go
Normal file
101
middleware/i18n/i18n.go
Normal file
@@ -0,0 +1,101 @@
|
||||
package i18n
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
"github.com/Unknwon/i18n"
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
)
|
||||
|
||||
type i18nMiddleware struct {
|
||||
config Config
|
||||
}
|
||||
|
||||
// Serve serves the request, the actual middleware's job is here
|
||||
func (i *i18nMiddleware) Serve(ctx *iris.Context) {
|
||||
wasByCookie := false
|
||||
|
||||
language := i.config.Default
|
||||
if ctx.GetString(iris.TranslateLanguageContextKey) == "" {
|
||||
// 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(iris.TranslateLanguageContextKey)
|
||||
|
||||
if len(language) > 0 {
|
||||
wasByCookie = true
|
||||
} else {
|
||||
// try to get by the request headers(?)
|
||||
if langHeader := ctx.RequestHeader("Accept-Language"); i18n.IsExist(langHeader) {
|
||||
language = langHeader
|
||||
}
|
||||
}
|
||||
}
|
||||
// if it was not taken by the cookie, then set the cookie in order to have it
|
||||
if !wasByCookie {
|
||||
ctx.SetCookieKV(iris.TranslateLanguageContextKey, language)
|
||||
}
|
||||
if language == "" {
|
||||
language = i.config.Default
|
||||
}
|
||||
ctx.Set(iris.TranslateLanguageContextKey, language)
|
||||
}
|
||||
locale := i18n.Locale{Lang: language}
|
||||
|
||||
ctx.Set(iris.TranslateFunctionContextKey, locale.Tr)
|
||||
ctx.Next()
|
||||
}
|
||||
|
||||
// Translate returns the translated word from a context
|
||||
// the second parameter is the key of the world or line inside the .ini file
|
||||
// the third parameter is the '%s' of the world or line inside the .ini file
|
||||
func Translate(ctx *iris.Context, format string, args ...interface{}) string {
|
||||
return ctx.Translate(format, args...)
|
||||
}
|
||||
|
||||
// New returns a new i18n middleware
|
||||
func New(c Config) iris.HandlerFunc {
|
||||
if len(c.Languages) == 0 {
|
||||
panic("You cannot use this middleware without set the Languages option, please try again and read the _example.")
|
||||
}
|
||||
i := &i18nMiddleware{config: c}
|
||||
firstlanguage := ""
|
||||
//load the files
|
||||
for k, v := range c.Languages {
|
||||
if !strings.HasSuffix(v, ".ini") {
|
||||
v += ".ini"
|
||||
}
|
||||
err := i18n.SetMessage(k, v)
|
||||
if err != nil && err != i18n.ErrLangAlreadyExist {
|
||||
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 c.Default == "" {
|
||||
c.Default = firstlanguage
|
||||
}
|
||||
|
||||
i18n.SetDefaultLang(i.config.Default)
|
||||
return i.Serve
|
||||
}
|
||||
|
||||
// TranslatedMap returns translated map[string]interface{} from i18n structure
|
||||
func TranslatedMap(sourceInterface interface{}, ctx *iris.Context) map[string]interface{} {
|
||||
iType := reflect.TypeOf(sourceInterface).Elem()
|
||||
result := make(map[string]interface{})
|
||||
|
||||
for i := 0; i < iType.NumField(); i++ {
|
||||
fieldName := reflect.TypeOf(sourceInterface).Elem().Field(i).Name
|
||||
fieldValue := reflect.ValueOf(sourceInterface).Elem().Field(i).String()
|
||||
|
||||
result[fieldName] = Translate(ctx, fieldValue)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
53
middleware/logger/_example/main.go
Normal file
53
middleware/logger/_example/main.go
Normal file
@@ -0,0 +1,53 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/middleware/logger"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
app.Adapt(iris.DevLogger()) // it just enables the print of the iris.DevMode logs. Enable it to view the middleware's messages.
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
customLogger := logger.New(logger.Config{
|
||||
// Status displays status code
|
||||
Status: true,
|
||||
// IP displays request's remote address
|
||||
IP: true,
|
||||
// Method displays the http method
|
||||
Method: true,
|
||||
// Path displays the request path
|
||||
Path: true,
|
||||
})
|
||||
|
||||
app.Use(customLogger)
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
ctx.Writef("hello")
|
||||
})
|
||||
|
||||
app.Get("/1", func(ctx *iris.Context) {
|
||||
ctx.Writef("hello")
|
||||
})
|
||||
|
||||
app.Get("/2", func(ctx *iris.Context) {
|
||||
ctx.Writef("hello")
|
||||
})
|
||||
|
||||
// log http errors
|
||||
errorLogger := logger.New()
|
||||
|
||||
app.OnError(iris.StatusNotFound, func(ctx *iris.Context) {
|
||||
errorLogger.Serve(ctx)
|
||||
ctx.Writef("My Custom 404 error page ")
|
||||
})
|
||||
|
||||
// http://localhost:8080
|
||||
// http://localhost:8080/1
|
||||
// http://localhost:8080/2
|
||||
app.Listen(":8080")
|
||||
|
||||
}
|
||||
21
middleware/logger/config.go
Normal file
21
middleware/logger/config.go
Normal file
@@ -0,0 +1,21 @@
|
||||
package logger
|
||||
|
||||
// Config are the options of the logger middlweare
|
||||
// contains 4 bools
|
||||
// Status, IP, Method, Path
|
||||
// if set to true then these will print
|
||||
type Config struct {
|
||||
// Status displays status code (bool)
|
||||
Status bool
|
||||
// IP displays request's remote address (bool)
|
||||
IP bool
|
||||
// Method displays the http method (bool)
|
||||
Method bool
|
||||
// Path displays the request path (bool)
|
||||
Path bool
|
||||
}
|
||||
|
||||
// DefaultConfig returns an options which all properties are true except EnableColors
|
||||
func DefaultConfig() Config {
|
||||
return Config{true, true, true, true}
|
||||
}
|
||||
62
middleware/logger/logger.go
Normal file
62
middleware/logger/logger.go
Normal file
@@ -0,0 +1,62 @@
|
||||
package logger
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
)
|
||||
|
||||
type loggerMiddleware struct {
|
||||
config Config
|
||||
}
|
||||
|
||||
// Serve serves the middleware
|
||||
func (l *loggerMiddleware) Serve(ctx *iris.Context) {
|
||||
//all except latency to string
|
||||
var date, status, ip, method, path string
|
||||
var latency time.Duration
|
||||
var startTime, endTime time.Time
|
||||
path = ctx.Path()
|
||||
method = ctx.Method()
|
||||
|
||||
startTime = time.Now()
|
||||
|
||||
ctx.Next()
|
||||
//no time.Since in order to format it well after
|
||||
endTime = time.Now()
|
||||
date = endTime.Format("01/02 - 15:04:05")
|
||||
latency = endTime.Sub(startTime)
|
||||
|
||||
if l.config.Status {
|
||||
status = strconv.Itoa(ctx.ResponseWriter.StatusCode())
|
||||
}
|
||||
|
||||
if l.config.IP {
|
||||
ip = ctx.RemoteAddr()
|
||||
}
|
||||
|
||||
if !l.config.Method {
|
||||
method = ""
|
||||
}
|
||||
|
||||
if !l.config.Path {
|
||||
path = ""
|
||||
}
|
||||
|
||||
//finally print the logs
|
||||
ctx.Log(iris.DevMode, fmt.Sprintf("%s %v %4v %s %s %s \n", date, status, latency, ip, method, path))
|
||||
}
|
||||
|
||||
// New returns the logger middleware
|
||||
// receives optional configs(logger.Config)
|
||||
func New(cfg ...Config) iris.HandlerFunc {
|
||||
c := DefaultConfig()
|
||||
if len(cfg) > 0 {
|
||||
c = cfg[0]
|
||||
}
|
||||
l := &loggerMiddleware{config: c}
|
||||
|
||||
return l.Serve
|
||||
}
|
||||
31
middleware/recover/_example/main.go
Normal file
31
middleware/recover/_example/main.go
Normal file
@@ -0,0 +1,31 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/middleware/recover"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
app.Adapt(iris.DevLogger()) // fast way to enable non-fatal messages to be printed to the user
|
||||
// (yes in iris even recover's errors are not fatal because it's restarting,
|
||||
// ProdMode messages are only for things that Iris cannot continue at all,
|
||||
// these are logged by-default but you can change that behavior too by passing a different LoggerPolicy to the .Adapt)
|
||||
app.Use(recover.New()) // it's io.Writer is the same as app.Config.LoggerOut
|
||||
|
||||
i := 0
|
||||
// let's simmilate a panic every next request
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
i++
|
||||
if i%2 == 0 {
|
||||
panic("a panic here")
|
||||
}
|
||||
ctx.Writef("Hello, refresh one time more to get panic!")
|
||||
})
|
||||
|
||||
// http://localhost:8080
|
||||
app.Listen(":8080")
|
||||
}
|
||||
58
middleware/recover/recover.go
Normal file
58
middleware/recover/recover.go
Normal file
@@ -0,0 +1,58 @@
|
||||
package recover
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"runtime"
|
||||
"strconv"
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
)
|
||||
|
||||
func getRequestLogs(ctx *iris.Context) string {
|
||||
var status, ip, method, path string
|
||||
status = strconv.Itoa(ctx.ResponseWriter.StatusCode())
|
||||
path = ctx.Path()
|
||||
method = ctx.Method()
|
||||
ip = ctx.RemoteAddr()
|
||||
// the date should be logged by iris' Logger, so we skip them
|
||||
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
|
||||
func New() iris.HandlerFunc {
|
||||
return func(ctx *iris.Context) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
if ctx.IsStopped() {
|
||||
return
|
||||
}
|
||||
|
||||
var stacktrace string
|
||||
for i := 1; ; i++ {
|
||||
_, f, l, got := runtime.Caller(i)
|
||||
if !got {
|
||||
break
|
||||
|
||||
}
|
||||
|
||||
stacktrace += fmt.Sprintf("%s:%d\n", f, l)
|
||||
}
|
||||
|
||||
// when stack finishes
|
||||
logMessage := fmt.Sprintf("Recovered from a route's Handler('%s')\n", ctx.GetHandlerName())
|
||||
logMessage += fmt.Sprintf("At Request: %s\n", getRequestLogs(ctx))
|
||||
logMessage += fmt.Sprintf("Trace: %s\n", err)
|
||||
logMessage += fmt.Sprintf("\n%s\n", stacktrace)
|
||||
ctx.Log(iris.DevMode, logMessage)
|
||||
|
||||
ctx.StopExecution()
|
||||
ctx.EmitError(iris.StatusInternalServerError)
|
||||
|
||||
}
|
||||
}()
|
||||
|
||||
ctx.Next()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user