mirror of
https://github.com/kataras/iris.git
synced 2026-02-28 05:26:00 +00:00
Publish the new version ✈️ | Look description please!
# FAQ ### Looking for free support? http://support.iris-go.com https://kataras.rocket.chat/channel/iris ### Looking for previous versions? https://github.com/kataras/iris#version ### Should I upgrade my Iris? Developers are not forced to upgrade if they don't really need it. Upgrade whenever you feel ready. > Iris uses the [vendor directory](https://docs.google.com/document/d/1Bz5-UB7g2uPBdOx-rw5t9MxJwkfpx90cqG9AFL0JAYo) feature, so you get truly reproducible builds, as this method guards against upstream renames and deletes. **How to upgrade**: Open your command-line and execute this command: `go get -u github.com/kataras/iris`. For further installation support, please click [here](http://support.iris-go.com/d/16-how-to-install-iris-web-framework). ### About our new home page http://iris-go.com Thanks to [Santosh Anand](https://github.com/santoshanand) the http://iris-go.com has been upgraded and it's really awesome! [Santosh](https://github.com/santoshanand) is a freelancer, he has a great knowledge of nodejs and express js, Android, iOS, React Native, Vue.js etc, if you need a developer to find or create a solution for your problem or task, please contact with him. The amount of the next two or three donations you'll send they will be immediately transferred to his own account balance, so be generous please! Read more at https://github.com/kataras/iris/blob/master/HISTORY.md Former-commit-id: eec2d71bbe011d6b48d2526eb25919e36e5ad94e
This commit is contained in:
@@ -1,21 +0,0 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2016-2017 Gerasimos Maropoulos
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,3 +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
|
||||
|
||||
import (
|
||||
@@ -5,22 +10,10 @@ import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
// +------------------------------------------------------------+
|
||||
// | 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
|
||||
@@ -41,29 +34,31 @@ type (
|
||||
|
||||
//
|
||||
|
||||
// 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)}
|
||||
// New takes one parameter, the Config returns a Handler
|
||||
// use: iris.Use(New(...)), iris.Get(...,New(...),...)
|
||||
func New(c Config) context.Handler {
|
||||
config := DefaultConfig()
|
||||
if c.ContextKey != "" {
|
||||
config.ContextKey = c.ContextKey
|
||||
}
|
||||
if c.Realm != "" {
|
||||
config.Realm = c.Realm
|
||||
}
|
||||
config.Users = c.Users
|
||||
|
||||
b := &basicAuthMiddleware{config: config}
|
||||
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 {
|
||||
// Default takes one parameter, the users returns a Handler
|
||||
// use: iris.Use(Default(...)), iris.Get(...,Default(...),...)
|
||||
func Default(users map[string]string) context.Handler {
|
||||
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))
|
||||
@@ -98,20 +93,20 @@ func (b *basicAuthMiddleware) findAuth(headerValue string) (auth *encodedUser, f
|
||||
return
|
||||
}
|
||||
|
||||
func (b *basicAuthMiddleware) askForCredentials(ctx *iris.Context) {
|
||||
ctx.SetHeader("WWW-Authenticate", b.realmHeaderValue)
|
||||
ctx.SetStatusCode(iris.StatusUnauthorized)
|
||||
func (b *basicAuthMiddleware) askForCredentials(ctx context.Context) {
|
||||
ctx.Header("WWW-Authenticate", b.realmHeaderValue)
|
||||
ctx.StatusCode(iris.StatusUnauthorized)
|
||||
}
|
||||
|
||||
// Serve the actual middleware
|
||||
func (b *basicAuthMiddleware) Serve(ctx *iris.Context) {
|
||||
func (b *basicAuthMiddleware) Serve(ctx context.Context) {
|
||||
|
||||
if auth, found := b.findAuth(ctx.RequestHeader("Authorization")); !found {
|
||||
if auth, found := b.findAuth(ctx.GetHeader("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)
|
||||
ctx.Values().Set(b.config.ContextKey, auth.Username)
|
||||
if b.expireEnabled {
|
||||
|
||||
if auth.logged == false {
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// 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 (
|
||||
"time"
|
||||
|
||||
"github.com/imdario/mergo"
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -35,14 +38,7 @@ 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)
|
||||
func (c Config) User(ctx context.Context) string {
|
||||
return ctx.Values().GetString(c.ContextKey)
|
||||
}
|
||||
|
||||
@@ -1,189 +0,0 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2016-2017 Gerasimos Maropoulos
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
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
|
||||
@@ -1,3 +1,4 @@
|
||||
// Package i18n provides internalization and localization via middleware. See _examples/intermediate/i18n
|
||||
package i18n
|
||||
|
||||
import (
|
||||
@@ -5,59 +6,61 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/Unknwon/i18n"
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
type i18nMiddleware struct {
|
||||
config Config
|
||||
}
|
||||
|
||||
// Serve serves the request, the actual middleware's job is here
|
||||
func (i *i18nMiddleware) Serve(ctx *iris.Context) {
|
||||
// ServeHTTP serves the request, the actual middleware's job is here
|
||||
func (i *i18nMiddleware) ServeHTTP(ctx context.Context) {
|
||||
wasByCookie := false
|
||||
|
||||
language := i.config.Default
|
||||
if ctx.GetString(iris.TranslateLanguageContextKey) == "" {
|
||||
|
||||
langKey := ctx.Application().ConfigurationReadOnly().GetTranslateLanguageContextKey()
|
||||
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(iris.TranslateLanguageContextKey)
|
||||
language = ctx.GetCookie(langKey)
|
||||
|
||||
if len(language) > 0 {
|
||||
wasByCookie = true
|
||||
} else {
|
||||
// try to get by the request headers(?)
|
||||
if langHeader := ctx.RequestHeader("Accept-Language"); i18n.IsExist(langHeader) {
|
||||
if langHeader := ctx.GetHeader("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)
|
||||
ctx.SetCookieKV(langKey, language)
|
||||
}
|
||||
if language == "" {
|
||||
language = i.config.Default
|
||||
}
|
||||
ctx.Set(iris.TranslateLanguageContextKey, language)
|
||||
ctx.Values().Set(langKey, language)
|
||||
}
|
||||
locale := i18n.Locale{Lang: language}
|
||||
|
||||
ctx.Set(iris.TranslateFunctionContextKey, locale.Tr)
|
||||
translateFuncKey := ctx.Application().ConfigurationReadOnly().GetTranslateFunctionContextKey()
|
||||
ctx.Values().Set(translateFuncKey, 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 {
|
||||
func Translate(ctx context.Context, format string, args ...interface{}) string {
|
||||
return ctx.Translate(format, args...)
|
||||
}
|
||||
|
||||
// New returns a new i18n middleware
|
||||
func New(c Config) iris.HandlerFunc {
|
||||
func New(c Config) context.Handler {
|
||||
if len(c.Languages) == 0 {
|
||||
panic("You cannot use this middleware without set the Languages option, please try again and read the _example.")
|
||||
}
|
||||
@@ -82,11 +85,11 @@ func New(c Config) iris.HandlerFunc {
|
||||
}
|
||||
|
||||
i18n.SetDefaultLang(i.config.Default)
|
||||
return i.Serve
|
||||
return i.ServeHTTP
|
||||
}
|
||||
|
||||
// TranslatedMap returns translated map[string]interface{} from i18n structure
|
||||
func TranslatedMap(sourceInterface interface{}, ctx *iris.Context) map[string]interface{} {
|
||||
func TranslatedMap(sourceInterface interface{}, ctx context.Context) map[string]interface{} {
|
||||
iType := reflect.TypeOf(sourceInterface).Elem()
|
||||
result := make(map[string]interface{})
|
||||
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2016-2017 Gerasimos Maropoulos
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,3 +1,7 @@
|
||||
// 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
|
||||
@@ -16,6 +20,6 @@ type Config struct {
|
||||
}
|
||||
|
||||
// DefaultConfig returns an options which all properties are true except EnableColors
|
||||
func DefaultConfig() Config {
|
||||
func DefaultConfigurationReadOnly() Config {
|
||||
return Config{true, true, true, true}
|
||||
}
|
||||
|
||||
@@ -1,21 +1,25 @@
|
||||
// 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 loger provides request logging via middleware. See _examples/beginner/request-logger
|
||||
package logger
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
type loggerMiddleware struct {
|
||||
type requestLoggerMiddleware struct {
|
||||
config Config
|
||||
}
|
||||
|
||||
// Serve serves the middleware
|
||||
func (l *loggerMiddleware) Serve(ctx *iris.Context) {
|
||||
func (l *requestLoggerMiddleware) ServeHTTP(ctx context.Context) {
|
||||
//all except latency to string
|
||||
var date, status, ip, method, path string
|
||||
var status, ip, method, path string
|
||||
var latency time.Duration
|
||||
var startTime, endTime time.Time
|
||||
path = ctx.Path()
|
||||
@@ -26,11 +30,10 @@ func (l *loggerMiddleware) Serve(ctx *iris.Context) {
|
||||
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())
|
||||
status = strconv.Itoa(ctx.GetStatusCode())
|
||||
}
|
||||
|
||||
if l.config.IP {
|
||||
@@ -45,18 +48,21 @@ func (l *loggerMiddleware) Serve(ctx *iris.Context) {
|
||||
path = ""
|
||||
}
|
||||
|
||||
//finally print the logs
|
||||
ctx.Log(iris.DevMode, fmt.Sprintf("%s %v %4v %s %s %s \n", date, status, latency, ip, method, path))
|
||||
//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)
|
||||
}
|
||||
|
||||
// New returns the logger middleware
|
||||
// receives optional configs(logger.Config)
|
||||
func New(cfg ...Config) iris.HandlerFunc {
|
||||
c := DefaultConfig()
|
||||
// New creates and returns a new request logger middleware.
|
||||
// Do not confuse it with the framework's Logger.
|
||||
// This is for the http requests.
|
||||
//
|
||||
// Receives an optional configuation.
|
||||
func New(cfg ...Config) context.Handler {
|
||||
c := DefaultConfigurationReadOnly()
|
||||
if len(cfg) > 0 {
|
||||
c = cfg[0]
|
||||
}
|
||||
l := &loggerMiddleware{config: c}
|
||||
l := &requestLoggerMiddleware{config: c}
|
||||
|
||||
return l.Serve
|
||||
return l.ServeHTTP
|
||||
}
|
||||
|
||||
@@ -1,59 +1,51 @@
|
||||
// Package pprof usage: app.Get(iris.RouteWildcardPath("/debug/pprof", "action"), pprof.New())
|
||||
// for specific router adaptors follow these optional route syntax:
|
||||
// 'adaptors/httprouter':
|
||||
//
|
||||
// app := iris.New()
|
||||
// app.Adapt(httprouter.New())
|
||||
// app.Get("/debug/pprof/*action", pprof.New())
|
||||
//
|
||||
// 'adaptors/gorillamux':
|
||||
//
|
||||
// app := iris.New()
|
||||
// app.Adapt(gorillamux.New())
|
||||
// app.Get("/debug/pprof/{action:.*}", pprof.New())
|
||||
// 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
|
||||
|
||||
import (
|
||||
"net/http/pprof"
|
||||
"strings"
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/core/handlerconv"
|
||||
)
|
||||
|
||||
// New returns a new pprof (profile, cmdline, symbol, goroutine, heap, threadcreate, debug/block) Middleware.
|
||||
// Note: Route MUST have the last named parameter wildcard named '*action'
|
||||
func New() iris.HandlerFunc {
|
||||
indexHandler := iris.ToHandler(pprof.Index)
|
||||
cmdlineHandler := iris.ToHandler(pprof.Cmdline)
|
||||
profileHandler := iris.ToHandler(pprof.Profile)
|
||||
symbolHandler := iris.ToHandler(pprof.Symbol)
|
||||
goroutineHandler := iris.ToHandler(pprof.Handler("goroutine"))
|
||||
heapHandler := iris.ToHandler(pprof.Handler("heap"))
|
||||
threadcreateHandler := iris.ToHandler(pprof.Handler("threadcreate"))
|
||||
debugBlockHandler := iris.ToHandler(pprof.Handler("block"))
|
||||
// Note: Route MUST have the last named parameter wildcard named '{action:path}'
|
||||
func New() context.Handler {
|
||||
indexHandler := handlerconv.FromStd(pprof.Index)
|
||||
cmdlineHandler := handlerconv.FromStd(pprof.Cmdline)
|
||||
profileHandler := handlerconv.FromStd(pprof.Profile)
|
||||
symbolHandler := handlerconv.FromStd(pprof.Symbol)
|
||||
goroutineHandler := handlerconv.FromStd(pprof.Handler("goroutine"))
|
||||
heapHandler := handlerconv.FromStd(pprof.Handler("heap"))
|
||||
threadcreateHandler := handlerconv.FromStd(pprof.Handler("threadcreate"))
|
||||
debugBlockHandler := handlerconv.FromStd(pprof.Handler("block"))
|
||||
|
||||
return iris.HandlerFunc(func(ctx *iris.Context) {
|
||||
ctx.SetContentType("text/html; charset=" + ctx.Framework().Config.Charset)
|
||||
|
||||
action := ctx.Param("action")
|
||||
if len(action) > 1 {
|
||||
if strings.Contains(action, "cmdline") {
|
||||
cmdlineHandler.Serve((ctx))
|
||||
} else if strings.Contains(action, "profile") {
|
||||
profileHandler.Serve(ctx)
|
||||
} else if strings.Contains(action, "symbol") {
|
||||
symbolHandler.Serve(ctx)
|
||||
} else if strings.Contains(action, "goroutine") {
|
||||
goroutineHandler.Serve(ctx)
|
||||
} else if strings.Contains(action, "heap") {
|
||||
heapHandler.Serve(ctx)
|
||||
} else if strings.Contains(action, "threadcreate") {
|
||||
threadcreateHandler.Serve(ctx)
|
||||
} else if strings.Contains(action, "debug/block") {
|
||||
debugBlockHandler.Serve(ctx)
|
||||
return func(ctx context.Context) {
|
||||
ctx.ContentType("text/html")
|
||||
actionPathParameter := ctx.Values().GetString("action")
|
||||
if len(actionPathParameter) > 1 {
|
||||
if strings.Contains(actionPathParameter, "cmdline") {
|
||||
cmdlineHandler((ctx))
|
||||
} else if strings.Contains(actionPathParameter, "profile") {
|
||||
profileHandler(ctx)
|
||||
} else if strings.Contains(actionPathParameter, "symbol") {
|
||||
symbolHandler(ctx)
|
||||
} else if strings.Contains(actionPathParameter, "goroutine") {
|
||||
goroutineHandler(ctx)
|
||||
} else if strings.Contains(actionPathParameter, "heap") {
|
||||
heapHandler(ctx)
|
||||
} else if strings.Contains(actionPathParameter, "threadcreate") {
|
||||
threadcreateHandler(ctx)
|
||||
} else if strings.Contains(actionPathParameter, "debug/block") {
|
||||
debugBlockHandler(ctx)
|
||||
}
|
||||
} else {
|
||||
indexHandler.Serve(ctx)
|
||||
indexHandler(ctx)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2016-2017 Gerasimos Maropoulos
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,3 +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 recover provides recovery for specific routes or for the whole app via middleware. See _examples/beginner/recover
|
||||
package recover
|
||||
|
||||
import (
|
||||
@@ -5,12 +10,12 @@ import (
|
||||
"runtime"
|
||||
"strconv"
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
func getRequestLogs(ctx *iris.Context) string {
|
||||
func getRequestLogs(ctx context.Context) string {
|
||||
var status, ip, method, path string
|
||||
status = strconv.Itoa(ctx.ResponseWriter.StatusCode())
|
||||
status = strconv.Itoa(ctx.GetStatusCode())
|
||||
path = ctx.Path()
|
||||
method = ctx.Method()
|
||||
ip = ctx.RemoteAddr()
|
||||
@@ -21,8 +26,8 @@ func getRequestLogs(ctx *iris.Context) string {
|
||||
// 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) {
|
||||
func New() context.Handler {
|
||||
return func(ctx context.Context) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
if ctx.IsStopped() {
|
||||
@@ -41,14 +46,14 @@ func New() iris.HandlerFunc {
|
||||
}
|
||||
|
||||
// when stack finishes
|
||||
logMessage := fmt.Sprintf("Recovered from a route's Handler('%s')\n", ctx.GetHandlerName())
|
||||
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.Log(iris.DevMode, logMessage)
|
||||
ctx.Application().Log(logMessage)
|
||||
|
||||
ctx.StopExecution()
|
||||
ctx.EmitError(iris.StatusInternalServerError)
|
||||
ctx.StatusCode(500)
|
||||
|
||||
}
|
||||
}()
|
||||
|
||||
Reference in New Issue
Block a user