Release version 11.2 #1175

Upgrade: v11.2.0
Former-commit-id: 8e641ff1c25d92af0502400f3555f9c49d43e1ca
This commit is contained in:
Gerasimos (Makis) Maropoulos 2019-07-23 19:36:31 +03:00 committed by GitHub
commit 2731ba4772
271 changed files with 10342 additions and 17176 deletions

11
.fossa.yml Normal file
View File

@ -0,0 +1,11 @@
version: 2
cli:
server: https://app.fossa.com
fetcher: custom
project: https://github.com/kataras/iris.git
analyze:
modules:
- name: iris
type: go
target: .
path: .

3
.gitattributes vendored
View File

@ -1,5 +1,4 @@
*.go linguist-language=Go
vendor/* linguist-vendored
_examples/* linguist-documentation
_benchmarks/* linguist-documentation
# Set the default behavior, in case people don't have core.autocrlf set.
@ -10,4 +9,4 @@ _benchmarks/* linguist-documentation
# https://help.github.com/articles/dealing-with-line-endings/#per-repository-settings
* text=auto
# ignore perms
# git config core.filemode false
# git config core.filemode false

7
.gitignore vendored
View File

@ -1,4 +1,7 @@
.vscode
_authortools
/_examples/**/node_modules
.directory
.directory
node_modules
package-lock.json
_benchmarks/benchmarker/benchmarker.exe
_benchmarks/benchmarker/platforms

View File

@ -3,17 +3,13 @@ os:
- linux
- osx
go:
- 1.9.x
- 1.10.x
- 1.11.x
- 1.12.x
go_import_path: github.com/kataras/iris
# we disable test caching via GOCACHE=off
# env:
# global:
# - GOCACHE=off
env:
global:
- GO111MODULE=on
install:
- go get ./... # for iris-contrib/httpexpect, kataras/golog
- go get ./...
script:
- go test -v -cover ./...
after_script:

View File

@ -9,7 +9,7 @@ First of all read our [Code of Conduct](https://github.com/kataras/iris/blob/mas
* Write version of your local Go programming language.
* Describe your problem, what did you expect to see and what you see instead.
* If it's a feature request, describe your idea as better as you can
* optionally, navigate to the [chat](https://kataras.rocket.chat/channel/iris) to push other members to participate and share their thoughts about your brilliant idea.
* optionally, navigate to the [chat](https://chat.iris-go.com) to push other members to participate and share their thoughts about your brilliant idea.
2. Fork the [repository](https://github.com/kataras/iris).
3. Make your changes.
4. Compare & Push the PR from [here](https://github.com/kataras/iris/compare).

60
FAQ.md
View File

@ -21,9 +21,11 @@ Add a `badge` to your open-source projects powered by [Iris](https://iris-go.com
## How to upgrade
```sh
go get -u github.com/kataras/iris
go get github.com/kataras/iris@v11.2.0
```
Go version 1.12 and above is required.
## Learning
More than 100 practical examples, tutorials and articles at:
@ -39,40 +41,9 @@ More than 100 practical examples, tutorials and articles at:
Want to help and join to the greatest community? Describe your skills and push your own sections at: https://github.com/kataras/build-a-better-web-together/issues/new
### common errors that new gophers may meet
#### type aliases
| build error | reason | solution |
| -----------|--------|--------|
| `undefined iris.Context` | caused of using the **optional type alias** `iris.Context` instead of the `context.Context` when building with Go 1.8 | import the original package `github.com/kataras/iris/context` and declare as `func(context.Context){})` **or** download and install the [latest go version](https://golang.org/dl) _recommended_ |
Type alias is a new feature, introduced at Go version 1.9, so if you want to use Iris' type aliases you have to build using the latest Go version. Nothing really changes for your application if you use type alias or not, Iris' type aliases helps you to omit import statements -- to reduce lines of code, nothing more.
**Details...**
Go version 1.9 introduced the [type alias](https://golang.org/doc/go1.9#language) feature.
Iris uses the `type alias` feature to help you writing less code by omitting some package imports. The examples and documentation are written using Go 1.9 as well.
If you build your Go app with Go 1.9 you can, optionally, use all Iris web framework's features by importing one single package, the `github.com/kataras/iris`.
Available type aliases;
| Go 1.8 | Go 1.8 usage | Go 1.9 usage (optionally) |
| -----------|--------|--------|
| `import "github.com/kataras/iris/context"` | `func(context.Context) {}`, `context.Handler`, `context.Map` | `func(iris.Context) {}`, `iris.Handler`, `iris.Map` |
| `import "github.com/kataras/iris/mvc"` | `type MyController struct { mvc.Controller }` , `mvc.SessionController` | `type MyController struct { iris.Controller }`, `iris.SessionController` |
| `import "github.com/kataras/iris/core/router"` | `app.PartyFunc("/users", func(p router.Party) {})` | `app.PartyFunc("/users", func(p iris.Party) {})` |
| `import "github.com/kataras/iris/core/host"` | `app.ConfigureHost(func(s *host.Supervisor) {})` | `app.ConfigureHost(func(s *iris.Supervisor) {})` |
You can find all type aliases and their original package import statements at the [./context.go file](context.go).
> Remember; this doesn't mean that you have to use those type aliases, you can still import the original packages as you did with Go version 1.8, it's up to you.
## Active development mode
Iris may have reached version 10, but we're not stopping there. We have many feature ideas on our board that we're anxious to add and other innovative web development solutions that we're planning to build into Iris.
Iris may have reached version 11, but we're not stopping there. We have many feature ideas on our board that we're anxious to add and other innovative web development solutions that we're planning to build into Iris.
## Can I find a job if I learn how to use Iris?
@ -81,33 +52,12 @@ open for Iris-specific developers the time we speak.
Go to our facebook page, like it and receive notifications about new job offers, we already have couple of them stay at the top of the page: https://www.facebook.com/iris.framework
<!--
## Can Iris be used in production after Dubai purchase?
Yes, now more than ever.
https://github.com/kataras/iris/issues/711
-------
UPDATE which I could mention by the beginning of the Decemember of 2017:
Nothing keeps for ever, and we should move on to greater things.
As you probably know, I was hired to develop an inside Iris version for a Dubai-based startup company's specific requirements in the same time I was developing the open-source Iris repository with your help this time as well!
As our first deal was to end this agreement via last-time negotiatations by the end of the current year (2017), the
agreement ended unofficially at 22 Novemember of 2017 (officially some weeks later, paper work), and after a week I came back to Greece as you may understood from the regularly commits and improvements to the public repository that I pushed.
-->
## Do we have a community Chat?
Yes, https://chat.iris-go.com
https://github.com/kataras/iris/issues/646
## How is the development of Iris supported?
By normal people, like you, who help us by donating small or large amounts of money.
Help this project deliver awesome and unique features with the highest possible code quality by donating any amount via [PayPal](https://www.paypal.me/kataras). Your name will be published [here](https://iris-go.com/donate) after your approval via e-mail.
Help this project deliver awesome and unique features with the highest possible code quality by donating any amount via [PayPal](https://www.paypal.me/kataras). Your name will be published [here](https://iris-go.com) after your approval via e-mail.

View File

@ -1,4 +1,6 @@
# History/Changelog <a href="HISTORY_ZH.md"> <img width="20px" src="https://iris-go.com/images/flag-china.svg?v=10" /></a><a href="HISTORY_ID.md"> <img width="20px" src="https://iris-go.com/images/flag-indonesia.svg?v=10" /></a><a href="HISTORY_GR.md"> <img width="20px" src="https://iris-go.com/images/flag-greece.svg?v=10" /></a>
<!-- # History/Changelog <a href="HISTORY_ZH.md"> <img width="20px" src="https://iris-go.com/images/flag-china.svg?v=10" /></a><a href="HISTORY_ID.md"> <img width="20px" src="https://iris-go.com/images/flag-indonesia.svg?v=10" /></a><a href="HISTORY_GR.md"> <img width="20px" src="https://iris-go.com/images/flag-greece.svg?v=10" /></a> -->
# Changelog
### Looking for free and real-time support?
@ -9,974 +11,16 @@
https://github.com/kataras/iris/releases
### Want to be hired?
https://facebook.com/iris.framework
### 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 github.com/kataras/iris@v11.2.0`.
**How to upgrade**: Open your command-line and execute this command: `go get -u github.com/kataras/iris` or let the automatic updater do that for you.
# Tu, 23 July 2019 | v11.2.0
# Fr, 11 January 2019 | v11.1.1
Happy new year! This is a minor release, contains mostly bug fixes.
Strange that we don't have major features in this release, right? Don't worry, I am not out of ideas (at least not yet!).
I have some features in-mind but lately I do not have the time to humanize those ideas for you due to my new position in [Netdata Inc.](https://github.com/netdata/netdata), so be patient and [stay-tuned](https://github.com/kataras/iris/stargazers). Read the current changelog below:
- session/redis: fix unused service config var. IdleTimeout witch was replaced by default values. [#1140](https://github.com/kataras/iris/pull/1140) ([@d7561985](https://github.com/d7561985))
- fix [#1141](https://github.com/kataras/iris/issues/1141) and [#1142](https://github.com/kataras/iris/issues/1142). [2bd7a8e88777766d1f4cac7562feec304112d2b1](https://github.com/kataras/iris/commit/2bd7a8e88777766d1f4cac7562feec304112d2b1) (@kataras)
- fix cache corruption due to recorder reuse. [#1146](https://github.com/kataras/iris/pull/1146) ([@Slamper](https://github.com/Slamper))
- add `StatusTooEarly`, compatible with: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/425#Browser_compatibility. [31b2913447aa9e41e16a3eb33eb0019427e15cea](https://github.com/kataras/iris/commit/31b2913447aa9e41e16a3eb33eb0019427e15cea) (@kataras)
- fix [#1164](https://github.com/kataras/iris/issues/1164). [701e8e46c20395f87fa34bf9fabd145074c7b78c](https://github.com/kataras/iris/commit/701e8e46c20395f87fa34bf9fabd145074c7b78c) (@kataras)
- `context#ReadForm` can skip unkown fields by `IsErrPath(err)`, fixes: [#1157](https://github.com/kataras/iris/issues/1157). [1607bb5113568af6a34142f23bfa44903205b314](https://github.com/kataras/iris/commit/1607bb5113568af6a34142f23bfa44903205b314) (@kataras)
Doc updates:
- fix grammar and misspell. [5069e9afd8700d20dfd04cdc008efd671b5d0b40](https://github.com/kataras/iris/commit/5069e9afd8700d20dfd04cdc008efd671b5d0b40) (@kataras)
- fix link for httpexpect in README. [#1148](https://github.com/kataras/iris/pull/1148) ([@drenel18](https://github.com/drenel18))
- translate _examples/README.md into Chinese. [#1156](https://github.com/kataras/iris/pull/1156) ([@fduxiao](https://github.com/fduxiao))
- add https://github.com/snowlyg/IrisApiProject to starter kits (Chinese). [ea12533871253afc34e40e36ba658b51955ea82d](https://github.com/kataras/iris/commit/ea12533871253afc34e40e36ba658b51955ea82d)
- add https://github.com/yz124/superstar to starter kits (Chinese). [0e734ff8445f07482c28881347c1e564dc5aab9c](https://github.com/kataras/iris/commit/0e734ff8445f07482c28881347c1e564dc5aab9c)
# Su, 18 November 2018 | v11.1.0
PR: https://github.com/kataras/iris/pull/1130
This release contains a new feature for versioning your Iris APIs. The initial motivation and feature request came by https://github.com/kataras/iris/issues/1129.
The [versioning](https://github.com/kataras/iris/tree/master/versioning) package provides [semver](https://semver.org/) versioning for your APIs. It implements all the suggestions written at [api-guidelines](https://github.com/byrondover/api-guidelines/blob/master/Guidelines.md#versioning) and more.
The version comparison is done by the [go-version](https://github.com/hashicorp/go-version) package. It supports matching over patterns like `">= 1.0, < 3"` and etc.
## Features
- per route version matching, a normal iris handler with "switch" cases via Map for version => handler
- per group versioned routes and deprecation API
- version matching like ">= 1.0, < 2.0" or just "2.0.1" and etc.
- version not found handler (can be customized by simply adding the versioning.NotFound: customNotMatchVersionHandler on the Map)
- version is retrieved from the "Accept" and "Accept-Version" headers (can be customized via middleware)
- respond with "X-API-Version" header, if version found.
- deprecation options with customizable "X-API-Warn", "X-API-Deprecation-Date", "X-API-Deprecation-Info" headers via `Deprecated` wrapper.
## Get version
Current request version is retrieved by `versioning.GetVersion(ctx)`.
By default the `GetVersion` will try to read from:
- `Accept` header, i.e `Accept: "application/json; version=1.0"`
- `Accept-Version` header, i.e `Accept-Version: "1.0"`
You can also set a custom version for a handler via a middleware by using the context's store values.
For example:
```go
func(ctx iris.Context) {
ctx.Values().Set(versioning.Key, ctx.URLParamDefault("version", "1.0"))
ctx.Next()
}
```
## Match version to handler
The `versioning.NewMatcher(versioning.Map) iris.Handler` creates a single handler which decides what handler need to be executed based on the requested version.
```go
app := iris.New()
// middleware for all versions.
myMiddleware := func(ctx iris.Context) {
// [...]
ctx.Next()
}
myCustomNotVersionFound := func(ctx iris.Context) {
ctx.StatusCode(404)
ctx.Writef("%s version not found", versioning.GetVersion(ctx))
}
userAPI := app.Party("/api/user")
userAPI.Get("/", myMiddleware, versioning.NewMatcher(versioning.Map{
"1.0": sendHandler(v10Response),
">= 2, < 3": sendHandler(v2Response),
versioning.NotFound: myCustomNotVersionFound,
}))
```
### Deprecation
Using the `versioning.Deprecated(handler iris.Handler, options versioning.DeprecationOptions) iris.Handler` function you can mark a specific handler version as deprecated.
```go
v10Handler := versioning.Deprecated(sendHandler(v10Response), versioning.DeprecationOptions{
// if empty defaults to: "WARNING! You are using a deprecated version of this API."
WarnMessage string
DeprecationDate time.Time
DeprecationInfo string
})
userAPI.Get("/", versioning.NewMatcher(versioning.Map{
"1.0": v10Handler,
// [...]
}))
```
This will make the handler to send these headers to the client:
- `"X-API-Warn": options.WarnMessage`
- `"X-API-Deprecation-Date": context.FormatTime(ctx, options.DeprecationDate))`
- `"X-API-Deprecation-Info": options.DeprecationInfo`
> versioning.DefaultDeprecationOptions can be passed instead if you don't care about Date and Info.
## Grouping routes by version
Grouping routes by version is possible as well.
Using the `versioning.NewGroup(version string) *versioning.Group` function you can create a group to register your versioned routes.
The `versioning.RegisterGroups(r iris.Party, versionNotFoundHandler iris.Handler, groups ...*versioning.Group)` must be called in the end in order to register the routes to a specific `Party`.
```go
app := iris.New()
userAPI := app.Party("/api/user")
// [... static serving, middlewares and etc goes here].
userAPIV10 := versioning.NewGroup("1.0")
userAPIV10.Get("/", sendHandler(v10Response))
userAPIV2 := versioning.NewGroup(">= 2, < 3")
userAPIV2.Get("/", sendHandler(v2Response))
userAPIV2.Post("/", sendHandler(v2Response))
userAPIV2.Put("/other", sendHandler(v2Response))
versioning.RegisterGroups(userAPI, versioning.NotFoundHandler, userAPIV10, userAPIV2)
```
> A middleware can be registered to the actual `iris.Party` only, using the methods we learnt above, i.e by using the `versioning.Match` in order to detect what code/handler you want to be executed when "x" or no version is requested.
### Deprecation for Group
Just call the `Deprecated(versioning.DeprecationOptions)` on the group you want to notify your API consumers that this specific version is deprecated.
```go
userAPIV10 := versioning.NewGroup("1.0").Deprecated(versioning.DefaultDeprecationOptions)
```
## Compare version manually from inside your handlers
```go
// reports if the "version" is matching to the "is".
// the "is" can be a constraint like ">= 1, < 3".
If(version string, is string) bool
```
```go
// same as `If` but expects a Context to read the requested version.
Match(ctx iris.Context, expectedVersion string) bool
```
```go
app.Get("/api/user", func(ctx iris.Context) {
if versioning.Match(ctx, ">= 2.2.3") {
// [logic for >= 2.2.3 version of your handler goes here]
return
}
})
```
Example can be found [here](_examples/versioning/main.go).
# Fr, 09 November 2018 | v11.0.4
Add `Configuration.DisablePathCorrectionRedirection` - `iris.WithoutPathCorrectionRedirection` to support
direct handler execution of the matching route without the last `'/'` instead of sending a redirect response when `DisablePathCorrection` is set to false(default behavior).
Usage:
For example, CORS needs the allow origin headers in redirect response as well,
however is not possible from the router to know what headers a route's handler will send to the client.
So the best option we have is to just execute the handler itself instead of sending a redirect response.
Add the `app.Run(..., iris.WithoutPathCorrectionRedirection)` on the server side if you wish
to directly fire the handler instead of redirection (which is the default behavior)
on request paths like `"$yourdomain/v1/mailer/"` when `"/v1/mailer"` route handler is registered.
Example Code:
```go
package main
import "github.com/kataras/iris"
func main() {
app := iris.New()
crs := func(ctx iris.Context) {
ctx.Header("Access-Control-Allow-Origin", "*")
ctx.Header("Access-Control-Allow-Credentials", "true")
ctx.Header("Access-Control-Allow-Headers",
"Access-Control-Allow-Origin,Content-Type")
ctx.Next()
}
v1 := app.Party("/api/v1", crs).AllowMethods(iris.MethodOptions)
{
v1.Post("/mailer", func(ctx iris.Context) {
var any iris.Map
err := ctx.ReadJSON(&any)
if err != nil {
ctx.WriteString(err.Error())
ctx.StatusCode(iris.StatusBadRequest)
return
}
ctx.Application().Logger().Infof("received %#+v", any)
})
}
// HERE:
app.Run(iris.Addr(":80"), iris.WithoutPathCorrectionRedirection)
}
```
# Tu, 06 November 2018 | v11.0.3
- add "part" html view engine's tmpl function: [15bb55d](https://github.com/kataras/iris/commit/15bb55d85eac378bbe0c98c10ffea938cc05fe4d)
- update pug engine's vendor: [c20bc3b](https://github.com/kataras/iris/commit/c20bc3bceef158ef99931e609123fa0aca2a918c)
# Tu, 30 October 2018 | v11.0.2
Fix [memstore](core/memstore/memstore.go) overflows when build 32 bit app, reported and fixed by [@bouroo](https://github.com/bouroo) at: https://github.com/kataras/iris/issues/1118
# Su, 28 October 2018 | v11.0.1
- Update benchmarks: https://github.com/kataras/iris/commit/d1b47b1ec65ae77a2ca7485e510386f4a5456ac4
- Add link for third-party source benchmarks: https://github.com/kataras/iris/commit/64e80a7ee5c23ed938ddc8b68d181a25420c7653
- Add optionally custom low-level websocket message data prefix as requested at: https://github.com/kataras/iris/issues/1113 by [@jjhesk](https://github.com/jjhesk). Example:
```go
app := iris.New()
// [...]
wsServer := websocket.New(websocket.Config{
// [...]
EvtMessagePrefix: []byte("my-custom-prefix:"),
})
// [...]
// serve the javascript built'n client-side library,
// see websockets.html script tags, this path is used.
app.Any("/iris-ws.js", func(ctx iris.Context) {
ctx.Write(wsServer.ClientSource)
})
// [...]
```
# Su, 21 October 2018 | v11.0.0
For the craziest of us, click [here](https://github.com/kataras/iris/compare/v10.7.0...v11) 🔥 to find out the commits and the code changes since our previous release.
## Breaking changes
- Remove the "Configurator" `WithoutVersionChecker` and the configuration field `DisableVersionChecker`
- `:int` parameter type **can accept negative numbers now**.
- `app.Macros().String/Int/Uint64/Path...RegisterFunc` should be replaced to: `app.Macros().Get("string" or "int" or "uint64" or "path" when "path" is the ":path" parameter type).RegisterFunc`, because you can now add custom macros and parameter types as well, see [here](_examples/routing/macros).
- `RegisterFunc("min", func(paramValue string) bool {...})` should be replaced to `RegisterFunc("min", func(paramValue <T>) bool {...})`, the `paramValue` argument is now stored in the exact type the macro's type evaluator inits it, i.e `uint64` or `int` and so on, therefore you don't have to convert the parameter value each time (this should make your handlers with macro functions activated even faster now)
- The `Context#ReadForm` will no longer return an error if it has no value to read from the request, we let those checks to the caller and validators as requested at: https://github.com/kataras/iris/issues/1095 by [@haritsfahreza](https://github.com/haritsfahreza)
## Routing
I wrote a [new router implementation](https://github.com/kataras/muxie#philosophy) for our Iris internal(low-level) routing mechanism, it is good to know that this was the second time we have updated the router internals without a single breaking change after the v6, thanks to the very well-written and designed-first code we have for the high-level path syntax component called [macro interpreter](macro/interpreter).
The new router supports things like **closest wildcard resolution**.
> If the name doesn't sound good to you it is because I named that feature myself, I don't know any other framework or router that supports a thing like that so be gentle:)
Previously you couldn't register routes like: `/{myparam:path}` and `/static` and `/{myparam:string}` and `/{myparam:string}/static` and `/static/{myparam:string}` all in one path prefix without a "decision handler". And generally if you had a wildcard it was possible to add (a single) static part and (a single) named parameter but not without performance cost and limits, why only one? (one is better than nothing: look the Iris' alternatives) We struggle to overcome our own selves, now you **can definitely do it without a bit of performance cost**, and surely we hand't imagine the wildcard to **catch all if nothing else found** without huge routing performance cost, the wildcard(`:path`) meant ONLY: "accept one or more path segments and put them into the declared parameter" so if you had register a dynamic single-path-segment named parameter like `:string, :int, :uint, :alphabetical...` in between those path segments it wouldn't work. The **closest wildcard resolution** offers you the opportunity to design your APIs even better via custom handlers and error handlers like `404 not found` to path prefixes for your API's groups, now you can do it without any custom code for path resolution inside a "decision handler" or a middleware.
Code worths 1000 words, now it is possible to define your routes like this without any issues:
```go
package main
import (
"github.com/kataras/iris"
"github.com/kataras/iris/context"
)
func main() {
app := iris.New()
// matches everyhing if nothing else found,
// so you can use it for custom 404 root-level/main pages!
app.Get("/{p:path}", func(ctx context.Context) {
path := ctx.Params().Get("p")
// gives the path without the first "/".
ctx.Writef("Site Custom 404 Error Message\nPage of: '%s' not found", path)
})
app.Get("/", indexHandler)
// request: http://localhost:8080/profile
// response: "Profile Index"
app.Get("/profile", func(ctx context.Context) {
ctx.Writef("Profile Index")
})
// request: http://localhost:8080/profile/kataras
// response: "Profile of username: 'kataras'"
app.Get("/profile/{username}", func(ctx context.Context) {
username := ctx.Params().Get("username")
ctx.Writef("Profile of username: '%s'", username)
})
// request: http://localhost:8080/profile/settings
// response: "Profile personal settings"
app.Get("/profile/settings", func(ctx context.Context) {
ctx.Writef("Profile personal settings")
})
// request: http://localhost:8080/profile/settings/security
// response: "Profile personal security settings"
app.Get("/profile/settings/security", func(ctx context.Context) {
ctx.Writef("Profile personal security settings")
})
// matches everyhing /profile/*somethng_here*
// if no other route matches the path semgnet after the
// /profile or /profile/
//
// So, you can use it for custom 404 profile pages
// side-by-side to your root wildcard without issues!
// For example:
// request: http://localhost:8080/profile/kataras/what
// response:
// Profile Page Custom 404 Error Message
// Profile Page of: 'kataras/what' was unable to be found
app.Get("/profile/{p:path}", func(ctx context.Context) {
path := ctx.Params().Get("p")
ctx.Writef("Profile Page Custom 404 Error Message\nProfile Page of: '%s' not found", path)
})
app.Run(iris.Addr(":8080"))
}
func indexHandler(ctx context.Context) {
ctx.HTML("This is the <strong>index page</strong>")
}
```
The `github.com/kataras/iris/core/router.AllMethods` is now a variable that can be altered by end-developers, so things like `app.Any` can register to custom methods as well, as requested at: https://github.com/kataras/iris/issues/1102. For example, import that package and do `router.AllMethods = append(router.AllMethods, "LINK")` in your `main` or `init` function.
The old `github.com/kataras/iris/core/router/macro` package was moved to `guthub.com/kataras/iris/macro` to allow end-developers to add custom parameter types and macros, it supports all go standard types by default as you will see below.
- `:int` parameter type as an alias to the old `:int` which can accept any numeric path segment now, both negative and positive numbers
- Add `:int8` parameter type and `ctx.Params().GetInt8`
- Add `:int16` parameter type and `ctx.Params().GetInt16`
- Add `:int32` parameter type and `ctx.Params().GetInt32`
- Add `:int64` parameter type and `ctx.Params().GetInt64`
- Add `:uint` parameter type and `ctx.Params().GetUint`
- Add `:uint8` parameter type and `ctx.Params().GetUint8`
- Add `:uint16` parameter type and `ctx.Params().GetUint16`
- Add `:uint32` parameter type and `ctx.Params().GetUint32`
- Add `:uint64` parameter type and `ctx.Params().GetUint64`
- Add alias `:bool` for the `:boolean` parameter type
Here is the full list of the built'n parameter types that we support now, including their validations/path segment rules.
| Param Type | Go Type | Validation | Retrieve Helper |
| -----------------|------|-------------|------|
| `:string` | string | the default if param type is missing, anything (single path segment) | `Params().Get` |
| `:int` | int | -9223372036854775808 to 9223372036854775807 (x64) or -2147483648 to 2147483647 (x32), depends on the host arch | `Params().GetInt` |
| `:int8` | int8 | -128 to 127 | `Params().GetInt8` |
| `:int16` | int16 | -32768 to 32767 | `Params().GetInt16` |
| `:int32` | int32 | -2147483648 to 2147483647 | `Params().GetInt32` |
| `:int64` | int64 | -9223372036854775808 to 9223372036854775807 | `Params().GetInt64` |
| `:uint` | uint | 0 to 18446744073709551615 (x64) or 0 to 4294967295 (x32), depends on the host arch | `Params().GetUint` |
| `:uint8` | uint8 | 0 to 255 | `Params().GetUint8` |
| `:uint16` | uint16 | 0 to 65535 | `Params().GetUint16` |
| `:uint32` | uint32 | 0 to 4294967295 | `Params().GetUint32` |
| `:uint64` | uint64 | 0 to 18446744073709551615 | `Params().GetUint64` |
| `:bool` | bool | "1" or "t" or "T" or "TRUE" or "true" or "True" or "0" or "f" or "F" or "FALSE" or "false" or "False" | `Params().GetBool` |
| `:alphabetical` | string | lowercase or uppercase letters | `Params().Get` |
| `:file` | string | lowercase or uppercase letters, numbers, underscore (_), dash (-), point (.) and no spaces or other special characters that are not valid for filenames | `Params().Get` |
| `:path` | string | anything, can be separated by slashes (path segments) but should be the last part of the route path | `Params().Get` |
**Usage**:
```go
app.Get("/users/{id:uint64}", func(ctx iris.Context){
id, _ := ctx.Params().GetUint64("id")
// [...]
})
```
| Built'n Func | Param Types |
| -----------|---------------|
| `regexp`(expr string) | :string |
| `prefix`(prefix string) | :string |
| `suffix`(suffix string) | :string |
| `contains`(s string) | :string |
| `min`(minValue int or int8 or int16 or int32 or int64 or uint8 or uint16 or uint32 or uint64 or float32 or float64) | :string(char length), :int, :int8, :int16, :int32, :int64, :uint, :uint8, :uint16, :uint32, :uint64 |
| `max`(maxValue int or int8 or int16 or int32 or int64 or uint8 or uint16 or uint32 or uint64 or float32 or float64) | :string(char length), :int, :int8, :int16, :int32, :int64, :uint, :uint8, :uint16, :uint32, :uint64 |
| `range`(minValue, maxValue int or int8 or int16 or int32 or int64 or uint8 or uint16 or uint32 or uint64 or float32 or float64) | :int, :int8, :int16, :int32, :int64, :uint, :uint8, :uint16, :uint32, :uint64 |
**Usage**:
```go
app.Get("/profile/{name:alphabetical max(255)}", func(ctx iris.Context){
name := ctx.Params().Get("name")
// len(name) <=255 otherwise this route will fire 404 Not Found
// and this handler will not be executed at all.
})
```
## Vendoring
- Rename the vendor `sessions/sessiondb/vendor/...bbolt` from `coreos/bbolt` to `etcd-io/bbolt` and update to v1.3.1, based on [that](https://github.com/etcd-io/bbolt/releases/tag/v1.3.1-etcd.7)
- Update the vendor `sessions/sessiondb/vendor/...badger` to v1.5.3
I believe it is soon to adapt the new [go modules](https://github.com/golang/go/wiki/Modules#table-of-contents) inside Iris, the new `go mod` command may change until go 1.12, it is still an experimental feature.
The [vendor](https://github.com/kataras/iris/tree/master/vendor) folder will be kept until the majority of Go developers get acquainted with the new `go modules`. The `go.mod` and `go.sum` files will come at `iris v12` (or `go 1.12`), we could do that on this version as well but I don't want to have half-things, versioning should be passed on import path as well and that is a large breaking change to go with it right now, so it will probably have a new path such as `github.com/kataras/iris/v12` based on a `git tag` like every Iris release (we are lucky here because we used semantic versioning from day zero). No folder re-structure inside the root git repository to split versions will ever happen, so backwards-compatibility for older go versions(before go 1.9.3) and iris versions will be not enabled by-default although it's easy for anyone to grab any version from older [releases](https://github.com/kataras/iris/releases) or branch and target that.
# Sat, 11 August 2018 | v10.7.0
I am overjoyed to announce stage 1 of the the Iris Web framework **10.7 stable release is now available**.
Version 10.7.0 is part of the official [releases](https://github.com/kataras/iris/releases).
This release does not contain any breaking changes to existing Iris-based projects built on older versions of Iris. Iris developers can upgrade with absolute safety.
Read below the changes and the improvements to the framework's internals. We also have more examples for beginners in our community.
## New Examples
- [Iris + WebAssemply = 💓](_examples/webassembly/basic/main.go) **compatible only for projects built with go11.beta and above**
- [Server-Sent Events](_examples/http_responsewriter/sse/main.go)
- [Struct Validation on context.ReadJSON](_examples/http_request/read-json-struct-validation/main.go)
- [Extract referrer from "referer" header or URL query parameter](_examples/http_request/extract-referer/main.go)
- [Hero Sessions](_examples/hero/sessions)
- [Yet another dependency injection example with hero](_examples/hero/smart-contract/main.go)
- [Writing an API for the Apache Kafka](_examples/tutorial/api-for-apache-kafka)
> Also, all "sessions" examples have been customized to include the `AllowReclaim: true` option.
## kataras/iris/websocket
- Change connection list from a customized slice to `sync.Map` with: [this](https://github.com/kataras/iris/commit/5f16704f45bedd767527eadf411cf9bc0f8edaee) and [that commit](https://github.com/kataras/iris/commit/16b30e8eed1406c61abc01282120870bd9fa31d8)
- Minify and add the `iris-ws.js` to the famous https://cdnjs.com via [this PR](https://github.com/kataras/iris/pull/1053) made by [Dibyendu Das](https://github.com/dibyendu)
## kataras/iris/core/router
- Add `json` field tags and new functions such as `ChangeMethod`, `SetStatusOffline` and `RestoreStatus` to the `Route` structure, these type of changes to the routes at runtime have effect after the manual call of the `Router/Application.RefreshRouter()` (not recommended but useful for custom Iris web server's remote control panels)
- Add `GetRoutesReadOnly` function to the `APIBuilder` structure
## kataras/iris/context
- Add `GetReferrer`, `GetContentTypeRequested` and `URLParamInt32Default` functions
- Insert `Trace`, `Tmpl` and `MainHandlerName` functions to the `RouteReadOnly` interface
- Add `OnConnectionClose` function listener to fire a callback when the underline tcp connection is closed, extremely useful for SSE or other loop-forever implementations inside a handler -- and `OnClose` which is the same as `OnConnectionClose(myFunc)` and `defer myFunc()` [*](https://github.com/kataras/iris/commit/6898c2f755a0e22aa42e3b1799e29c857777a6f9)
This release contains minor grammar and typo fixes and more meaningful [godoc](https://godoc.org/github.com/kataras/iris) code comments too.
## Industry
I am glad to announce that Iris has been chosen as the main development kit for eight medium-to-large sized companies and a new very promising India-based startup. I want to thank you once again for the unwavering support and trust you have shown me, especially this year, despite the past unfair rumours and defamation that we suffered by the merciless competition.
# Tu, 05 June 2018 | v10.6.6
- **view/pug**: update vendor for Pug (Jade) parser and add [Iris + Pug examples](https://github.com/kataras/iris/tree/master/_examples#view) via [this commit](https://github.com/kataras/iris/commit/e0171cbed69efecba199ef547aa5e7063e18b27a), relative to [issue #1003](https://github.com/kataras/iris/issues/1003) opened by [@DjLeChuck](https://github.com/DjLeChuck)
- **middleware/logger**: new configuration field, defaults to false: `Query bool`, if true prints the full path, including the URL query as requested at [issue #1017](https://github.com/kataras/iris/issues/1017) by [@andr33z](https://github.com/andr33z). Example [here](https://github.com/kataras/iris/blob/master/_examples/http_request/request-logger/main.go#L21). Implemented by [this commit](https://github.com/kataras/iris/commit/a7364876e0d1b8bd60acf94f17f6d1341b16c617)
- **cookies**: some minor but helpful additions, like `CookieOption` relative to [issue #1018](https://github.com/kataras/iris/issues/1018) asked by [@dibyendu](https://github.com/dibyendu). [Cookies examples added](https://github.com/kataras/iris/tree/master/_examples/cookies) too. Implemented by [this commit](https://github.com/kataras/iris/commit/574414a64ed3d8736c836d476e6304d915f4a511)
- **cookies**: ability to set custom cookie encoders to encode the cookie's value before sent by `context#SetCookie` and `context#SetCookieKV` and cookie decoders to decode the cookie's value when retrieving from `context#GetCookie`. That was the second and final part relative to a community's question at: [issue #1018](https://github.com/kataras/iris/issues/1018). Implemented by [this commit](https://github.com/kataras/iris/commit/f708c6098faec7c4e2232c791380cdff7a26960b)
- **fix**: [issue #1020](https://github.com/kataras/iris/issues/1020) via [this commit](https://github.com/kataras/iris/commit/3d30ccef05703246b716a14dda14d2f28294dbd2), redis database stores the int as float64, don't change that native behavior, just grab it nicely.
## Translations (2)
- [README_PT_BR.md](README_PT_BR.md) for Brazilian Portuguese language via [this PR](https://github.com/kataras/iris/pull/1008) thanks to [@gschri](https://github.com/gschri)
- [README_JPN.md](README_JPN.md) for Japanese language via [this PR](https://github.com/kataras/iris/pull/1015) thanks to [@tkhkokd](https://github.com/tkhkokd).
Thank you both for your contribution. We all looking forward for the HISTORY translations as well!!!
# Mo, 21 May 2018 | v10.6.5
First of all, special thanks to [@haritsfahreza](https://github.com/haritsfahreza) for translating the entire Iris' README page & Changelogs to the Bahasa Indonesia language via PR: [#1000](https://github.com/kataras/iris/pull/1000)!
## New Feature: `Execution Rules`
From the begin of the Iris' journey we used to use the `ctx.Next()` inside handlers in order to call the next handler in the route's registered handlers chain, otherwise the "next handler" would never be executed.
We could always "force-break" that handlers chain using the `ctx.StopExecution()` to indicate that any future `ctx.Next()` calls will do nothing.
These things will never change, they were designed in the lower possible level of the Iris' high-performant and unique router and they're working like a charm:)
We have introduced `Iris MVC Applications` two years later. Iris is the first and the only one Go web framework with a realistic point-view and feature-rich MVC architectural pattern support without sacrifices, always with speed in mind (handlers vs mvc have almost the same speed here!!!).
A bit later we introduced another two unique features, `Hero Handlers and Service/Dynamic Bindings` (see the very bottom of this HISTORY page).
You loved it, you're using it a lot, just take a look at the recent github issues the community raised about MVC and etc.
Two recent discussions/support were about calling `Done` handlers inside MVC applications, you could simply do that by implementing the optional `BaseController` as examples shown, i.e:
```go
func (c *myController) BeginRequest(ctx iris.Context) {}
func (c *myController) EndRequest(ctx iris.Context) {
ctx.Next() // Call of any `Done` handlers.
}
```
But for some reason you found that confused. This is where the new feature comes: **The option to change the default behavior of handlers execution's rules PER PARTY**.
For example, we want to run all handlers(begin, main and done handlers) with the order you register but without the need of the `ctx.Next()` (in that case the only remained way to stop the lifecycle of an http request when next handlers are registered is to use the `ctx.StopExecution()` which, does not allow the next handler(s) to be executed even if `ctx.Next()` called in some place later on, but you're already know this, I hope :)).
```go
package main
import (
"github.com/kataras/iris"
"github.com/kataras/iris/mvc"
)
func main() {
app := iris.New()
app.Get("/", func(ctx iris.Context) { ctx.Redirect("/example") })
m := mvc.New(app.Party("/example"))
// IMPORTANT
// the new feature, all options can be filled with Force:true, they are all play nice together.
m.Router.SetExecutionRules(iris.ExecutionRules{
// Begin: <- from `Use[all]` to `Handle[last]` future route handlers, execute all, execute all even if `ctx.Next()` is missing.
// Main: <- all `Handle` future route handlers, execute all >> >>.
Done: iris.ExecutionOptions{Force: true}, // <- from `Handle[last]` to `Done[all]` future route handlers, execute all >> >>.
})
m.Router.Done(doneHandler)
// m.Router.Done(...)
// ...
//
m.Handle(&exampleController{})
app.Run(iris.Addr(":8080"))
}
func doneHandler(ctx iris.Context) {
ctx.WriteString("\nFrom Done Handler")
}
type exampleController struct{}
func (c *exampleController) Get() string {
return "From Main Handler"
// Note that here we don't binding the `Context`, and we don't call its `Next()`
// function in order to call the `doneHandler`,
// this is done automatically for us because we changed the execution rules with the `SetExecutionRules`.
//
// Therefore, the final output is:
// From Main Handler
// From Done Handler
}
```
Example at: [_examples/mvc/middleware/without-ctx-next](_examples/mvc/middleware/without-ctx-next).
This feature can be applied to any type of application, the example is an MVC Application because many of you asked for this exactly flow the past days.
## Thank you
Thank you for your honest support once again, your posts are the heart of this framework.
Don't forget to [star](https://github.com/kataras/iris/stargazers) the Iris' github repository whenever you can and spread the world about its potentials!
Be part of this,
- complete our User Experience Report: https://goo.gl/forms/lnRbVgA6ICTkPyk02
- join to our Community live chat: https://kataras.rocket.chat/channel/iris
- connect to our [new facebook group](https://www.facebook.com/iris.framework) to get notifications about new job opportunities relatively to Iris!
Sincerely,
[Gerasimos Maropoulos](https://twitter.com/MakisMaropoulos).
# We, 09 May 2018 | v10.6.4
- [fix issue 995](https://github.com/kataras/iris/commit/62457279f41a1f157869a19ef35fb5198694fddb)
- [fix issue 996](https://github.com/kataras/iris/commit/a11bb5619ab6b007dce15da9984a78d88cd38956)
# We, 02 May 2018 | v10.6.3
**Every server should be upgraded to this version**, it contains an important, but easy, fix for the `websocket/Connection#Emit##To`.
- Websocket: fix https://github.com/kataras/iris/issues/991
# Tu, 01 May 2018 | v10.6.2
- Websocket: added OnPong to Connection via PR: https://github.com/kataras/iris/pull/988
- Websocket: `OnError` accepts a `func(error)` now instead of `func(string)`, as requested at: https://github.com/kataras/iris/issues/987
# We, 25 April 2018 | v10.6.1
- Re-implement the [BoltDB](https://github.com/coreos/bbolt) as built'n back-end storage for sessions(`sessiondb`) using the latest features: [/sessions/sessiondb/boltdb/database.go](sessions/sessiondb/boltdb/database.go), example can be found at [/_examples/sessions/database/boltdb/main.go](_examples/sessions/database/boltdb/main.go).
- Fix a minor issue on [Badger sessiondb example](_examples/sessions/database/badger/main.go). Its `sessions.Config { Expires }` field was `2 *time.Second`, it's `45 *time.Minute` now.
- Other minor improvements to the badger sessiondb.
# Su, 22 April 2018 | v10.6.0
- Fix open redirect by @wozz via PR: https://github.com/kataras/iris/pull/972.
- Fix when destroy session can't remove cookie in subdomain by @Chengyumeng via PR: https://github.com/kataras/iris/pull/964.
- Add `OnDestroy(sid string)` on sessions for registering a listener when a session is destroyed with commit: https://github.com/kataras/iris/commit/d17d7fecbe4937476d00af7fda1c138c1ac6f34d.
- Finally, sessions are in full-sync with the registered database now. That required a lot of internal code changed but **zero code change requirements by your side**. We kept only `badger` and `redis` as the back-end built'n supported sessions storages, they are enough. Made with commit: https://github.com/kataras/iris/commit/f2c3a5f0cef62099fd4d77c5ccb14f654ddbfb5c relative to many issues that you've requested it.
# Sa, 24 March 2018 | v10.5.0
### New
Add new client cache (helpers) middlewares for even faster static file servers. Read more [there](https://github.com/kataras/iris/pull/935).
### Breaking Change
Change the `Value<T>Default(<T>, error)` to `Value<T>Default(key, defaultValue) <T>` like `ctx.PostValueIntDefault` or `ctx.Values().GetIntDefault` or `sessions/session#GetIntDefault` or `context#URLParamIntDefault`.
The proposal was made by @jefurry at https://github.com/kataras/iris/issues/937.
#### How to align your existing codebase
Just remove the second return value from these calls.
Nothing too special or hard to change here, think that in our 100+ [_examples](_examples) we had only two of them.
For example: at [_examples/mvc/basic/main.go line 100](_examples/mvc/basic/main.go#L100) the `count,_ := c.Session.GetIntDefault("count", 1)` **becomes now:** `count := c.Session.GetIntDefault("count", 1)`.
> Remember that if you can't upgrade then just don't, we dont have any security fixes in this release, but at some point you will have to upgrade for your own good, we always add new features that you will love to embrace!
# We, 14 March 2018 | v10.4.0
- fix `APIBuilder, Party#StaticWeb` and `APIBuilder, Party#StaticEmbedded` wrong strip prefix inside children parties
- keep the `iris, core/router#StaticEmbeddedHandler` and remove the `core/router/APIBuilder#StaticEmbeddedHandler`, (note the `Handler` suffix) it's global and has nothing to do with the `Party` or the `APIBuilder`
- fix high path cleaning between `{}` (we already escape those contents at the [interpreter](macro/interpreter) level but some symbols are still removed by the higher-level api builder) , i.e `\\` from the string's macro function `regex` contents as reported at [927](https://github.com/kataras/iris/issues/927) by [commit e85b113476eeefffbc7823297cc63cd152ebddfd](https://github.com/kataras/iris/commit/e85b113476eeefffbc7823297cc63cd152ebddfd)
- sync the `golang.org/x/sys/unix` vendor
## The most important
We've made static files served up to 8 times faster using the new tool, <https://github.com/kataras/bindata> which is a fork of your beloved `go-bindata`, some unnecessary things for us were removed there and contains some additions for performance boost.
## Reqs/sec with [shuLhan/go-bindata](https://github.com/shuLhan/go-bindata) and alternatives
![go-bindata](https://github.com/kataras/bindata/raw/master/go-bindata-benchmark.png)
## Reqs/sec with [kataras/bindata](https://github.com/kataras/bindata)
![bindata](https://github.com/kataras/bindata/raw/master/bindata-benchmark.png)
A **new** function `Party#StaticEmbeddedGzip` which has the same input arguments as the `Party#StaticEmbedded` added. The difference is that the **new** `StaticEmbeddedGzip` accepts the `GzipAsset` and `GzipAssetNames` from the `bindata` (go get -u github.com/kataras/bindata/cmd/bindata).
You can still use both `bindata` and `go-bindata` tools in the same folder, the first for embedding the rest of the static files (javascript, css, ...) and the second for embedding the templates!
A full example can be found at: [_examples/file-server/embedding-gziped-files-into-app/main.go](_examples/file-server/embedding-gziped-files-into-app/main.go).
_Happy Coding!_
# Sa, 10 March 2018 | v10.3.0
- The only one API Change is the [Application/Context/Router#RouteExists](https://godoc.org/github.com/kataras/iris/core/router#Router.RouteExists), it accepts the `Context` as its first argument instead of last now.
- Fix cors middleware via https://github.com/iris-contrib/middleware/commit/048e2be034ed172c6754448b8a54a9c55debad46, relative issue: https://github.com/kataras/iris/issues/922 (still pending for a verification).
- Add `Context#NextOr` and `Context#NextOrNotFound`
```go
// NextOr checks if chain has a next handler, if so then it executes it
// otherwise it sets a new chain assigned to this Context based on the given handler(s)
// and executes its first handler.
//
// Returns true if next handler exists and executed, otherwise false.
//
// Note that if no next handler found and handlers are missing then
// it sends a Status Not Found (404) to the client and it stops the execution.
NextOr(handlers ...Handler) bool
// NextOrNotFound checks if chain has a next handler, if so then it executes it
// otherwise it sends a Status Not Found (404) to the client and stops the execution.
//
// Returns true if next handler exists and executed, otherwise false.
NextOrNotFound() bool
```
- Add a new `Party#AllowMethods` which if called before any `Handle, Get, Post...` will clone the routes to that methods as well.
- Fix trailing slash from POST method request redirection as reported at: https://github.com/kataras/iris/issues/921 via https://github.com/kataras/iris/commit/dc589d9135295b4d080a9a91e942aacbfe5d56c5
- Add examples for read using custom decoder per type, read using custom decoder via `iris#UnmarshalerFunc` and to complete it add an example for the `context#ReadXML`, you can find them [here](https://github.com/kataras/iris/tree/master/_examples#how-to-read-from-contextrequest-httprequest)via https://github.com/kataras/iris/commit/78cd8e5f677fe3ff2c863c5bea7d1c161bf4c31e.
- Add one more example for custom router macro functions, relative to https://github.com/kataras/iris/issues/918, you can find it [there](https://github.com/kataras/iris/blob/master/_examples/routing/dynamic-path/main.go#L144-L158), via https://github.com/kataras/iris/commit/a7690c71927cbf3aa876592fab94f04cada91b72
- Add wrappers for `Pongo`'s `AsValue()` and `AsSaveValue()` by @neenar via PR: https://github.com/kataras/iris/pull/913
- Remove unnecessary reflection usage on `context#UnmarshalBody` via https://github.com/kataras/iris/commit/4b9e41458b62035ea4933789c0a132c3ef2a90cc
# Th, 15 February 2018 | v10.2.1
Fix subdomains' `StaticEmbedded` & `StaticWeb` not found errors, as reported by [@speedwheel](https://github.com/speedwheel) via [facebook page's chat](https://facebook.com/iris.framework).
# Th, 08 February 2018 | v10.2.0
A new minor version family because it contains a **BREAKING CHANGE** and a new `Party#Reset` function.
### Party#Done behavior change & new Party#DoneGlobal introduced
As correctly pointed out by @likakuli at https://github.com/kataras/iris/issues/901, the old `Done` registered
handlers globally instead of party's and its children routes, this was not by accident because `Done` was introduced
before the `UseGlobal` idea and it didn't change for the shake of stability. Now it's time to move on, the new `Done` should be called before the routes that they care about those done handlers and the **new** `DoneGlobal` works like the old `Done`; order doesn't matter and it appends those done handlers
to the current registered routes and the future, globally (to all subdomains, parties every route in the Application).
The [routing/writing-a-middleware](_examples/routing/writing-a-middleware) examples are updated, read those to understand what's going on, although if you used iris before and you know the vocabulary we use you don't have to, the `DoneGlobal` and `Done` are clearly separated.
### Party#Reset
A new `Party#Reset()` function introduced in order to be able to clear parent's Party's begin and done handlers that are registered via `Use` and `Done` at a previous state, nothing crazy about this, it just clears the `middleware` and `doneHandlers` of the current Party instance, see `core/router#APIBuilder` for more.
### Update your codebase
Just replace all existing `.Done(` with `.DoneGlobal(` using a rich code editor (like the [VSCode](https://marketplace.visualstudio.com/items?itemName=kataras2006.iris)) which supports `find and replace all` and you're ready to Go:)
# Tu, 06 February 2018 | v10.1.0
New Features:
- Multi-Level subdomain redirect helper, you can find an example [here](https://github.com/kataras/iris/blob/master/_examples/subdomains/redirect/main.go)
- Cache middleware which makes use of the `304` status code, request fires from client to server but server respond with a status code, client is responsible to render the cached, you can find an example [here](https://github.com/kataras/iris/blob/master/_examples/cache/client-side/main.go)
- `websocket/Connection#IsJoined(roomName string)` new method to check if a user is joined to a room. An un-joined connections cannot send messages, this check is optionally.
More:
- update vendor/golang/crypto package to its latest version again, they have a lot of fixes there, as you know we're always following the dependencies for any fixes and meanful updates.
- [don't force-set content type on gzip response writer's WriteString and Writef if already there](https://github.com/kataras/iris/commit/af79aad11932f1a4fcbf7ebe28274b96675d0000)
- [new: add websocket/Connection#IsJoined](https://github.com/kataras/iris/commit/cb9e30948c8f1dd099f5168218d110765989992e)
- [fix #897](https://github.com/kataras/iris/commit/21cb572b638e82711910745cfae3c52d836f01f9)
- [add context#StatusCodeNotSuccessful variable for customize even the rfc2616-sec10](https://github.com/kataras/iris/commit/c56b7a3f04d953a264dfff15dadd2b4407d62a6f)
- [fix example comment on routing/dynamic-path/main.go#L101](https://github.com/kataras/iris/commit/0fbf1d45f7893cb1393759b7362444f3d381d182)
- [new: Cache Middleware `iris.Cache304`](https://github.com/kataras/iris/commit/1722355870174cecbc12f7beff8514b058b3b912)
- [fix comment on csrf example](https://github.com/kataras/iris/commit/a39e3d7d6cf528e51e6c7e32a884a8d9f2fadc0b)
- [un-default the Configuration.RemoteAddrHeaders](https://github.com/kataras/iris/commit/47108dc5a147a8b23de61bef86fe9327f0781396)
- [add vscode extension link and badge](https://github.com/kataras/iris/commit/6f594c0a7c641cc98bd683163fffbf5fa5fc8de6)
- [add an `app.View` example for parsing and writing templates outside of the HTTP (similar to context#View)](_examples/view/write-to)
- [new: Support multi-level subdomains redirect](https://github.com/kataras/iris/commit/12d7df113e611a75088c2a72774dab749d2c7685).
# Tu, 16 January 2018 | v10.0.2
## Security | `iris.AutoTLS`
**Every server should be upgraded to this version**, it contains fixes for the _tls-sni challenge disabled_ some days ago by letsencrypt.org which caused almost every https-enabled golang server to be unable to be functional, therefore support for the _http-01 challenge type_ added. Now the server is testing all available letsencrypt challenges.
Read more at:
- https://letsencrypt.status.io/pages/incident/55957a99e800baa4470002da/5a55777ed9a9c1024c00b241
- https://github.com/golang/crypto/commit/13931e22f9e72ea58bb73048bc752b48c6d4d4ac
# Mo, 15 January 2018 | v10.0.1
Not any serious problems were found to be resolved here but one, the first one which is important for devs that used the [cache](cache) package.
- fix a single one cache handler didn't work across multiple route handlers at the same time https://github.com/kataras/iris/pull/852, as reported at https://github.com/kataras/iris/issues/850
- merge PR https://github.com/kataras/iris/pull/862
- do not allow concurrent access to the `ExecuteWriter -> Load` when `view#Engine##Reload` was true, as requested at https://github.com/kataras/iris/issues/872
- badge for open-source projects powered by Iris, learn how to add that badge to your open-source project at [FAQ.md](FAQ.md) file
- upstream update for `golang/crypto` to apply the fix about the [tls-sni challenge disabled](https://letsencrypt.status.io/pages/incident/55957a99e800baa4470002da/5a55777ed9a9c1024c00b241) https://github.com/golang/crypto/commit/13931e22f9e72ea58bb73048bc752b48c6d4d4ac (**relative to iris.AutoTLS**)
## New Backers
1. https://opencollective.com/cetin-basoz
## New Translations
1. The Chinese README_ZH.md and HISTORY_ZH.md was translated by @Zeno-Code via https://github.com/kataras/iris/pull/858
2. New Russian README_RU.md translations by @merrydii via https://github.com/kataras/iris/pull/857
3. New Greek README_GR.md and HISTORY_GR.md translations via https://github.com/kataras/iris/commit/8c4e17c2a5433c36c148a51a945c4dc35fbe502a#diff-74b06c740d860f847e7b577ad58ddde0 and https://github.com/kataras/iris/commit/bb5a81c540b34eaf5c6c8e993f644a0e66a78fb8
## New Examples
1. [MVC - Register Middleware](_examples/mvc/middleware)
## New Articles
1. [A Todo MVC Application using Iris and Vue.js](https://hackernoon.com/a-todo-mvc-application-using-iris-and-vue-js-5019ff870064)
2. [A Hasura starter project with a ready to deploy Golang hello-world web app with IRIS](bit.ly/2lmKaAZ)
# Mo, 01 January 2018 | v10.0.0
We must thanks [Mrs. Diana](https://www.instagram.com/merry.dii/) for our awesome new [logo](https://iris-go.com/images/icon.svg)!
You can [contact](mailto:Kovalenkodiana8@gmail.com) her for any design-related enquiries or explore and send a direct message via [instagram](https://www.instagram.com/merry.dii/).
<p align="center">
<img width="145px" src="https://iris-go.com/images/icon.svg?v=a" />
</p>
At this version we have many internal improvements but just two major changes and one big feature, called **hero**.
> The new version adds 75 plus new commits, the PR is located [here](https://github.com/kataras/iris/pull/849) read the internal changes if you are developing a web framework based on Iris. Why 9 was skipped? Because.
## Hero
The new package [hero](hero) contains features for binding any object or function that `handlers` may use, these are called dependencies. Hero funcs can also return any type of values, these values will be dispatched to the client.
> You may saw binding before but you didn't have code editor's support, with Iris you get truly safe binding thanks to the new `hero` package. It's also fast, near to raw handlers performance because Iris calculates everything before server ran!
Below you will see some screenshots we prepared for you in order to be easier to understand:
### 1. Path Parameters - Built'n Dependencies
![](https://github.com/kataras/explore/raw/master/iris/hero/hero-1-monokai.png)
### 2. Services - Static Dependencies
![](https://github.com/kataras/explore/raw/master/iris/hero/hero-2-monokai.png)
### 3. Per-Request - Dynamic Dependencies
![](https://github.com/kataras/explore/raw/master/iris/hero/hero-3-monokai.png)
`hero funcs` are very easy to understand and when you start using them **you never go back**.
Examples:
- [Basic](_examples/hero/basic/main.go)
- [Overview](_examples/hero/overview)
## MVC
You have to understand the `hero` package in order to use the `mvc`, because `mvc` uses the `hero` internally for the controller's methods you use as routes, the same rules applied to those controller's methods of yours as well.
With this version you can register **any controller's methods as routes manually**, you can **get a route based on a method name and change its `Name` (useful for reverse routing inside templates)**, you can use any **dependencies** registered from `hero.Register` or `mvc.New(iris.Party).Register` per mvc application or per-controller, **you can still use `BeginRequest` and `EndRequest`**, you can catch **`BeforeActivation(b mvc.BeforeActivation)` to add dependencies per controller and `AfterActivation(a mvc.AfterActivation)` to make any post-validations**, **singleton controllers when no dynamic dependencies are used**, **Websocket controller, as simple as a `websocket.Connection` dependency** and more...
Examples:
**If you used MVC before then read very carefully: MVC CONTAINS SOME BREAKING CHANGES BUT YOU CAN DO A LOT MORE AND EVEN FASTER THAN BEFORE**
**PLEASE READ THE EXAMPLES CAREFULLY, WE'VE MADE THEM FOR YOU**
Old examples are here as well. Compare the two different versions of each example to understand what you win if you upgrade now.
| NEW | OLD |
| -----------|-------------|
| [Hello world](_examples/mvc/hello-world/main.go) | [OLD Hello world](https://github.com/kataras/iris/blob/v8/_examples/mvc/hello-world/main.go) |
| [Session Controller](_examples/mvc/session-controller/main.go) | [OLD Session Controller](https://github.com/kataras/iris/blob/v8/_examples/mvc/session-controller/main.go) |
| [Overview - Plus Repository and Service layers](_examples/mvc/overview) | [OLD Overview - Plus Repository and Service layers](https://github.com/kataras/iris/tree/v8/_examples/mvc/overview) |
| [Login showcase - Plus Repository and Service layers](_examples/mvc/login) | [OLD Login showcase - Plus Repository and Service layers](https://github.com/kataras/iris/tree/v8/_examples/mvc/login) |
| [Singleton](_examples/mvc/singleton) | **NEW** |
| [Websocket Controller](_examples/mvc/websocket) | **NEW** |
| [Vue.js Todo MVC](_examples/tutorial/vuejs-todo-mvc) | **NEW** |
## context#PostMaxMemory
Remove the old static variable `context.DefaultMaxMemory` and replace it with the configuration `WithPostMaxMemory`.
```go
// WithPostMaxMemory sets the maximum post data size
// that a client can send to the server, this differs
// from the overral request body size which can be modified
// by the `context#SetMaxRequestBodySize` or `iris#LimitRequestBodySize`.
//
// Defaults to 32MB or 32 << 20 if you prefer.
func WithPostMaxMemory(limit int64) Configurator
```
If you used that old static field you will have to change that single line.
Usage:
```go
import "github.com/kataras/iris"
func main() {
app := iris.New()
// [...]
app.Run(iris.Addr(":8080"), iris.WithPostMaxMemory(10 << 20))
}
```
## context#UploadFormFiles
New method to upload multiple files, should be used for common upload actions, it's just a helper function.
```go
// UploadFormFiles uploads any received file(s) from the client
// to the system physical location "destDirectory".
//
// The second optional argument "before" gives caller the chance to
// modify the *miltipart.FileHeader before saving to the disk,
// it can be used to change a file's name based on the current request,
// all FileHeader's options can be changed. You can ignore it if
// you don't need to use this capability before saving a file to the disk.
//
// Note that it doesn't check if request body streamed.
//
// Returns the copied length as int64 and
// a not nil error if at least one new file
// can't be created due to the operating system's permissions or
// http.ErrMissingFile if no file received.
//
// If you want to receive & accept files and manage them manually you can use the `context#FormFile`
// instead and create a copy function that suits your needs, the below is for generic usage.
//
// The default form's memory maximum size is 32MB, it can be changed by the
// `iris#WithPostMaxMemory` configurator at main configuration passed on `app.Run`'s second argument.
//
// See `FormFile` to a more controlled to receive a file.
func (ctx *context) UploadFormFiles(
destDirectory string,
before ...func(string, string),
) (int64, error)
```
Example can be found [here](_examples/http_request/upload-files/main.go).
## context#View
Just a minor addition, add a second optional variadic argument to the `context#View` method to accept a single value for template binding.
When you just want one value and not key-value pairs, you used to use an empty string on the `ViewData`, which is fine, especially if you preload these from a previous handler/middleware in the request handlers chain.
```go
func(ctx iris.Context) {
ctx.ViewData("", myItem{Name: "iris" })
ctx.View("item.html")
}
```
Same as:
```go
func(ctx iris.Context) {
ctx.View("item.html", myItem{Name: "iris" })
}
```
```html
Item's name: {{.Name}}
```
## context#YAML
Add a new `context#YAML` function, it renders a yaml from a structured value.
```go
// YAML marshals the "v" using the yaml marshaler and renders its result to the client.
func YAML(v interface{}) (int, error)
```
## Session#GetString
`sessions/session#GetString` can now return a filled value even if the stored value is a type of integer, just like the memstore, the context's temp store, the context's path parameters and the context's url parameters.
Read about the new release at: https://dev.to/kataras/iris-version-11-2-released-22bc

View File

@ -1,343 +0,0 @@
# Ιστορικό <a href="HISTORY.md"> <img width="20px" src="https://iris-go.com/images/flag-unitedkingdom.svg?v=10" /></a> <a href="HISTORY_ZH.md"> <img width="20px" src="https://iris-go.com/images/flag-china.svg?v=10" /></a> <a href="HISTORY_ID.md"> <img width="20px" src="https://iris-go.com/images/flag-indonesia.svg?v=10" /></a>
### Ψάχνετε για δωρεάν υποστήριξη σε πραγματικό χρόνο;
https://github.com/kataras/iris/issues
https://chat.iris-go.com
### Ψάχνετε για προηγούμενες εκδόσεις;
https://github.com/kataras/iris/releases
### Πρέπει να αναβαθμίσω το Iris μου;
Οι προγραμματιστές δεν αναγκάζονται να αναβαθμίσουν αν δεν το χρειάζονται πραγματικά. Αναβαθμίστε όποτε αισθάνεστε έτοιμοι.
> Το Iris εκμεταλλεύεται τη λεγόμενη λειτουργία [vendor directory](https://docs.google.com/document/d/1Bz5-UB7g2uPBdOx-rw5t9MxJwkfpx90cqG9AFL0JAYo). Παίρνετε πλήρως αναπαραγωγίσιμα builds, καθώς αυτή η μέθοδος προστατεύει από τις upstream μετονομασίες και διαγραφές.
**Πώς να αναβαθμίσετε**: Ανοίξτε την γραμμή εντολών σας και εκτελέστε αυτήν την εντολή: `go get -u github.com/kataras/iris` ή αφήστε το αυτόματο updater να το κάνει αυτό για σας.
# Fr, 11 January 2019 | v11.1.1
Πατήστε [εδώ](https://github.com/kataras/iris/blob/master/HISTORY.md#fr-11-january-2019--v1111) για να διαβάσετε στα αγγλικά.
# Su, 18 November 2018 | v11.1.0
Πατήστε [εδώ](https://github.com/kataras/iris/blob/master/HISTORY.md#su-18-november-2018--v1110) για να διαβάσετε στα αγγλικά για το νέο "versioning" feature.
# Fr, 09 November 2018 | v11.0.4
Πατήστε [εδώ](https://github.com/kataras/iris/blob/master/HISTORY.md#fr-09-november-2018--v1104) για να διαβάσετε στα αγγλικά τις αλλαγές που φέρνει το τελευταίο patch για την έκδοση 11.
# Tu, 30 October 2018 | v11.0.2
Πατήστε [εδώ](https://github.com/kataras/iris/blob/master/HISTORY.md#tu-30-october-2018--v1102) για να διαβάσετε στα αγγλικά μια σημαντική διόρθωση για τα x32 machines που φέρνει το τελευταίο patch για την έκδοση 11.
# Su, 28 October 2018 | v11.0.1
Πατήστε [εδώ](https://github.com/kataras/iris/blob/master/HISTORY.md#su-28-october-2018--v1101) για να διαβάσετε στα αγγλικά τις αλλαγές και το νέο feature που φέρνει το τελευταίο patch για την έκδοση 11.
# Su, 21 October 2018 | v11.0.0
Πατήστε [εδώ](https://github.com/kataras/iris/blob/master/HISTORY.md#su-21-october-2018--v1100) για να διαβάσετε στα αγγλικά τις αλλαγές και τα νέα features που φέρνει νεότερη έκδοση του Iris, version 11.
# Sat, 11 August 2018 | v10.7.0
Είμαι στην, πραγματικά, ευχάριστη θέση να σας ανακοινώσω το πρώτο στάδιο της σταθερής κυκλοφορίας της έκδοσης **10.7** του Iris Web Framework.
Η έκδοση 10.7.0 είναι μέρος των [επίσημων διανομών μας](https://github.com/kataras/iris/releases).
Αυτή η έκδοση δεν περιέχει αλλαγές που μπορούν να αλλάξουν ριζικά τα υπάρχοντα προγράμματα που χτίστηκαν με βάση παλιότερες εκδόσεις του Iris. Οι προγραμματιστές μπορούν να αναβαθμίσουν με απόλυτη ασφάλεια.
Διαβάστε παρακάτω τις αλλαγές και τις βελτιώσεις στον εσωτερικό άβυσσο του Iris. Επιπλέον έχουμε ακόμα περισσότερα παραδείγματα για αρχάριους στην κοινότητα μας.
## Νέα παραδείγματα
- [Iris + WebAssemply = 💓](_examples/webassembly/basic/main.go) **προυποθέτει την έκδοση go11.beta και αφεξ**
- [Server-Sent Events](_examples/http_responsewriter/sse/main.go)
- [Struct Validation on context.ReadJSON](_examples/http_request/read-json-struct-validation/main.go)
- [Extract referrer from "referer" header or URL query parameter](_examples/http_request/extract-referer/main.go)
- [Hero Sessions](_examples/hero/sessions)
- [Yet another dependency injection example with hero](_examples/hero/smart-contract/main.go)
- [Writing an API for the Apache Kafka](_examples/tutorial/api-for-apache-kafka)
> Επίσης, όλα τα "sessions" παραδείγματα έχουν προσαρμοστεί ώστε να περιέχουν την επιλογή `AllowReclaim: true`
## kataras/iris/websocket
- Αλλαγή του "connection list" από απλή λίστα σε `sync.Map`, έγινε με: [αυτό](https://github.com/kataras/iris/commit/5f16704f45bedd767527eadf411cf9bc0f8edaee) και [αυτό το commit](https://github.com/kataras/iris/commit/16b30e8eed1406c61abc01282120870bd9fa31d8)
- Προσθήκη του `iris-ws.js` αρχείου στο διάσημο CDN https://cdnjs.com με [αυτό το PR](https://github.com/kataras/iris/pull/1053) από τον [Dibyendu Das](https://github.com/dibyendu)
## kataras/iris/core/router
- Προσθήκη κάποιων `json` field tags και νέα functions όπως τα `ChangeMethod`, `SetStatusOffline` και `RestoreStatus` στη `Route` δομή, προσοχή, για να υσχίσουν αυτών των ειδών οι αλλαγές προυποθέτουν από εσας το κάλεσμα του `Router/Application.RefreshRouter()`. (δεν συνιστάται απόλυτα αλλά είναι χρήσιμο για ειδικά κατασκευασμένες ιστοσελίδες τρίτων που μπορεί να υπάρχουν εκει έξω για διαχείριση ενός Web Server που χτίστηκε με Iris)
- Προσθήκη του `GetRoutesReadOnly` function στην `APIBuilder` δομή
## kataras/iris/context
- Προσθήκη των `GetReferrer`, `GetContentTypeRequested` και `URLParamInt32Default` functions
- Εισαγωγή των `Trace`, `Tmpl` και `MainHandlerName` functions στη διεπαφή(interface) `RouteReadOnly`
- Προσθήκη του `OnConnectionClose` function, χρησημοποείται για να καλεί κάποιο function όταν η "underline tcp connection" διακοπεί, εξαιρετικά χρήσιμο για SSE ή και άλλες παρόμοιες υλοποιήσεις μέσα σε έναν Iris Handler -- και του `OnClose` function το οποίο είναι σαν να καλείτε τα `OnConnectionClose(myFunc)` και `defer myFunc()` στον ίδιο Iris Handler [*](https://github.com/kataras/iris/commit/6898c2f755a0e22aa42e3b1799e29c857777a6f9)
Αυτή η έκδοση περιέχει επίσης κάποιες δευτερεύουσες γραμματικής και τυπογραφικού λάθους διορθώσεις και πιό ευανάγνωστα σχόλια για το [godoc](https://godoc.org/github.com/kataras/iris).
## Βιομηχανία
Βρίσκομαι στην ευχάριστη αυτή θέση να σας ανακοινώσω ότι το Iris έχει επιλεγεί ως το κύριο αναπτυξιακό kit(main development kit) για οκτώ μεσαίου ως μεγάλου μεγέθους εταιρείες και μια νέα πολύ ελπιδοφόρα startup με βάση την Ινδία.
Θέλω να σας ευχαριστήσω όλους, **καθέ μία και έναν ξεχωριστά**, για την αδιάκοπη αυτή υποστήριξη και την εμπιστοσύνη που μου δείξατε όλα αυτά τα χρόνια, ειδικά φέτος, παρά τις φήμες και τις διάφορες δυσφήσεις που είχαμε υποστεί αδίκως από τον ανελέητο ανταγωνισμό.
# Tu, 05 June 2018 | v10.6.6
This history entry is not translated yet to the Greek language yet, please refer to the english version of the [HISTORY entry](https://github.com/kataras/iris/blob/master/HISTORY.md#tu-05-june-2018--v1066) instead.
# Mo, 21 May 2018 | v10.6.5
This history entry is not translated yet to the Greek language yet, please refer to the english version of the [HISTORY entry](https://github.com/kataras/iris/blob/master/HISTORY.md#mo-21-may-2018--v1065) instead.
# We, 09 May 2018 | v10.6.4
- [διόρθωση του bug #995](https://github.com/kataras/iris/commit/62457279f41a1f157869a19ef35fb5198694fddb)
- [διόρθωση του bug #996](https://github.com/kataras/iris/commit/a11bb5619ab6b007dce15da9984a78d88cd38956)
# We, 02 May 2018 | v10.6.3
This history entry is not translated yet to the Greek language yet, please refer to the english version of the [HISTORY entry](https://github.com/kataras/iris/blob/master/HISTORY.md#we-02-may-2018--v1063) instead.
# Tu, 01 May 2018 | v10.6.2
This history entry is not translated yet to the Greek language yet, please refer to the english version of the [HISTORY entry](https://github.com/kataras/iris/blob/master/HISTORY.md#tu-01-may-2018--v1062) instead.
# We, 25 April 2018 | v10.6.1
This history entry is not translated yet to the Greek language yet, please refer to the english version of the [HISTORY entry](https://github.com/kataras/iris/blob/master/HISTORY.md#we-25-april-2018--v1061) instead.
# Su, 22 April 2018 | v10.6.0
This history entry is not translated yet to the Greek language yet, please refer to the english version of the [HISTORY entry](https://github.com/kataras/iris/blob/master/HISTORY.md#su-22-april-2018--v1060) instead.
# Sa, 24 March 2018 | v10.5.0
This history entry is not translated yet to the Greek language yet, please refer to the english version of the [HISTORY entry](https://github.com/kataras/iris/blob/master/HISTORY.md#sa-24-march-2018--v1050) instead.
# We, 14 March 2018 | v10.4.0
This history entry is not translated yet to the Greek language yet, please refer to the english version of the [HISTORY entry](https://github.com/kataras/iris/blob/master/HISTORY.md#we-14-march-2018--v1040) instead.
# Sa, 10 March 2018 | v10.3.0
This history entry is not translated yet to the Greek language yet, please refer to the english version of the [HISTORY entry](https://github.com/kataras/iris/blob/master/HISTORY.md#sa-10-march-2018--v1030) instead.
# Th, 15 February 2018 | v10.2.1
Διόρθωση το οποίο αφορά 404 not found errors στα αρχεία που σερβίρονται από τα `StaticEmbedded` και `StaticWeb` των υποτομεών(subdomains), όπως αναφέρθηκε πριν λίγο από τον [@speedwheel](https://github.com/speedwheel) μέσω [της σελίδας μας στο facebook](https://facebook.com/iris.framework).
This history entry is not yet translated to Greek. Please read [the english version instead](https://github.com/kataras/iris/blob/master/HISTORY.md#th-15-february-2018--v1021).
# Th, 08 February 2018 | v10.2.0
This history entry is not yet translated to Greek. Please read [the english version instead](https://github.com/kataras/iris/blob/master/HISTORY.md#th-08-february-2018--v1020).
# Tu, 06 February 2018 | v10.1.0
This history entry is not yet translated to Greek. Please read [the english version instead](https://github.com/kataras/iris/blob/master/HISTORY.md#tu-06-february-2018--v1010).
# Tu, 16 January 2018 | v10.0.2
## Ασφάλεια | `iris.AutoTLS`
**Όλοι οι servers πρέπει να αναβαθμιστούν σε αυτήν την έκδοση**, περιέχει διορθώσεις για το _tls-sni challenge_ το οποίο απενεργοποιήθηκε μερικές μέρες πριν από το letsencrypt.org το οποίο προκάλεσε σχεδόν όλα τα golang https-ενεργποιημένα servers να να μην είναι σε θέση να λειτουργήσουν, έτσι υποστήριξη για το _http-01 challenge_ προστέθηκε σαν αναπλήρωση. Πλέον ο διακομιστής δοκιμάζει όλες τις διαθέσιμες προκλήσεις(challenges) letsencrypt.
Διαβάστε περισσότερα:
- https://letsencrypt.status.io/pages/incident/55957a99e800baa4470002da/5a55777ed9a9c1024c00b241
- https://github.com/golang/crypto/commit/13931e22f9e72ea58bb73048bc752b48c6d4d4ac
# Mo, 15 January 2018 | v10.0.1
- διόρθωση του cache handler που δεν δούλευε όπως έπρεπε όταν γινόταν εγγραφή σε πάνω από ένα handler, παλιότερα ήταν ένα cache handler προς ένα route handler, τώρα το ίδιο handler μπορεί να καταχωρηθεί σε όσα route handlers θέλετε https://github.com/kataras/iris/pull/852, όπως είχε αναφερθεί στο https://github.com/kataras/iris/issues/850
- συγχώνευση PR https://github.com/kataras/iris/pull/862
- απαγόρευση της ταυτόχρονης προσπέλασης του `ExecuteWriter -> Load` όταν το `view#Engine##Reload` είναι true, όπως είχε ζητηθεί στο https://github.com/kataras/iris/issues/872
- αναβάθμιση του ενσωματωμένου πακέτου `golang/crypto` για να εφαρμοστεί η επιδιόρθωση για το [tls-sni challenge disabled](https://letsencrypt.status.io/pages/incident/55957a99e800baa4470002da/5a55777ed9a9c1024c00b241) https://github.com/golang/crypto/commit/13931e22f9e72ea58bb73048bc752b48c6d4d4ac (**σχετικό με το iris.AutoTLS**)
## Νέοι Υποστηρικτές
1. https://opencollective.com/cetin-basoz
## Νέες Μεταφράσεις
1. Aναβαθμίσεις για την Κινέζικη μετάφραση README_ZH.md (νέο) και HISTORY_ZH.md από @Zeno-Code μέσω του https://github.com/kataras/iris/pull/858
2. Το Ρώσικο README_RU.md μεταφράστηκε από την @merrydii μέσω του https://github.com/kataras/iris/pull/857
3. Τα Ελληνικά README_GR.md και HISTORY_GR.md μεταφράστηκαν μέσω των https://github.com/kataras/iris/commit/8c4e17c2a5433c36c148a51a945c4dc35fbe502a#diff-74b06c740d860f847e7b577ad58ddde0 και https://github.com/kataras/iris/commit/bb5a81c540b34eaf5c6c8e993f644a0e66a78fb8
## Νέα Παραδείγματα
1. [MVC - Register Middleware](_examples/mvc/middleware)
## Νέα Άρθρα
1. [A Todo MVC Application using Iris and Vue.js](https://hackernoon.com/a-todo-mvc-application-using-iris-and-vue-js-5019ff870064)
2. [A Hasura starter project with a ready to deploy Golang hello-world web app with IRIS](bit.ly/2lmKaAZ)
# Mo, 01 January 2018 | v10.0.0
Πρέπει να ευχαριστήσουμε την [Κυρία Diana](https://www.instagram.com/merry.dii/) για το νέο μας [λογότυπο](https://iris-go.com/images/icon.svg)!
Μπορείτε να [επικοινωνήσετε](mailto:Kovalenkodiana8@gmail.com) μαζί της για οποιεσδήποτε σχετικές με το σχεδιασμό εργασίες ή να της στείλειτε ένα άμεσο μήνυμα μέσω [instagram](https://www.instagram.com/merry.dii/).
<p align="center">
<img width="145px" src="https://iris-go.com/images/icon.svg?v=a" />
</p>
Σε αυτή την έκδοση έχουμε πολλές εσωτερικές βελτιώσεις αλλά μόνο δύο μεγάλες αλλαγές και ένα μεγάλο χαρακτηριστικό, που ονομάζεται **hero**.
> Η νέα έκδοση προσθέτει 75 καινούρια commits, το PR βρίσκεται [εδώ](https://github.com/kataras/iris/pull/849). Παρακαλώ διαβάστε τις εσωτερικές αλλαγές αν σχεδιάζετε ένα web framework που βασίζεται στο Iris. Γιατί η έκδοση 9 παραλείφθηκε; Έτσι.
## Hero
Το νέο πακέτο [hero](hero) περιέχει χαρακτηριστικά για σύνδεση(binding) οποιουδήποτε αντικειμένου ή function το οποίο τα `handlers` μπορεί να χρησημοποιούν, αυτά λεγόνται εξαρτήσεις(dependencies). Τα Hero funcs μπορούν επίσης να επιστρέψουν οποιαδήποτε τιμή, οποιουδήποτε τύπου, αυτές οι τιμές αποστέλλονται στον πελάτη(client).
> Μπορεί να είχατε ξαναδει "εξαρτήσεις" και "δέσιμο" πριν αλλά ποτέ με υποστήριξη από τον επεξεργαστή κώδικα (code editor), με το Iris πέρνεις πραγματικά ασφαλή "δεσίματα"(bindings) χάρη στο νέο `hero` πακέτο. Αυτή η όλη εκτέλεση(implementation) είναι επίσης η ποιο γρήγορη που έχει επιτευχθεί εως τώρα, η επίδοση είναι πολύ κοντά στα απλά "handlers" και αυτό γιατί το Iris υπολογίζει τα πάντα πριν καν ο server τρέξει!
Παρακάτω θα δείτε μερικά στιγμιότυπα που ετοιμάσαμε για εσάς, ώστε να γίνουν πιο κατανοητά τα παραπάνω:
### 1. Παράμετροι διαδρομής - Ενσωματωμένες Εξαρτήσεις (Built'n Dependencies)
![](https://github.com/kataras/explore/raw/master/iris/hero/hero-1-monokai.png)
### 2. Υπηρεσίες - Στατικές Eξαρτήσεις (Static Dependencies)
![](https://github.com/kataras/explore/raw/master/iris/hero/hero-2-monokai.png)
### 3. Ανά Αίτηση - Δυναμικές Eξαρτήσεις (Dynamic Dependencies)
![](https://github.com/kataras/explore/raw/master/iris/hero/hero-3-monokai.png)
Είναι πραγματικά πολύ εύκολο να καταλάβεις πως δουλεύουν τα `hero funcs` και όταν αρχίσεις να τα χρησιμοποιείς **δεν γυρίζεις ποτέ πίσω**.
Παραδείγματα:
- [Βασικό](_examples/hero/basic/main.go)
- [Επισκόπηση](_examples/hero/overview)
## MVC
Πρέπει να καταλάβεις πως δουλεύει το `hero` πακετό ώστε να να δουλέψεις με το `mvc`, γιατί το `mvc` πακέτο βασίζετε στο `hero` για τις μεθόδους του controller σου, οι ίδιοι κανόνες εφαρμόζονται και εκεί.
Παραδείγματα:
**Αν χρησημοποιούσατε το MVC πριν, διαβάστε προσεχτικά: Το MVC ΠΕΡΙΕΧΕΙ ΟΡΙΣΜΕΝΕΣ ΑΛΛΑΓΕΣ, ΜΠΟΡΕΙΤΕ ΝΑ ΚΑΝΕΤΕ ΠΕΡΙΣΣΟΤΕΡΑ ΑΠΟ'ΤΙ ΠΡΙΝ**
**ΠΑΡΑΚΑΛΩ ΔΙΑΒΑΣΤΕ ΤΑ ΠΑΡΑΔΕΙΓΜΑΤΑ ΠΡΟΣΕΧΤΙΚΑ, ΓΙΑ ΕΣΑΣ ΦΤΙΑΧΤΗΚΑΝ**
Τα παλιά παραδείγματα είναι επίσης εδώ ώστε να μπορείτε να τα συγκρίνετε με τα καινούρια.
| ΤΩΡΑ | ΠΡΙΝ |
| -----------|-------------|
| [Hello world](_examples/mvc/hello-world/main.go) | [ΠΑΛΙΟ Hello world](https://github.com/kataras/iris/blob/v8/_examples/mvc/hello-world/main.go) |
| [Session Controller](_examples/mvc/session-controller/main.go) | [ΠΑΛΙΟ Session Controller](https://github.com/kataras/iris/blob/v8/_examples/mvc/session-controller/main.go) |
| [Overview - Plus Repository and Service layers](_examples/mvc/overview) | [ΠΑΛΙΟ Overview - Plus Repository and Service layers](https://github.com/kataras/iris/tree/v8/_examples/mvc/overview) |
| [Login showcase - Plus Repository and Service layers](_examples/mvc/login) | [ΠΑΛΙΟ Login showcase - Plus Repository and Service layers](https://github.com/kataras/iris/tree/v8/_examples/mvc/login) |
| [Singleton](_examples/mvc/singleton) | **NEO** |
| [Websocket Controller](_examples/mvc/websocket) | **NEO** |
| [Vue.js Todo MVC](_examples/tutorial/vuejs-todo-mvc) | **NEO** |
## context#PostMaxMemory
Αφαίρεση της παλιάς στατικής μεταβλητής `context.DefaultMaxMemory` και αντικατάσταση με ρύθμιση στο configuration `WithPostMaxMemory`.
```go
// WithPostMaxMemory sets the maximum post data size
// that a client can send to the server, this differs
// from the overral request body size which can be modified
// by the `context#SetMaxRequestBodySize` or `iris#LimitRequestBodySize`.
//
// Defaults to 32MB or 32 << 20 if you prefer.
func WithPostMaxMemory(limit int64) Configurator
```
Αν χρησημοποιούσατε την παλιά στατική μεταβλητή θα χρειαστεί να κάνετε μια αλλαγή σε εκείνη τη γραμμή του κώδικα.
```go
import "github.com/kataras/iris"
func main() {
app := iris.New()
// [...]
app.Run(iris.Addr(":8080"), iris.WithPostMaxMemory(10 << 20))
}
```
## context#UploadFormFiles
Νέα μέθοδος για ανέβασμα πολλαπλών αρχείων από τον client, πρέπει να χρησημοποιείται για απλές και συνηθισμένες καταστάσεις, ένα helper είναι μόνο.
```go
// UploadFormFiles uploads any received file(s) from the client
// to the system physical location "destDirectory".
//
// The second optional argument "before" gives caller the chance to
// modify the *miltipart.FileHeader before saving to the disk,
// it can be used to change a file's name based on the current request,
// all FileHeader's options can be changed. You can ignore it if
// you don't need to use this capability before saving a file to the disk.
//
// Note that it doesn't check if request body streamed.
//
// Returns the copied length as int64 and
// a not nil error if at least one new file
// can't be created due to the operating system's permissions or
// http.ErrMissingFile if no file received.
//
// If you want to receive & accept files and manage them manually you can use the `context#FormFile`
// instead and create a copy function that suits your needs, the below is for generic usage.
//
// The default form's memory maximum size is 32MB, it can be changed by the
// `iris#WithPostMaxMemory` configurator at main configuration passed on `app.Run`'s second argument.
//
// See `FormFile` to a more controlled to receive a file.
func (ctx *context) UploadFormFiles(
destDirectory string,
before ...func(string, string),
) (int64, error)
```
Το παράδειγμα μπορεί να βρεθεί [εδώ](_examples/http_request/upload-files/main.go).
## context#View
Απλά μια μικρή προσθήκη μια δεύτερης προαιρετικής variadic παράμετρου στη `context#View` μέθοδο για να δέχεται μια μονή τιμή για template binding.
Όταν απλά θέλετε να εμφάνισετε ένα struct value και όχι ζεύγη από κλειδί-τιμή, παλιότερα για να το κάνετε αυτό έπρεπε να δηλώσετε κενό string στη 1η παράμετρο στη `context#ViewData` μέθοδο, το οποίο είναι μια χαρά ειδικά αν δηλώνατε αυτά τα δεδομένα σε προηγούμενο handler της αλυσίδας.
```go
func(ctx iris.Context) {
ctx.ViewData("", myItem{Name: "iris" })
ctx.View("item.html")
}
```
Το ίδιο όπως:
```go
func(ctx iris.Context) {
ctx.View("item.html", myItem{Name: "iris" })
}
```
```html
Item's name: {{.Name}}
```
## context#YAML
Προσθήκη νέας μεθόδου, `context#YAML`, εμφανίζει δομημένο yaml κείμενο από struct value.
```go
// YAML marshals the "v" using the yaml marshaler and renders its result to the client.
func YAML(v interface{}) (int, error)
```
## Session#GetString
Η μέθοδος `sessions/session#GetString` μπορεί πλέον να επιστρέψει τιμή ακόμα και απο τιμή που αποθηκεύτηκαι σαν αριθμός (integer), όπως ακριβώς κάνουν ήδη τα: memstore, η προσωρινή μνήμη του context, οι δυναμικές μεταβλητές του path routing και οι παράμετροι του url query.

View File

@ -1,424 +0,0 @@
# Riwayat/Changelog <a href="HISTORY.md"> <img width="20px" src="https://iris-go.com/images/flag-unitedkingdom.svg?v=10" /></a> <a href="HISTORY_ZH.md"> <img width="20px" src="https://iris-go.com/images/flag-china.svg?v=10" /></a> <a href="HISTORY_GR.md"> <img width="20px" src="https://iris-go.com/images/flag-greece.svg?v=10" /></a>
### Butuh bantuan gratis secara langsung?
https://github.com/kataras/iris/issues
https://chat.iris-go.com
### Mencari versi sebelumnya?
https://github.com/kataras/iris/releases
### Apakah saya harus melakukan upgrade terhadap Iris saya?
Developers tidak diwajibkan untuk melakukan upgrade apabila mereka tidak membutuhkannya. Anda bisa melakukan upgrade ketika anda sudah siap.
> Iris menggunakan fitur [vendor directory](https://docs.google.com/document/d/1Bz5-UB7g2uPBdOx-rw5t9MxJwkfpx90cqG9AFL0JAYo). Anda mendapatkan build yang benar - benar dapat direproduksi, karena metode ini menjaga terhadap penggantian nama dan penghapusan di upstream.
**Cara Upgrade**: Bukan command-line anda dan eksekuis perintah ini: `go get -u github.com/kataras/iris` atau biarkan updater otomatis melakukannya untuk anda.
# Fr, 11 January 2019 | v11.1.1
This history entry is not translated yet to the Indonesian language yet, please refer to the english version of the [HISTORY entry](https://github.com/kataras/iris/blob/master/HISTORY.md#fr-11-january-2019--v1111) instead.
# Su, 18 November 2018 | v11.1.0
This history entry is not translated yet to the Indonesian language yet, please refer to the english version of the [HISTORY entry](https://github.com/kataras/iris/blob/master/HISTORY.md#su-18-november-2018--v1110) instead.
# Fr, 09 November 2018 | v11.0.4
This history entry is not translated yet to the Indonesian language yet, please refer to the english version of the [HISTORY entry](https://github.com/kataras/iris/blob/master/HISTORY.md#fr-09-november-2018--v1104) instead.
# Tu, 30 October 2018 | v11.0.2
This history entry is not translated yet to the Indonesian language yet, please refer to the english version of the [HISTORY entry](https://github.com/kataras/iris/blob/master/HISTORY.md#tu-30-october-2018--v1102) instead.
# Su, 28 October 2018 | v11.0.1
This history entry is not translated yet to the Indonesian language yet, please refer to the english version of the [HISTORY entry](https://github.com/kataras/iris/blob/master/HISTORY.md#su-28-october-2018--v1101) instead.
# Su, 21 October 2018 | v11.0.0
This history entry is not translated yet to the Indonesian language yet, please refer to the english version of the [HISTORY entry](https://github.com/kataras/iris/blob/master/HISTORY.md#su-21-october-2018--v1100) instead.
# Sat, 11 August 2018 | v10.7.0
This history entry is not translated yet to the Indonesian language yet, please refer to the english version of the [HISTORY entry](https://github.com/kataras/iris/blob/master/HISTORY.md#sat-11-august-2018--v1070) instead.
# Tu, 05 June 2018 | v10.6.6
This history entry is not translated yet to the Indonesian language yet, please refer to the english version of the [HISTORY entry](https://github.com/kataras/iris/blob/master/HISTORY.md#tu-05-june-2018--v1066) instead.
# Mo, 21 May 2018 | v10.6.5
This history entry is not translated yet to the Bahasa Indonesia language yet, please refer to the english version of the [HISTORY entry](https://github.com/kataras/iris/blob/master/HISTORY.md#mo-21-may-2018--v1065) instead.
# We, 09 May 2018 | v10.6.4
- [fix issue 995](https://github.com/kataras/iris/commit/62457279f41a1f157869a19ef35fb5198694fddb)
- [fix issue 996](https://github.com/kataras/iris/commit/a11bb5619ab6b007dce15da9984a78d88cd38956)
# We, 02 May 2018 | v10.6.3
**Every server should be upgraded to this version**, it contains an important, but easy, fix for the `websocket/Connection#Emit##To`.
- Websocket: fix https://github.com/kataras/iris/issues/991
# Tu, 01 May 2018 | v10.6.2
- Websocket: added OnPong to Connection via PR: https://github.com/kataras/iris/pull/988
- Websocket: `OnError` accepts a `func(error)` now instead of `func(string)`, as requested at: https://github.com/kataras/iris/issues/987
# We, 25 April 2018 | v10.6.1
- Re-implement the [BoltDB](https://github.com/coreos/bbolt) as built'n back-end storage for sessions(`sessiondb`) using the latest features: [/sessions/sessiondb/boltdb/database.go](sessions/sessiondb/boltdb/database.go), example can be found at [/_examples/sessions/database/boltdb/main.go](_examples/sessions/database/boltdb/main.go).
- Fix a minor issue on [Badger sessiondb example](_examples/sessions/database/badger/main.go). Its `sessions.Config { Expires }` field was `2 *time.Second`, it's `45 *time.Minute` now.
- Other minor improvements to the badger sessiondb.
# Su, 22 April 2018 | v10.6.0
- Fix open redirect by @wozz via PR: https://github.com/kataras/iris/pull/972.
- Fix when destroy session can't remove cookie in subdomain by @Chengyumeng via PR: https://github.com/kataras/iris/pull/964.
- Add `OnDestroy(sid string)` on sessions for registering a listener when a session is destroyed with commit: https://github.com/kataras/iris/commit/d17d7fecbe4937476d00af7fda1c138c1ac6f34d.
- Finally, sessions are in full-sync with the registered database now. That required a lot of internal code changed but **zero code change requirements by your side**. We kept only `badger` and `redis` as the back-end built'n supported sessions storages, they are enough. Made with commit: https://github.com/kataras/iris/commit/f2c3a5f0cef62099fd4d77c5ccb14f654ddbfb5c relative to many issues that you've requested it.
# Sa, 24 March 2018 | v10.5.0
### New
Add new client cache (helpers) middlewares for even faster static file servers. Read more [there](https://github.com/kataras/iris/pull/935).
### Breaking Change
Change the `Value<T>Default(<T>, error)` to `Value<T>Default(key, defaultValue) <T>` like `ctx.PostValueIntDefault` or `ctx.Values().GetIntDefault` or `sessions/session#GetIntDefault` or `context#URLParamIntDefault`.
The proposal was made by @jefurry at https://github.com/kataras/iris/issues/937.
#### How to align your existing codebase
Just remove the second return value from these calls.
Nothing too special or hard to change here, think that in our 100+ [_examples](_examples) we had only two of them.
For example: at [_examples/mvc/basic/main.go line 100](_examples/mvc/basic/main.go#L100) the `count,_ := c.Session.GetIntDefault("count", 1)` **becomes now:** `count := c.Session.GetIntDefault("count", 1)`.
> Remember that if you can't upgrade then just don't, we dont have any security fixes in this release, but at some point you will have to upgrade for your own good, we always add new features that you will love to embrace!
# We, 14 March 2018 | v10.4.0
- fix `APIBuilder, Party#StaticWeb` and `APIBuilder, Party#StaticEmbedded` wrong strip prefix inside children parties
- keep the `iris, core/router#StaticEmbeddedHandler` and remove the `core/router/APIBuilder#StaticEmbeddedHandler`, (note the `Handler` suffix) it's global and has nothing to do with the `Party` or the `APIBuilder`
- fix high path cleaning between `{}` (we already escape those contents at the [interpreter](macro/interpreter) level but some symbols are still removed by the higher-level api builder) , i.e `\\` from the string's macro function `regex` contents as reported at [927](https://github.com/kataras/iris/issues/927) by [commit e85b113476eeefffbc7823297cc63cd152ebddfd](https://github.com/kataras/iris/commit/e85b113476eeefffbc7823297cc63cd152ebddfd)
- sync the `golang.org/x/sys/unix` vendor
## The most important
We've made static files served up to 8 times faster using the new tool, <https://github.com/kataras/bindata> which is a fork of your beloved `go-bindata`, some unnecessary things for us were removed there and contains some additions for performance boost.
## Reqs/sec with [shuLhan/go-bindata](https://github.com/shuLhan/go-bindata) and alternatives
![go-bindata](https://github.com/kataras/bindata/raw/master/go-bindata-benchmark.png)
## Reqs/sec with [kataras/bindata](https://github.com/kataras/bindata)
![bindata](https://github.com/kataras/bindata/raw/master/bindata-benchmark.png)
A **new** function `Party#StaticEmbeddedGzip` which has the same input arguments as the `Party#StaticEmbedded` added. The difference is that the **new** `StaticEmbeddedGzip` accepts the `GzipAsset` and `GzipAssetNames` from the `bindata` (go get -u github.com/kataras/bindata/cmd/bindata).
You can still use both `bindata` and `go-bindata` tools in the same folder, the first for embedding the rest of the static files (javascript, css, ...) and the second for embedding the templates!
A full example can be found at: [_examples/file-server/embedding-gziped-files-into-app/main.go](_examples/file-server/embedding-gziped-files-into-app/main.go).
_Happy Coding!_
# Sa, 10 March 2018 | v10.3.0
- The only one API Change is the [Application/Context/Router#RouteExists](https://godoc.org/github.com/kataras/iris/core/router#Router.RouteExists), it accepts the `Context` as its first argument instead of last now.
- Fix cors middleware via https://github.com/iris-contrib/middleware/commit/048e2be034ed172c6754448b8a54a9c55debad46, relative issue: https://github.com/kataras/iris/issues/922 (still pending for a verification).
- Add `Context#NextOr` and `Context#NextOrNotFound`
```go
// NextOr checks if chain has a next handler, if so then it executes it
// otherwise it sets a new chain assigned to this Context based on the given handler(s)
// and executes its first handler.
//
// Returns true if next handler exists and executed, otherwise false.
//
// Note that if no next handler found and handlers are missing then
// it sends a Status Not Found (404) to the client and it stops the execution.
NextOr(handlers ...Handler) bool
// NextOrNotFound checks if chain has a next handler, if so then it executes it
// otherwise it sends a Status Not Found (404) to the client and stops the execution.
//
// Returns true if next handler exists and executed, otherwise false.
NextOrNotFound() bool
```
- Add a new `Party#AllowMethods` which if called before any `Handle, Get, Post...` will clone the routes to that methods as well.
- Fix trailing slash from POST method request redirection as reported at: https://github.com/kataras/iris/issues/921 via https://github.com/kataras/iris/commit/dc589d9135295b4d080a9a91e942aacbfe5d56c5
- Add examples for read using custom decoder per type, read using custom decoder via `iris#UnmarshalerFunc` and to complete it add an example for the `context#ReadXML`, you can find them [here](https://github.com/kataras/iris/tree/master/_examples#how-to-read-from-contextrequest-httprequest)via https://github.com/kataras/iris/commit/78cd8e5f677fe3ff2c863c5bea7d1c161bf4c31e.
- Add one more example for custom router macro functions, relative to https://github.com/kataras/iris/issues/918, you can find it [there](https://github.com/kataras/iris/blob/master/_examples/routing/dynamic-path/main.go#L144-L158), via https://github.com/kataras/iris/commit/a7690c71927cbf3aa876592fab94f04cada91b72
- Add wrappers for `Pongo`'s `AsValue()` and `AsSaveValue()` by @neenar via PR: https://github.com/kataras/iris/pull/913
- Remove unnecessary reflection usage on `context#UnmarshalBody` via https://github.com/kataras/iris/commit/4b9e41458b62035ea4933789c0a132c3ef2a90cc
# Th, 15 February 2018 | v10.2.1
Fix subdomains' `StaticEmbedded` & `StaticWeb` not found errors, as reported by [@speedwheel](https://github.com/speedwheel) via [facebook page's chat](https://facebook.com/iris.framework).
# Th, 08 February 2018 | v10.2.0
A new minor version family because it contains a **BREAKING CHANGE** and a new `Party#Reset` function.
### Party#Done behavior change & new Party#DoneGlobal introduced
As correctly pointed out by @likakuli at https://github.com/kataras/iris/issues/901, the old `Done` registered
handlers globally instead of party's and its children routes, this was not by accident because `Done` was introduced
before the `UseGlobal` idea and it didn't change for the shake of stability. Now it's time to move on, the new `Done` should be called before the routes that they care about those done handlers and the **new** `DoneGlobal` works like the old `Done`; order doesn't matter and it appends those done handlers
to the current registered routes and the future, globally (to all subdomains, parties every route in the Application).
The [routing/writing-a-middleware](_examples/routing/writing-a-middleware) examples are updated, read those to understand what's going on, although if you used iris before and you know the vocabulary we use you don't have to, the `DoneGlobal` and `Done` are clearly separated.
### Party#Reset
A new `Party#Reset()` function introduced in order to be able to clear parent's Party's begin and done handlers that are registered via `Use` and `Done` at a previous state, nothing crazy about this, it just clears the `middleware` and `doneHandlers` of the current Party instance, see `core/router#APIBuilder` for more.
### Update your codebase
Just replace all existing `.Done(` with `.DoneGlobal(` using a rich code editor (like the [VSCode](https://marketplace.visualstudio.com/items?itemName=kataras2006.iris)) which supports `find and replace all` and you're ready to Go:)
# Tu, 06 February 2018 | v10.1.0
New Features:
- Multi-Level subdomain redirect helper, you can find an example [here](https://github.com/kataras/iris/blob/master/_examples/subdomains/redirect/main.go)
- Cache middleware which makes use of the `304` status code, request fires from client to server but server respond with a status code, client is responsible to render the cached, you can find an example [here](https://github.com/kataras/iris/blob/master/_examples/cache/client-side/main.go)
- `websocket/Connection#IsJoined(roomName string)` new method to check if a user is joined to a room. An un-joined connections cannot send messages, this check is optionally.
More:
- update vendor/golang/crypto package to its latest version again, they have a lot of fixes there, as you know we're always following the dependencies for any fixes and meanful updates.
- [don't force-set content type on gzip response writer's WriteString and Writef if already there](https://github.com/kataras/iris/commit/af79aad11932f1a4fcbf7ebe28274b96675d0000)
- [new: add websocket/Connection#IsJoined](https://github.com/kataras/iris/commit/cb9e30948c8f1dd099f5168218d110765989992e)
- [fix #897](https://github.com/kataras/iris/commit/21cb572b638e82711910745cfae3c52d836f01f9)
- [add context#StatusCodeNotSuccessful variable for customize even the rfc2616-sec10](https://github.com/kataras/iris/commit/c56b7a3f04d953a264dfff15dadd2b4407d62a6f)
- [fix example comment on routing/dynamic-path/main.go#L101](https://github.com/kataras/iris/commit/0fbf1d45f7893cb1393759b7362444f3d381d182)
- [new: Cache Middleware `iris.Cache304`](https://github.com/kataras/iris/commit/1722355870174cecbc12f7beff8514b058b3b912)
- [fix comment on csrf example](https://github.com/kataras/iris/commit/a39e3d7d6cf528e51e6c7e32a884a8d9f2fadc0b)
- [un-default the Configuration.RemoteAddrHeaders](https://github.com/kataras/iris/commit/47108dc5a147a8b23de61bef86fe9327f0781396)
- [add vscode extension link and badge](https://github.com/kataras/iris/commit/6f594c0a7c641cc98bd683163fffbf5fa5fc8de6)
- [add an `app.View` example for parsing and writing templates outside of the HTTP (similar to context#View)](_examples/view/write-to)
- [new: Support multi-level subdomains redirect](https://github.com/kataras/iris/commit/12d7df113e611a75088c2a72774dab749d2c7685).
# Tu, 16 January 2018 | v10.0.2
## Security | `iris.AutoTLS`
**Every server should be upgraded to this version**, it contains fixes for the _tls-sni challenge disabled_ some days ago by letsencrypt.org which caused almost every https-enabled golang server to be unable to be functional, therefore support for the _http-01 challenge type_ added. Now the server is testing all available letsencrypt challenges.
Read more at:
- https://letsencrypt.status.io/pages/incident/55957a99e800baa4470002da/5a55777ed9a9c1024c00b241
- https://github.com/golang/crypto/commit/13931e22f9e72ea58bb73048bc752b48c6d4d4ac
# Mo, 15 January 2018 | v10.0.1
Not any serious problems were found to be resolved here but one, the first one which is important for devs that used the [cache](cache) package.
- fix a single one cache handler didn't work across multiple route handlers at the same time https://github.com/kataras/iris/pull/852, as reported at https://github.com/kataras/iris/issues/850
- merge PR https://github.com/kataras/iris/pull/862
- do not allow concurrent access to the `ExecuteWriter -> Load` when `view#Engine##Reload` was true, as requested at https://github.com/kataras/iris/issues/872
- badge for open-source projects powered by Iris, learn how to add that badge to your open-source project at [FAQ.md](FAQ.md) file
- upstream update for `golang/crypto` to apply the fix about the [tls-sni challenge disabled](https://letsencrypt.status.io/pages/incident/55957a99e800baa4470002da/5a55777ed9a9c1024c00b241) https://github.com/golang/crypto/commit/13931e22f9e72ea58bb73048bc752b48c6d4d4ac (**relative to iris.AutoTLS**)
## New Backers
1. https://opencollective.com/cetin-basoz
## New Translations
1. The Chinese README_ZH.md and HISTORY_ZH.md was translated by @Zeno-Code via https://github.com/kataras/iris/pull/858
2. New Russian README_RU.md translations by @merrydii via https://github.com/kataras/iris/pull/857
3. New Greek README_GR.md and HISTORY_GR.md translations via https://github.com/kataras/iris/commit/8c4e17c2a5433c36c148a51a945c4dc35fbe502a#diff-74b06c740d860f847e7b577ad58ddde0 and https://github.com/kataras/iris/commit/bb5a81c540b34eaf5c6c8e993f644a0e66a78fb8
## New Examples
1. [MVC - Register Middleware](_examples/mvc/middleware)
## New Articles
1. [A Todo MVC Application using Iris and Vue.js](https://hackernoon.com/a-todo-mvc-application-using-iris-and-vue-js-5019ff870064)
2. [A Hasura starter project with a ready to deploy Golang hello-world web app with IRIS](bit.ly/2lmKaAZ)
# Mo, 01 January 2018 | v10.0.0
We must thanks [Mrs. Diana](https://www.instagram.com/merry.dii/) for our awesome new [logo](https://iris-go.com/images/icon.svg)!
You can [contact](mailto:Kovalenkodiana8@gmail.com) her for any design-related enquiries or explore and send a direct message via [instagram](https://www.instagram.com/merry.dii/).
<p align="center">
<img width="145px" src="https://iris-go.com/images/icon.svg?v=a" />
</p>
At this version we have many internal improvements but just two major changes and one big feature, called **hero**.
> The new version adds 75 plus new commits, the PR is located [here](https://github.com/kataras/iris/pull/849) read the internal changes if you are developing a web framework based on Iris. Why 9 was skipped? Because.
## Hero
The new package [hero](hero) contains features for binding any object or function that `handlers` may use, these are called dependencies. Hero funcs can also return any type of values, these values will be dispatched to the client.
> You may saw binding before but you didn't have code editor's support, with Iris you get truly safe binding thanks to the new `hero` package. It's also fast, near to raw handlers performance because Iris calculates everything before server ran!
Below you will see some screenshots we prepared for you in order to be easier to understand:
### 1. Path Parameters - Built'n Dependencies
![](https://github.com/kataras/explore/raw/master/iris/hero/hero-1-monokai.png)
### 2. Services - Static Dependencies
![](https://github.com/kataras/explore/raw/master/iris/hero/hero-2-monokai.png)
### 3. Per-Request - Dynamic Dependencies
![](https://github.com/kataras/explore/raw/master/iris/hero/hero-3-monokai.png)
`hero funcs` are very easy to understand and when you start using them **you never go back**.
Examples:
- [Basic](_examples/hero/basic/main.go)
- [Overview](_examples/hero/overview)
## MVC
You have to understand the `hero` package in order to use the `mvc`, because `mvc` uses the `hero` internally for the controller's methods you use as routes, the same rules applied to those controller's methods of yours as well.
With this version you can register **any controller's methods as routes manually**, you can **get a route based on a method name and change its `Name` (useful for reverse routing inside templates)**, you can use any **dependencies** registered from `hero.Register` or `mvc.New(iris.Party).Register` per mvc application or per-controller, **you can still use `BeginRequest` and `EndRequest`**, you can catch **`BeforeActivation(b mvc.BeforeActivation)` to add dependencies per controller and `AfterActivation(a mvc.AfterActivation)` to make any post-validations**, **singleton controllers when no dynamic dependencies are used**, **Websocket controller, as simple as a `websocket.Connection` dependency** and more...
Examples:
**If you used MVC before then read very carefully: MVC CONTAINS SOME BREAKING CHANGES BUT YOU CAN DO A LOT MORE AND EVEN FASTER THAN BEFORE**
**PLEASE READ THE EXAMPLES CAREFULLY, WE'VE MADE THEM FOR YOU**
Old examples are here as well. Compare the two different versions of each example to understand what you win if you upgrade now.
| NEW | OLD |
| -----------|-------------|
| [Hello world](_examples/mvc/hello-world/main.go) | [OLD Hello world](https://github.com/kataras/iris/blob/v8/_examples/mvc/hello-world/main.go) |
| [Session Controller](_examples/mvc/session-controller/main.go) | [OLD Session Controller](https://github.com/kataras/iris/blob/v8/_examples/mvc/session-controller/main.go) |
| [Overview - Plus Repository and Service layers](_examples/mvc/overview) | [OLD Overview - Plus Repository and Service layers](https://github.com/kataras/iris/tree/v8/_examples/mvc/overview) |
| [Login showcase - Plus Repository and Service layers](_examples/mvc/login) | [OLD Login showcase - Plus Repository and Service layers](https://github.com/kataras/iris/tree/v8/_examples/mvc/login) |
| [Singleton](_examples/mvc/singleton) | **NEW** |
| [Websocket Controller](_examples/mvc/websocket) | **NEW** |
| [Vue.js Todo MVC](_examples/tutorial/vuejs-todo-mvc) | **NEW** |
## context#PostMaxMemory
Remove the old static variable `context.DefaultMaxMemory` and replace it with the configuration `WithPostMaxMemory`.
```go
// WithPostMaxMemory sets the maximum post data size
// that a client can send to the server, this differs
// from the overral request body size which can be modified
// by the `context#SetMaxRequestBodySize` or `iris#LimitRequestBodySize`.
//
// Defaults to 32MB or 32 << 20 if you prefer.
func WithPostMaxMemory(limit int64) Configurator
```
If you used that old static field you will have to change that single line.
Usage:
```go
import "github.com/kataras/iris"
func main() {
app := iris.New()
// [...]
app.Run(iris.Addr(":8080"), iris.WithPostMaxMemory(10 << 20))
}
```
## context#UploadFormFiles
New method to upload multiple files, should be used for common upload actions, it's just a helper function.
```go
// UploadFormFiles uploads any received file(s) from the client
// to the system physical location "destDirectory".
//
// The second optional argument "before" gives caller the chance to
// modify the *miltipart.FileHeader before saving to the disk,
// it can be used to change a file's name based on the current request,
// all FileHeader's options can be changed. You can ignore it if
// you don't need to use this capability before saving a file to the disk.
//
// Note that it doesn't check if request body streamed.
//
// Returns the copied length as int64 and
// a not nil error if at least one new file
// can't be created due to the operating system's permissions or
// http.ErrMissingFile if no file received.
//
// If you want to receive & accept files and manage them manually you can use the `context#FormFile`
// instead and create a copy function that suits your needs, the below is for generic usage.
//
// The default form's memory maximum size is 32MB, it can be changed by the
// `iris#WithPostMaxMemory` configurator at main configuration passed on `app.Run`'s second argument.
//
// See `FormFile` to a more controlled to receive a file.
func (ctx *context) UploadFormFiles(
destDirectory string,
before ...func(string, string),
) (int64, error)
```
Example can be found [here](_examples/http_request/upload-files/main.go).
## context#View
Just a minor addition, add a second optional variadic argument to the `context#View` method to accept a single value for template binding.
When you just want one value and not key-value pairs, you used to use an empty string on the `ViewData`, which is fine, especially if you preload these from a previous handler/middleware in the request handlers chain.
```go
func(ctx iris.Context) {
ctx.ViewData("", myItem{Name: "iris" })
ctx.View("item.html")
}
```
Same as:
```go
func(ctx iris.Context) {
ctx.View("item.html", myItem{Name: "iris" })
}
```
```html
Item's name: {{.Name}}
```
## context#YAML
Add a new `context#YAML` function, it renders a yaml from a structured value.
```go
// YAML marshals the "v" using the yaml marshaler and renders its result to the client.
func YAML(v interface{}) (int, error)
```
## Session#GetString
`sessions/session#GetString` can now return a filled value even if the stored value is a type of integer, just like the memstore, the context's temp store, the context's path parameters and the context's url parameters.

View File

@ -1,412 +0,0 @@
# 更新记录 <a href="HISTORY.md"> <img width="20px" src="https://iris-go.com/images/flag-unitedkingdom.svg?v=10" /></a> <a href="HISTORY_ID.md"> <img width="20px" src="https://iris-go.com/images/flag-indonesia.svg?v=10" /></a> <a href="HISTORY_GR.md"> <img width="20px" src="https://iris-go.com/images/flag-greece.svg?v=10" /></a>
### 想得到免费即时的支持?
https://github.com/kataras/iris/issues
https://chat.iris-go.com
### 获取历史版本?
https://github.com/kataras/iris/releases
### 我是否应该升级 Iris?
如果没有必要,不会强制升级。如果你已经准备好了,可以随时升级。
> Iris 使用 Golang 的 [vendor directory](https://docs.google.com/document/d/1Bz5-UB7g2uPBdOx-rw5t9MxJwkfpx90cqG9AFL0JAYo) 特性, 避免依赖包的更改带来影响。
**如何升级**: 打开命令行执行以下命令: `go get -u github.com/kataras/iris` 或者等待自动更新。
# Fr, 11 January 2019 | v11.1.1
This history entry is not translated yet to the Chinese language yet, please refer to the english version of the [HISTORY entry](https://github.com/kataras/iris/blob/master/HISTORY.md#fr-11-january-2019--v1111) instead.
# Su, 18 November 2018 | v11.1.0
This history entry is not translated yet to the Chinese language yet, please refer to the english version of the [HISTORY entry](https://github.com/kataras/iris/blob/master/HISTORY.md#su-18-november-2018--v1110) instead.
# Fr, 09 November 2018 | v11.0.4
This history entry is not translated yet to the Chinese language yet, please refer to the english version of the [HISTORY entry](https://github.com/kataras/iris/blob/master/HISTORY.md#fr-09-november-2018--v1104) instead.
# Tu, 30 October 2018 | v11.0.2
This history entry is not translated yet to the Chinese language yet, please refer to the english version of the [HISTORY entry](https://github.com/kataras/iris/blob/master/HISTORY.md#tu-30-october-2018--v1102) instead.
# Su, 28 October 2018 | v11.0.1
This history entry is not translated yet to the Chinese language yet, please refer to the english version of the [HISTORY entry](https://github.com/kataras/iris/blob/master/HISTORY.md#su-28-october-2018--v1101) instead.
# Su, 21 October 2018 | v11.0.0
This history entry is not translated yet to the Chinese language yet, please refer to the english version of the [HISTORY entry](https://github.com/kataras/iris/blob/master/HISTORY.md#su-21-october-2018--v1100) instead.
# Sat, 11 August 2018 | v10.7.0
This history entry is not translated yet to the Chinese language yet, please refer to the english version of the [HISTORY entry](https://github.com/kataras/iris/blob/master/HISTORY.md#sat-11-august-2018--v1070) instead.
# Tu, 05 June 2018 | v10.6.6
This history entry is not translated yet to the Chinese language yet, please refer to the english version of the [HISTORY entry](https://github.com/kataras/iris/blob/master/HISTORY.md#tu-05-june-2018--v1066) instead.
# Mo, 21 May 2018 | v10.6.5
This history entry is not translated yet to the Chinese language yet, please refer to the english version of the [HISTORY entry](https://github.com/kataras/iris/blob/master/HISTORY.md#mo-21-may-2018--v1065) instead.
# We, 09 May 2018 | v10.6.4
- [fix issue 995](https://github.com/kataras/iris/commit/62457279f41a1f157869a19ef35fb5198694fddb)
- [fix issue 996](https://github.com/kataras/iris/commit/a11bb5619ab6b007dce15da9984a78d88cd38956)
# We, 02 May 2018 | v10.6.3
This history entry is not translated yet to the Chinese language yet, please refer to the english version of the [HISTORY entry](https://github.com/kataras/iris/blob/master/HISTORY.md#we-02-may-2018--v1063) instead.
# Tu, 01 May 2018 | v10.6.2
This history entry is not translated yet to the Chinese language yet, please refer to the english version of the [HISTORY entry](https://github.com/kataras/iris/blob/master/HISTORY.md#tu-01-may-2018--v1062) instead.
# 2018 4月25日 | v10.6.1 版本更新
- 用最新版 BoltDB 重新实现 session (`sessiondb`) 存储:[/sessions/sessiondb/boltdb/database.go](sessions/sessiondb/boltdb/database.go), 相关示例 [/_examples/sessions/database/boltdb/main.go](_examples/sessions/database/boltdb/main.go).
- 修正 一个小问题 on [Badger sessiondb example](_examples/sessions/database/badger/main.go). `sessions.Config { Expires }` 字段由 `2 *time.Second` 调整为 `45 *time.Minute` .
- badger sessiondb 其他小改进.
# 2018 4月22日 | v10.6.0 版本更新
- 修正 重定向问题 由 @wozz 提交: https://github.com/kataras/iris/pull/972.
- 修正 无法销毁子域名 session 问题 由 @Chengyumeng 提交: https://github.com/kataras/iris/pull/964.
- 添加 `OnDestroy(sid string)` 当 session 销毁时注册监听器 相关细节: https://github.com/kataras/iris/commit/d17d7fecbe4937476d00af7fda1c138c1ac6f34d.
- sessions 现在与注册数据库完全同步。 这涉及到很多内部改动,但 **这不影响你当前项目代码**. 我们只保留了 `badger``redis` 作为底部支持。 相关细节: https://github.com/kataras/iris/commit/f2c3a5f0cef62099fd4d77c5ccb14f654ddbfb5c
# 2018 3月 24日 | v10.5.0 版本更新
### 新增
新增 缓存中间件客户端,更快的静态文件服务器. 详情 [点击](https://github.com/kataras/iris/pull/935).
### 破坏式更新
改变 `Value<T>Default(<T>, error)``Value<T>Default(key, defaultValue) <T>` 如同 `ctx.PostValueIntDefault` 或 `ctx.Values().GetIntDefault``sessions/session#GetIntDefault``context#URLParamIntDefault`.
@jefurry 提出 https://github.com/kataras/iris/issues/937.
#### 如何升级现有代码
只需要移除第二个返回值即可.
示例: [_examples/mvc/basic/main.go line 100](_examples/mvc/basic/main.go#L100)  `count,_ := c.Session.GetIntDefault("count", 1)` **变更为:** `count := c.Session.GetIntDefault("count", 1)`.
> 请记住,如果您无法升级,那么就不要这样做,我们在此版本中没有任何安全修复程序,但在某些时候建议您最好进行升级,我们总是会添加您喜欢的新功能!
# 2018 3月14日 | v10.4.0 版本更新
- 修正 `APIBuilder, Party#StaticWeb``APIBuilder, Party#StaticEmbedded` 子分组内的前缀错误
- 保留 `iris, core/router#StaticEmbeddedHandler` 并移除 `core/router/APIBuilder#StaticEmbeddedHandler`, (`Handler` 后缀) 这是全局性的,与 `Party` `APIBuilder` 无关。
- 修正 路径 `{}` 中的路径清理 (我们已经在 [解释器](macro/interpreter) 级别转义了这些字符, 但是一些符号仍然被更高级别的API构建器删除) , 例如 `\\` 字符串的宏函数正则表达式内容 [927](https://github.com/kataras/iris/issues/927) by [commit e85b113476eeefffbc7823297cc63cd152ebddfd](https://github.com/kataras/iris/commit/e85b113476eeefffbc7823297cc63cd152ebddfd)
- 同步 `golang.org/x/sys/unix`
## 重要变更
我们使用新工具将静态文件的速度提高了8倍, <https://github.com/kataras/bindata> 这是 go-bindata 的一个分支,对我们来说,一些不必要的东西被移除了,并且包含一些提高性能的补充。
## Reqs/sec 使用 [shuLhan/go-bindata](https://github.com/shuLhan/go-bindata) 和 备选方案对比
![go-bindata](https://github.com/kataras/bindata/raw/master/go-bindata-benchmark.png)
## Reqs/sec 使用 [kataras/bindata](https://github.com/kataras/bindata)
![bindata](https://github.com/kataras/bindata/raw/master/bindata-benchmark.png)
**新增** 方法 `Party#StaticEmbeddedGzip``Party#StaticEmbedded` 参数相同. 不同处在于 **新增** `StaticEmbeddedGzip` 从 `bindata` 接收 `GzipAsset` 和 `GzipAssetNames` (go get -u github.com/kataras/bindata/cmd/bindata).
你可以在同个文件夹里同时使用 `bindata``go-bindata` 工具, 第一个用于嵌入静态文件 (javascript, css, ...) 第二个用于静态编译模板!
完整示例: [_examples/file-server/embedding-gziped-files-into-app/main.go](_examples/file-server/embedding-gziped-files-into-app/main.go).
# 2018 3月10号 | v10.3.0 版本更新
- 只有一项 API 更改 [Application/Context/Router#RouteExists](https://godoc.org/github.com/kataras/iris/core/router#Router.RouteExists), 将 `Context` 作为第一参数,而不是最后一个。
- 修正 cors 中间件 https://github.com/iris-contrib/middleware/commit/048e2be034ed172c6754448b8a54a9c55debad46, 相关问题: https://github.com/kataras/iris/issues/922 (目前仍在等待验证).
- 添加 `Context#NextOr``Context#NextOrNotFound` 方法
```go
// NextOr 检查程序链上是否有下一个处理程序,如果是,则执行它
// 否则根据给定的处理程序设置分配给 Context 程序链,并且执行第一个控制器。
//
// 如果下一个处理器存在并执行则返回true否则返回false
//
// 请注意,如果没有找到下一个处理程序并且处理程序缺失,
// 会发送 (404) 状态码到客户端,并停止执行。
NextOr(handlers ...Handler) bool
// NextOrNotFound 检查程序链上是否存在下一个处理程序,如果有则执行
// 其他情况会发送 404 状态码,并停止执行。
//
// 如果下一个控制器存在并执行,返回 true , 其他情况 false.
NextOrNotFound() bool
```
- 新增方法 `Party#AllowMethods` 如果在 `Handle, Get, Post...` 之前调用,则会将路由克隆到该方法.
- 修复 POST 请求尾部斜杠重定向问题: https://github.com/kataras/iris/issues/921 https://github.com/kataras/iris/commit/dc589d9135295b4d080a9a91e942aacbfe5d56c5
- 新增示例 通过 `iris#UnmarshalerFunc` 自定义解码, 新增 `context#ReadXML` 使用示例, [相关示例](https://github.com/kataras/iris/tree/master/_examples#how-to-read-from-contextrequest-httprequest)via https://github.com/kataras/iris/commit/78cd8e5f677fe3ff2c863c5bea7d1c161bf4c31e.
- 新增自定义路由宏功能示例, 相关讨论 https://github.com/kataras/iris/issues/918, [示例代码](https://github.com/kataras/iris/blob/master/_examples/routing/dynamic-path/main.go#L144-L158), https://github.com/kataras/iris/commit/a7690c71927cbf3aa876592fab94f04cada91b72
- 为 `Pongo` 新增 `AsValue()``AsSaveValue()` @neenar https://github.com/kataras/iris/pull/913
- 删除 `context#UnmarshalBody` 上不必要的反射 https://github.com/kataras/iris/commit/4b9e41458b62035ea4933789c0a132c3ef2a90cc
# 2018 2月15号 | v10.2.1 版本更新
修正 子域名 (subdomain) 的 `StaticEmbedded``StaticWeb` 不存在错误, 由 [@speedwheel](https://github.com/speedwheel) 通过 [facebook page's chat](https://facebook.com/iris.framework) 反馈。
# 2018 2月8号 | v10.2.0 版本更新
新的小版本, 因为它包含一个 **破坏性变动** 和一个新功能 `Party#Reset`
### Party#Done 特性变动 和 新增 Party#DoneGlobal 介绍
正如 @likakuli 指出的那样 https://github.com/kataras/iris/issues/901, 以前 `Done` 注册的处理器,在全局范围内会替代子处理器,因为在引入 `UseGlobal` 这概念之前,缺少稳定性. 现在是时候了, 新的 `Done` 应该在相关的路由之前调用, **新增** `DoneGlobal` 之前的`Done` 使用相同; 顺序无关紧要,他只是结束处理附加到当前的注册程序, 全局性的 (所有子域名,分组).
[routing/writing-a-middleware](_examples/routing/writing-a-middleware) 路由中间件示例更新, 列举了使用方式变化, 如果之前使用过 Iris ,并熟悉内置函数方法名称,请区分 `DoneGlobal` 和 `Done` 的不同.
### Party#Reset
新增 `Party#Reset()` 函数,以便重置上级分组通过 `Use``Done` 注册的处理方法, 没有什么特别之处,它只是清除当前分组实例的 `middleware``doneHandlers`,详情参见 `core/router#APIBuilder`.
### 更新方法
只需要将现有的 `.Done` 替换为 `.DoneGlobal` 就可以了。
# 2018 2月6号 | v10.1.0 版本更新
新特性:
- 多级域名跳转, 相关示例 [here](https://github.com/kataras/iris/blob/master/_examples/subdomains/redirect/main.go)
- 缓存中间件携带 `304` 状态码, 缓存期间的请求,服务器只响应状态, 相关示例 [here](https://github.com/kataras/iris/blob/master/_examples/cache/client-side/main.go)
- `websocket/Connection#IsJoined(roomName string)` 新增方法,检查用户是否加入房间。 未加入的连接不能发送消息,此检查是可选的.
详情:
- 更新上游 vendor/golang/crypto 包到最新版本, 我们总是跟进依赖关系的任何修复和有意义的更新.
- [改进不在gzip响应的WriteString和Writef上强制设置内容类型如果已经存在的话](https://github.com/kataras/iris/commit/af79aad11932f1a4fcbf7ebe28274b96675d0000)
- [新增websocket/Connection#IsJoined](https://github.com/kataras/iris/commit/cb9e30948c8f1dd099f5168218d110765989992e)
- [修复:#897](https://github.com/kataras/iris/commit/21cb572b638e82711910745cfae3c52d836f01f9)
- [新增context#StatusCodeNotSuccessful 变量用来定制 rfc2616-sec10](https://github.com/kataras/iris/commit/c56b7a3f04d953a264dfff15dadd2b4407d62a6f)
- [修复:示例 routing/dynamic-path/main.go#L101](https://github.com/kataras/iris/commit/0fbf1d45f7893cb1393759b7362444f3d381d182)
- [新增:缓存中间件 `iris.Cache304`](https://github.com/kataras/iris/commit/1722355870174cecbc12f7beff8514b058b3b912)
- [修复:示例 csrf](https://github.com/kataras/iris/commit/a39e3d7d6cf528e51e6c7e32a884a8d9f2fadc0b)
- [取消Configuration.RemoteAddrHeaders 默认值](https://github.com/kataras/iris/commit/47108dc5a147a8b23de61bef86fe9327f0781396)
- [新增vscode 扩展链接和徽章](https://github.com/kataras/iris/commit/6f594c0a7c641cc98bd683163fffbf5fa5fc8de6)
- [新增:`app.View` 示例 用于解析和编写HTTP之外的模板类似于上下文视图)](_examples/view/write-to)
- [新增:支持多级域名跳转](https://github.com/kataras/iris/commit/12d7df113e611a75088c2a72774dab749d2c7685).
# 2018 1月16号 | v10.0.2 版本更新
## 安全更新 | `iris.AutoTLS`
**建议升级**, 包含几天前修复了 letsencrypt.org 禁用 tls-sni 的问题,这导致几乎每个启用了 https 的 golang 服务器都无法正常工作,因此支持添加了 http-01 类型。 现在服务器会尝试所有可用的 letsencrypt 类型。
更多相关资讯:
- https://letsencrypt.status.io/pages/incident/55957a99e800baa4470002da/5a55777ed9a9c1024c00b241
- https://github.com/golang/crypto/commit/13931e22f9e72ea58bb73048bc752b48c6d4d4ac
# 2018 1月15号 | v10.0.1 版本更新
该版本暂未发现重大问题,但如果你使用 [cache](cache) 包的话,这里有些更新或许正好解决某些问题。
- 修复缓存在同一控制器多个方法中,返回相同内容问题 https://github.com/kataras/iris/pull/852, 问题报告https://github.com/kataras/iris/issues/850
- 问题修正 https://github.com/kataras/iris/pull/862
- 当 `view#Engine##Reload` 为 true`ExecuteWriter -> Load` 不能同时使用问题,相关问题 https://github.com/kataras/iris/issues/872
- 由Iris提供支持的开源项目的徽章, 学习如何将徽章添加到您的开源项目中 [FAQ.md](FAQ.md)
- 上游更新 `golang/crypto` 修正 [tls-sni challenge disabled](https://letsencrypt.status.io/pages/incident/55957a99e800baa4470002da/5a55777ed9a9c1024c00b241) https://github.com/golang/crypto/commit/13931e22f9e72ea58bb73048bc752b48c6d4d4ac (**关系到 iris.AutoTLS**)
## 新增捐助
1. https://opencollective.com/cetin-basoz
## 新增翻译
1. 中文版 README_ZH.md and HISTORY_ZH.md 由 @Zeno-Code 翻译 https://github.com/kataras/iris/pull/858
2. 俄语版 README_RU.md 由 @merrydii 翻译 https://github.com/kataras/iris/pull/857
3. 希腊版 README_GR.md and HISTORY_GR.md https://github.com/kataras/iris/commit/8c4e17c2a5433c36c148a51a945c4dc35fbe502a#diff-74b06c740d860f847e7b577ad58ddde0 and https://github.com/kataras/iris/commit/bb5a81c540b34eaf5c6c8e993f644a0e66a78fb8
## 新增示例
1. [MVC - Register Middleware](_examples/mvc/middleware)
## 新增文章
1. [A Todo MVC Application using Iris and Vue.js](https://hackernoon.com/a-todo-mvc-application-using-iris-and-vue-js-5019ff870064)
2. [A Hasura starter project with a ready to deploy Golang hello-world web app with IRIS](bit.ly/2lmKaAZ)
# 2018 元旦 | v10.0.0 版本发布
我们必须感谢 [Mrs. Diana](https://www.instagram.com/merry.dii/) 帮我们绘制的漂亮 [logo](https://iris-go.com/images/icon.svg)!
如果有设计相关的需求,你可以[发邮件](mailto:Kovalenkodiana8@gmail.com)给他,或者通过 [instagram](https://www.instagram.com/merry.dii/) 给他发信息。
<p align="center">
<img width="145px" src="https://iris-go.com/images/icon.svg?v=a" />
</p>
在这个版本中,有许多内部优化改进,但只有两个重大变更和新增一个叫做 **hero** 的特性。
> 新版本有 75 + 的变更提交, 如果你需要升级 Iris 请仔细阅读本文档。 为什么版本 9 跳过了? 你猜...
## Hero 特性
新增包 [hero](hero) 可以绑定处理任何依赖 `handlers` 的对象或函数。Hero funcs 可以返回任何类型的值,并发送给客户端。
> 之前的绑定没有编辑器的支持, 新包 `hero` 为 Iris 带来真正的安全绑定。 Iris 会在服务器运行之前计算所有内容,所以它执行速度高,接近于原生性能。
下面你会看到我们为你准备的一些截图,以便于理解:
### 1. 路径参数 - 构建依赖
![](https://github.com/kataras/explore/raw/master/iris/hero/hero-1-monokai.png)
### 2. 服务 - 静态依赖
![](https://github.com/kataras/explore/raw/master/iris/hero/hero-2-monokai.png)
### 3. 请求之前 - 动态依赖
![](https://github.com/kataras/explore/raw/master/iris/hero/hero-3-monokai.png)
`hero funcs` 非常容易理解,当你用过之后 **在也回不去了**.
示例:
- [基本用法](_examples/hero/basic/main.go)
- [使用概览](_examples/hero/overview)
## MVC
如果要使用 `mvc` ,必须先理解 `hero` 包,因为`mvc`在内部使用`hero`作为路由控制器的方法,同样的规则也适用于你的控制器的方法。
With this version you can register **any controller's methods as routes manually**, you can **get a route based on a method name and change its `Name` (useful for reverse routing inside templates)**, you can use any **dependencies** registered from `hero.Register` or `mvc.New(iris.Party).Register` per mvc application or per-controller, **you can still use `BeginRequest` and `EndRequest`**, you can catch **`BeforeActivation(b mvc.BeforeActivation)` to add dependencies per controller and `AfterActivation(a mvc.AfterActivation)` to make any post-validations**, **singleton controllers when no dynamic dependencies are used**, **Websocket controller, as simple as a `websocket.Connection` dependency** and more...
示例:
**如果你之前使用过 MVC 请仔细阅读MVC 包含一些破坏性的改进,但新的方式可以做更多,会让程序执行更快**
**请阅读我们为你准备的示例**
如果你现在需要升级,请对比新旧版本示例的不同,便于理解。
| NEW | OLD |
| -----------|-------------|
| [Hello world](_examples/mvc/hello-world/main.go) | [OLD Hello world](https://github.com/kataras/iris/blob/v8/_examples/mvc/hello-world/main.go) |
| [Session Controller](_examples/mvc/session-controller/main.go) | [OLD Session Controller](https://github.com/kataras/iris/blob/v8/_examples/mvc/session-controller/main.go) |
| [Overview - Plus Repository and Service layers](_examples/mvc/overview) | [OLD Overview - Plus Repository and Service layers](https://github.com/kataras/iris/tree/v8/_examples/mvc/overview) |
| [Login showcase - Plus Repository and Service layers](_examples/mvc/login) | [OLD Login showcase - Plus Repository and Service layers](https://github.com/kataras/iris/tree/v8/_examples/mvc/login) |
| [Singleton](_examples/mvc/singleton) | **新增** |
| [Websocket Controller](_examples/mvc/websocket) | **新增** |
| [Vue.js Todo MVC](_examples/tutorial/vuejs-todo-mvc) | **新增** |
## context#PostMaxMemory
移除旧版本的常量 `context.DefaultMaxMemory` 替换为配置 `WithPostMaxMemory` 方法.
```go
// WithPostMaxMemory 设置客户端向服务器 post 提交数据的最大值
// 他不同于 request body 的值大小,如果有相关需求请使用
// `context#SetMaxRequestBodySize` 或者 `iris#LimitRequestBodySize`
//
// 默认值为 32MB 或者 32 << 20
func WithPostMaxMemory(limit int64) Configurator
```
如果你使用老版本的常量,你需要更改一行代码.
使用方式:
```go
import "github.com/kataras/iris"
func main() {
app := iris.New()
// [...]
app.Run(iris.Addr(":8080"), iris.WithPostMaxMemory(10 << 20))
}
```
## context#UploadFormFiles
新方法可以多文件上传, 应用于常见的上传操作, 它是一个非常有用的函数。
```go
// UploadFormFiles 将所有接收到的文件从客户端上传到系统物理位置 destDirectory。
//
// The second optional argument "before" gives caller the chance to
// modify the *miltipart.FileHeader before saving to the disk,
// it can be used to change a file's name based on the current request,
// all FileHeader's options can be changed. You can ignore it if
// you don't need to use this capability before saving a file to the disk.
//
// Note that it doesn't check if request body streamed.
//
// Returns the copied length as int64 and
// a not nil error if at least one new file
// can't be created due to the operating system's permissions or
// http.ErrMissingFile if no file received.
//
// If you want to receive & accept files and manage them manually you can use the `context#FormFile`
// instead and create a copy function that suits your needs, the below is for generic usage.
//
// The default form's memory maximum size is 32MB, it can be changed by the
// `iris#WithPostMaxMemory` configurator at main configuration passed on `app.Run`'s second argument.
//
// See `FormFile` to a more controlled to receive a file.
func (ctx *context) UploadFormFiles(
destDirectory string,
before ...func(string, string),
) (int64, error)
```
这里是相关示例 [here](_examples/http_request/upload-files/main.go).
## context#View
这里有个小更新,增加可选的第二个参数,用来绑定模版变量。提示:这种绑定方式,会忽略其他变量的绑定。
如果要忽略其他模版变量,之前是在 `ViewData` 上绑定一个空字符串,现在可以直接通过 View 方法添加。
```go
func(ctx iris.Context) {
ctx.ViewData("", myItem{Name: "iris" })
ctx.View("item.html")
}
```
等同于:
```go
func(ctx iris.Context) {
ctx.View("item.html", myItem{Name: "iris" })
}
```
```html
html 模版中调用: {{.Name}}
```
## context#YAML
新增 `context#YAML` 函数, 解析结构体到 yaml。
```go
//使用 yaml 包的 Marshal 的方法解析,并发送到客户端。
func YAML(v interface{}) (int, error)
```
## Session#GetString
`sessions/session#GetString` 可以获取 session 的变量值(可以是 integer 类型就像内存缓存、Context 上下文储存的值。

View File

@ -1,4 +1,4 @@
Copyright (c) 2017-2018 The Iris Authors. All rights reserved.
Copyright (c) 2017-2019 The Iris Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are

98
NOTICE Normal file
View File

@ -0,0 +1,98 @@
================================================================================
Third-Party Software for iris
================================================================================
The following 3rd-party software components may be used by or distributed with iris. This document was automatically generated by FOSSA on 2019-7-22; any information relevant to third-party vendors listed below are collected using common, reasonable means.
Revision ID: 607b5b7cef034da2692f99a4c9bafb31a999ccda
================================================================================
Direct Dependencies
================================================================================
----------------- ----------------- ------------------------------------------
Library Version Website
----------------- ----------------- ------------------------------------------
amber cdade1c073850f4 https://github.com/eknkc/amber
ffc70a829e31235
ea6892853b
blackfriday 48b3da6a6f3865c https://github.com/iris-contrib/
7eb1eba96d74cf0 blackfriday
a16f63faca
bluemonday 89802068f71166e https://github.com/microcosm-cc/
95c92040512bf2e bluemonday
11767721ed
columnize 9e6335e58db3b4c https://github.com/ryanuber/columnize
fe3c3c5c881f51f
fbc1091b34
formBinder fbd5963f41e18ae https://github.com/iris-contrib/
1f1423ba0462350 formBinder
94b0721ea1
go e369490fb7db5f2 https://github.com/golang/go
d42bb0e8ee19b48
378dee0ebf
go-version 192140e6f3e645d https://github.com/hashicorp/go-version
971b134d4e35b51
91adb9dfd3
go.uuid 36e9d2ebbde5e3f https://github.com/iris-contrib/go.uuid
13ab2e25625fd45
3271d6522e
golog 03be101463868ed https://github.com/kataras/golog
c5a81f094fc68a5
f6c1b5503a
goreferrer ec9c9a553398739 https://github.com/Shopify/goreferrer
f0dcf817e0ad5e0
1c4e7dcd08
httpexpect ebe99fcebbcedf6 https://github.com/iris-contrib/
e7916320cce24c3 httpexpect
e1832766ac
i18n 987a633949d087b https://github.com/iris-contrib/i18n
a52207b587792e8
c67d65780b
jade 9ffefa50b5f3141 https://github.com/Joker/jade
6ac643e9d9ad611
6f4688705f
json-iterator 08047c174c6c03e https://github.com/json-iterator/go
8ec963a411bde1b
6d1ee67b26
neffos c6806f19261108f https://github.com/kataras/neffos
bc1281e21faa79d
7193b36097
pongo2 8914e1cf9164420 https://github.com/flosch/pongo2
c91423cdefc7d97
8a76c38213
raymond b565731e1464263 https://github.com/aymerick/raymond
de0bda75f2e45d9
7b54b60110
structs 878a968ab225483 https://github.com/fatih/structs
62a09bdb3322f98
b00f470d46
toml 3012a1dbe2e4bd1 https://github.com/BurntSushi/toml
391d42b32f0577c
b7bbc7f005
yaml.v2 51d6538a90f86fe https://gopkg.in/yaml.v2
93ac480b35f37b2
be17fef232
================================================================================
Deep Dependencies
================================================================================
badger e9447c910efd3c6 https://github.com/dgraph-io/badger
7c5453ea1f65d2f
355544dd82
bbolt 2eb7227adea1d5c https://github.com/etcd-io/bbolt
f85f0bc2a82b705
9b13c2fa68
radix 5e391a8aaf46354 https://github.com/mediocregopher/radix
58e7d9f7296c125
01b06875c6

1093
README.md

File diff suppressed because it is too large Load Diff

View File

@ -1,24 +1,20 @@
# Iris Web Framework <a href="README.md"> <img width="20px" src="https://iris-go.com/images/flag-unitedkingdom.svg?v=10" /></a> <a href="README_ZH.md"> <img width="20px" src="https://iris-go.com/images/flag-china.svg?v=10" /></a> <a href="README_RU.md"><img width="20px" src="https://iris-go.com/images/flag-russia.svg?v=10" /></a> <a href="README_ID.md"> <img width="20px" src="https://iris-go.com/images/flag-indonesia.svg?v=10" /></a> <a href="README_PT_BR.md"><img width="20px" src="https://iris-go.com/images/flag-pt-br.svg?v=10" /></a> <a href="README_JPN.md"><img width="20px" src="https://iris-go.com/images/flag-japan.svg?v=10" /></a>
# Iris <a href="README.md"> <img width="20px" src="https://iris-go.com/images/flag-unitedkingdom.svg?v=10" /></a>
<a href="https://iris-go.com"> <img align="right" width="169px" src="https://iris-go.com/images/icon.svg?v=a" title="logo created by @merry.dii" /> </a>
[![build status](https://img.shields.io/travis/kataras/iris/master.svg?style=for-the-badge)](https://travis-ci.org/kataras/iris) [![report card](https://img.shields.io/badge/report%20card-a%2B-ff3333.svg?style=for-the-badge)](https://goreportcard.com/report/github.com/kataras/iris)<!--[![godocs](https://img.shields.io/badge/go-%20docs-488AC7.svg?style=for-the-badge)](https://godoc.org/github.com/kataras/iris)--> [![view examples](https://img.shields.io/badge/learn%20by-examples-0077b3.svg?style=for-the-badge)](https://github.com/kataras/iris/tree/master/_examples) [![chat](https://img.shields.io/gitter/room/iris_go/community.svg?color=blue&logo=gitter&style=for-the-badge)](https://gitter.im/iris_go/community) [![release](https://img.shields.io/badge/release%20-v11.2-0077b3.svg?style=for-the-badge)](https://github.com/kataras/iris/releases)
[![build status](https://img.shields.io/travis/kataras/iris/master.svg?style=flat-square)](https://travis-ci.org/kataras/iris)<!-- [![release](https://img.shields.io/github/release/kataras/iris.svg?style=flat-square)](https://github.com/kataras/iris/releases)--> [![report card](https://img.shields.io/badge/report%20card-a%2B-ff3333.svg?style=flat-square)](http://goreportcard.com/report/kataras/iris) [![vscode-iris](https://img.shields.io/badge/ext%20-vscode-0c77e3.svg?style=flat-square)](https://marketplace.visualstudio.com/items?itemName=kataras2006.iris)<!--[![github closed issues](https://img.shields.io/github/issues-closed-raw/kataras/iris.svg?style=flat-square)](https://github.com/kataras/iris/issues?q=is%3Aissue+is%3Aclosed)--> [![chat](https://img.shields.io/badge/community-%20chat-00BCD4.svg?style=flat-square)](https://kataras.rocket.chat/channel/iris) [![view examples](https://img.shields.io/badge/learn%20by-examples-0077b3.svg?style=flat-square)](https://github.com/kataras/iris/tree/master/_examples/routing) [![release](https://img.shields.io/badge/release%20-v11.1-0077b3.svg?style=flat-square)](https://github.com/kataras/iris/releases)
Το Iris είναι ένα γρήγορο, απλό αλλά και πλήρως λειτουργικό και πολύ αποδοτικό web framework για τη Go γλώσσα προγραμματισμού. Παρέχει ένα εκφραστικό και εύχρηστο υπόβαθρο για την επόμενη ιστοσελίδα σας.
Το Iris είναι ένα γρήγορο, απλό αλλά και πλήρως λειτουργικό και πολύ αποδοτικό web framework για τη Go.
Μάθετε τι [λένε οι άλλοι για το Iris](https://iris-go.com/testimonials/) και δώστε ένα **αστεράκι** στο GitHub.
Το Iris παρέχει ένα όμορφα εκφραστικό και εύχρηστο υπόβαθρο για την επόμενη σας ιστοσελίδα ή API.
## Μαθαίνοντας το Iris
Επιτέλους, ένα πραγματικά ισάξιο (και με το παραπάνω) expressjs web framework για τη γλώσσα προγραμματισμού Go.
Μάθετε τι [λένε οι άλλοι για το Iris](#%CE%A5%CF%80%CE%BF%CF%83%CF%84%CE%AE%CF%81%CE%B9%CE%BE%CE%B7) και [δώστε ένα αστέρι](https://github.com/kataras/iris/stargazers) στο github repository για να μένετε [πάντα ενημερωμένοι](https://facebook.com/iris.framework).
## Yποστηρικτές
Eυχαριστούμε όλους τους υποστηρικτές μας! 🙏 [Γίνετε ένας από αυτούς](https://iris-go.com/donate)
<a href="https://iris-go.com/donate" target="_blank"><img src="https://iris-go.com/backers.svg?v=2"/></a>
<details>
<summary>Γρήγορο ξεκίνημα</summary>
```sh
# υποθέτοντας ότι ο παρακάτω κώδικας
# βρίσκεται στο example.go αρχείο
#
$ cat example.go
```
@ -28,212 +24,51 @@ package main
import "github.com/kataras/iris"
func main() {
app := iris.New()
// Εδώ φορτώνουμε όλα τα templates από τον
// φάκελο "./views"
// όπου το extension είναι ".html" και αναλύουμε
// τα αρχεία αυτά βάση του `html/template` πακέτου.
app.RegisterView(iris.HTML("./views", ".html"))
// Method: GET
// Resource: http://localhost:8080
app.Get("/", func(ctx iris.Context) {
// Όπου {{.message}} εμφάνισε "Hello world!"
ctx.ViewData("message", "Hello world!")
// Εμφάνισε το σχετικό αρχείο "./views/hello.html"
ctx.View("hello.html")
app := iris.Default()
app.Get("/ping", func(ctx iris.Context) {
ctx.JSON(iris.Map{
"message": "pong",
})
})
// Method: GET
// Resource: http://localhost:8080/user/42
//
// Θέλετε να χρησημοποιήσετε regex expressions;
// Εύκολο,
// απλά δηλώστε τον τύπο της παραμέτρου ως 'string'
// ο οποίος δέχετε κάθε τιμή και κάντε χρήση
// της `regexp` macro function, για παράδειγμα:
// app.Get("/user/{id:string regexp(^[0-9]+$)}")
app.Get("/user/{id:long}", func(ctx iris.Context) {
userID, _ := ctx.Params().GetInt64("id")
ctx.Writef("User ID: %d", userID)
})
// Εδώ αρχίζουμε τον server χρησιμοποιώντας την
// τοπική διεύθυνση δικτύου με πόρτα την 8080.
app.Run(iris.Addr(":8080"))
}
```
> Μάθετε περισσότερα για τους τύπους παραμέτρων διαδρομής(routing) πατώντας [εδώ](_examples/routing/dynamic-path/main.go#L31)
```html
<!-- αρχείο: ./views/hello.html -->
<html>
<head>
<title>Hello Page</title>
</head>
<body>
<h1>{{.message}}</h1>
</body>
</html>
```
```sh
# τρέξτε το example.go και
# επισκεφτείτε την σελίδα http://localhost:8080/ping
# στο πρόγραμμα περιήγησης σας
#
$ go run example.go
Now listening on: http://localhost:8080
Application Started. Press CTRL+C to shut down.
_
```
## Εγκατάσταση
Η μόνη απαίτηση είναι η [Go Γλώσσα Προγραμματισμού](https://golang.org/dl/)
```sh
$ go get -u github.com/kataras/iris
```
Το Iris εκμεταλλεύεται τη λεγόμενη λειτουργία [vendor directory](https://docs.google.com/document/d/1Bz5-UB7g2uPBdOx-rw5t9MxJwkfpx90cqG9AFL0JAYo). Παίρνετε πλήρως αναπαραγωγίσιμα builds, καθώς αυτή η μέθοδος προστατεύει από τις upstream μετονομασίες και διαγραφές.
[![Iris vs .NET Core(C#) vs Node.js (Express)](https://iris-go.com/images/benchmark-new-gray.png)](_benchmarks/README_UNIX.md)
_Η τελευταία ενημέρωση έγινε την [Τρίτη, 21 Νοεμβρίου του 2017](_benchmarks/README_UNIX.md)_
<details>
<summary>Στοιχεία αναφοράς από τρίτες πηγές σε σχέση με τα υπόλοιπα web frameworks</summary>
![Comparison with other frameworks](https://raw.githubusercontent.com/smallnest/go-web-framework-benchmark/4db507a22c964c9bc9774c5b31afdc199a0fe8b7/benchmark.png)
> Η δρομολόγηση τροφοδοτείται από το [muxie](https://github.com/kataras/muxie), το πιο ισχυρό και ταχύτερο λογισμικό βασισμένο σε trie αλγόριθμο που γράφτηκε σε Go.
</details>
## Υποστήριξη
Το Iris περιέχει εκτενείς και λεπτομερείς **[wiki](https://github.com/kataras/iris/wiki)** καθιστώντας το εύκολο στην εκμάθηση.
- To [HISTORY](HISTORY_GR.md#fr-11-january-2019--v1111) αρχείο είναι ο καλύτερος σας φίλος, περιέχει πληροφορίες σχετικά με τις τελευταίες λειτουργίες(features) και αλλαγές
- Μήπως τυχαίνει να βρήκατε κάποιο bug; Δημοσιεύστε το στα [github issues](https://github.com/kataras/iris/issues)
- Έχετε οποιεσδήποτε ερωτήσεις ή πρέπει να μιλήσετε με κάποιον έμπειρο για την επίλυση ενός προβλήματος σε πραγματικό χρόνο; Ελάτε μαζί μας στην [συνομιλία κοινότητας](https://chat.iris-go.com)
- Συμπληρώστε την αναφορά εμπειρίας χρήστη κάνοντας κλικ [εδώ](https://docs.google.com/forms/d/e/1FAIpQLSdCxZXPANg_xHWil4kVAdhmh7EBBHQZ_4_xSZVDL-oCC_z5pA/viewform?usp=sf_link)
- Σας αρέσει το Iris; Τιτιβίστε κάτι για αυτό! Άνθρωποι από ολόκληρο τον πλανήτη έχουνε μιλήσει για αυτό ακριβώς:
Για λεπτομερέστερη τεχνική τεκμηρίωση μπορείτε να κατευθυνθείτε προς τα [godocs](https://godoc.org/github.com/kataras/iris) μας. Και για εκτελέσιμο κώδικα μπορείτε πάντα να επισκέπτεστε τα [παραδείγματα](_examples/).
<a href="https://twitter.com/gelnior/status/769100480706379776">
<img src="https://comments.iris-go.com/comment27_mini.png" width="350px">
</a>
### Σας αρέσει να διαβάζετε ενώ ταξιδεύετε;
<a href="https://twitter.com/MeAlex07/status/822799954188075008">
<img src="https://comments.iris-go.com/comment28_mini.png" width="350px">
</a>
Μπορείτε να [ζητήσετε](https://bit.ly/iris-req-book) σήμερα την PDF έκδοση και την online πρόσβαση στο Ηλεκτρονικό μας **Βιβλίο(E-Book)** και να συμμετάσχετε στην ανάπτυξη του Iris.
<a href="https://twitter.com/_mgale/status/818591490305761280">
<img src="https://comments.iris-go.com/comment29_mini.png" width="350px">
</a>
<a href="https://twitter.com/VeayoX/status/813273328550973440">
<img src="https://comments.iris-go.com/comment30_mini.png" width="350px">
</a>
[![https://iris-go.com/images/iris-book-overview.png](https://iris-go.com/images/iris-book-overview.png)](https://bit.ly/iris-req-book)
<a href="https://twitter.com/pvsukale/status/745328224876408832">
<img src="https://comments.iris-go.com/comment31_mini.png" width="350px">
</a>
## Συνεισφορά
<a href="https://twitter.com/blainsmith/status/745338092211560453">
<img src="https://comments.iris-go.com/comment32_mini.png" width="350px">
</a>
Θα θέλαμε να δούμε τη συμβολή σας στο Iris Web Framework! Για περισσότερες πληροφορίες σχετικά με το πως μπορείτε να συμβάλετε, δείτε το [CONTRIBUTING.md](CONTRIBUTING.md) αρχείο.
<a href="https://twitter.com/tjbyte/status/758287014210867200">
<img src="https://comments.iris-go.com/comment33_mini.png" width="350px">
</a>
[Κατάλογος όλων των συνεισφορών](https://github.com/kataras/iris/graphs/contributors).
<a href="https://twitter.com/tangzero/status/751050577220698112">
<img src="https://comments.iris-go.com/comment34_mini.png" width="350px">
</a>
## Αδυναμίες Ασφάλειας
<a href="https://twitter.com/tjbyte/status/758287244947972096">
<img src="https://comments.iris-go.com/comment33_2_mini.png" width="350px">
</a>
Εάν εντοπίσετε κάποια αδυναμία ασφαλείας του Iris, στείλτε ένα μήνυμα ηλεκτρονικού ταχυδρομείου στο [iris-go@outlook.com](mailto:iris-go@outlook.com). Όλες οι τυχών αδυναμίες ασφαλείας θα αντιμετωπιστούν άμεσα.
<a href="https://twitter.com/ferarias/status/902468752364773376">
<img src="https://comments.iris-go.com/comment41.png" width="350px">
</a>
## Άδεια Χρήσης
<br/><br/>
Το όνομα "Iris" εμπνεύστηκε από την ελληνική μυθολογία, από την θεά Ίριδα.
Για περισσότερες πληροφορίες σχετικά με τη συμβολή στο Iris, διαβάστε το [CONTRIBUTING.md](CONTRIBUTING.md) αρχείο.
[Κατάλογος όλων των Συνεργατών](https://github.com/kataras/iris/graphs/contributors)
## Μάθηση
Πρώτα απ 'όλα, ο πιο σωστός τρόπος για να ξεκινήσετε με ένα web framework είναι να μάθετε τα βασικά της γλώσσας προγραμματισμού και των τυπικών της δυνατοτήτων `http`, αν η εφαρμογή σας είναι ένα πολύ απλό προσωπικό έργο χωρίς απαιτήσεις επιδόσεων και συντηρησιμότητας, ίσως να θέλετε να προχωρήσετε μόνο με τα τυπικά πακέτα, εαν οχι τότε ακολουθήστε τις παρακάτω οδηγίες:
- Πλοηγηθείτε μέσω των **100+1** **[παραδειγμάτων](_examples)** και μερικές [απλές εφαρμογές για αρχάριους](#iris-starter-kits) που δημιουργήσαμε για εσάς
- Διαβάστε τα [godocs](https://godoc.org/github.com/kataras/iris) για οποιαδήποτε λεπτομέρεια
- Ετοιμάστε ένα φλιτζάνι καφέ ή τσάι, ό,τι σας ευχαριστεί περισσότερο και διαβάστε κάποια [άρθρα](#articles) που βρήκαμε για εσάς
### Iris starter kits
<!-- table form
| Description | Link |
| -----------|-------------|
| Hasura hub starter project with a ready to deploy golang helloworld webapp with IRIS! | https://hasura.io/hub/project/hasura/hello-golang-iris |
| A basic web app built in Iris for Go |https://github.com/gauravtiwari/go_iris_app |
| A mini social-network created with the awesome Iris💖💖 | https://github.com/iris-contrib/Iris-Mini-Social-Network |
| Iris isomorphic react/hot reloadable/redux/css-modules starter kit | https://github.com/iris-contrib/iris-starter-kit |
| Demo project with react using typescript and Iris | https://github.com/ionutvilie/react-ts |
| Self-hosted Localization Management Platform built with Iris and Angular | https://github.com/iris-contrib/parrot |
| Iris + Docker and Kubernetes | https://github.com/iris-contrib/cloud-native-go |
| Quickstart for Iris with Nanobox | https://guides.nanobox.io/golang/iris/from-scratch |
-->
1. [snowlyg/IrisApiProject: Iris + gorm + jwt + sqlite3](https://github.com/snowlyg/IrisApiProject) **NEW-Chinese**
2. [yz124/superstar: Iris + xorm to implement the star library](https://github.com/yz124/superstar) **NEW-Chinese**
3. [jebzmos4/Iris-golang: A basic CRUD API in golang with Iris](https://github.com/jebzmos4/Iris-golang)
4. [gauravtiwari/go_iris_app: A basic web app built in Iris for Go](https://github.com/gauravtiwari/go_iris_app)
5. [A mini social-network created with the awesome Iris💖💖](https://github.com/iris-contrib/Iris-Mini-Social-Network)
6. [Iris isomorphic react/hot reloadable/redux/css-modules starter kit](https://github.com/iris-contrib/iris-starter-kit)
7. [ionutvilie/react-ts: Demo project with react using typescript and Iris](https://github.com/ionutvilie/react-ts)
8. [Self-hosted Localization Management Platform built with Iris and Angular](https://github.com/iris-contrib/parrot)
9. [Iris + Docker and Kubernetes](https://github.com/iris-contrib/cloud-native-go)
10. [nanobox.io: Quickstart for Iris with Nanobox](https://guides.nanobox.io/golang/iris/from-scratch)
11. [hasura.io: A Hasura starter project with a ready to deploy Golang hello-world web app with IRIS](https://hasura.io/hub/project/hasura/hello-golang-iris)
> Έχετε χτίσει κάτι παρόμοιο; [Ενημέρωσέ μας](https://github.com/kataras/iris/pulls)!
### Middleware
Το Iris έχει μια μεγάλη συλλογή Handlers[[1]](middleware/)[[2]](https://github.com/iris-contrib/middleware) που μπορείτε να χρησιμοποιήσετε μέσα στις εφαρμογές σας. Ωστόσο, δεν περιορίζεστε σε αυτά - είστε ελεύθεροι να χρησιμοποιήσετε οποιοδήποτε μεσαίο λογισμικό τρίτου μέρους που είναι συμβατό με το [net/http](https://golang.org/pkg/net/http/) πακέτο, [_examples/convert-handlers](_examples/convert-handlers) θα σας δείξουν τον δρόμο.
Το Iris, σε αντίθεση με τα άλλα, είναι 100% συμβατό με τα πρότυπα και γι 'αυτό η πλειοψηφία των μεγάλων εταιρειών που προσαρμόζονται στην Go, όπως ένα πολύ γνωστό τηλεοπτικό δίκτυο των ΗΠΑ, εμπιστεύονται το Iris, και αυτό γιατί είναι πάντα ενημερωμένο και ευθυγραμμισμένο με το πακέτο `net/http` το οποίο εκσυγχρονίζεται από τους συγγραφέες(authors) της Go σε κάθε νέα έκδοση της, για πάντα.
### Articles
* [CRUD REST API in Iris (a framework for golang)](https://medium.com/@jebzmos4/crud-rest-api-in-iris-a-framework-for-golang-a5d33652401e)
* [A Todo MVC Application using Iris and Vue.js](https://hackernoon.com/a-todo-mvc-application-using-iris-and-vue-js-5019ff870064)
* [A Hasura starter project with a ready to deploy Golang hello-world web app with IRIS](bit.ly/2lmKaAZ)
* [Top 6 web frameworks for Go as of 2017](https://blog.usejournal.com/top-6-web-frameworks-for-go-as-of-2017-23270e059c4b)
* [Iris Go Framework + MongoDB](https://medium.com/go-language/iris-go-framework-mongodb-552e349eab9c)
* [How to build a file upload form using DropzoneJS and Go](https://hackernoon.com/how-to-build-a-file-upload-form-using-dropzonejs-and-go-8fb9f258a991)
* [How to display existing files on server using DropzoneJS and Go](https://hackernoon.com/how-to-display-existing-files-on-server-using-dropzonejs-and-go-53e24b57ba19)
* [Iris, a modular web framework](https://medium.com/@corebreaker/iris-web-cd684b4685c7)
* [Go vs .NET Core in terms of HTTP performance](https://medium.com/@kataras/go-vs-net-core-in-terms-of-http-performance-7535a61b67b8)
* [Iris Go vs .NET Core Kestrel in terms of HTTP performance](https://hackernoon.com/iris-go-vs-net-core-kestrel-in-terms-of-http-performance-806195dc93d5)
* [How to Turn an Android Device into a Web Server](https://twitter.com/ThePracticalDev/status/892022594031017988)
* [Deploying a Iris Golang app in hasura](https://medium.com/@HasuraHQ/deploy-an-iris-golang-app-with-backend-apis-in-minutes-25a559bf530b)
* [A URL Shortener Service using Go, Iris and Bolt](https://medium.com/@kataras/a-url-shortener-service-using-go-iris-and-bolt-4182f0b00ae7)
### Εκμάθηση μέσω video
* [Daily Coding - Web Framework Golang: Iris Framework]( https://www.youtube.com/watch?v=BmOLFQ29J3s) από WarnabiruTV, πηγή: youtube, κόστος: **ΔΩΡΕΑΝ**
* [Tutorial Golang MVC dengan Iris Framework & Mongo DB](https://www.youtube.com/watch?v=uXiNYhJqh2I&list=PLMrwI6jIZn-1tzskocnh1pptKhVmWdcbS) (19 videos ως τωρα) από Musobar Media, πηγή: youtube, κόστος: **ΔΩΡΕΑΝ**
* [Go/Golang 27 - Iris framework : Routage de base](https://www.youtube.com/watch?v=rQxRoN6ub78) από stephgdesign, πηγή: youtube, κόστος: **ΔΩΡΕΑΝ**
* [Go/Golang 28 - Iris framework : Templating](https://www.youtube.com/watch?v=nOKYV073S2Y) από stephgdesignn, πηγή: youtube, κόστος: **ΔΩΡΕΑΝ**
* [Go/Golang 29 - Iris framework : Paramètres](https://www.youtube.com/watch?v=K2FsprfXs1E) από stephgdesign, πηγή: youtube, κόστος: **ΔΩΡΕΑΝ**
* [Go/Golang 30 - Iris framework : Les middelwares](https://www.youtube.com/watch?v=BLPy1So6bhE) από stephgdesign, πηγή: youtube, κόστος: **ΔΩΡΕΑΝ**
* [Go/Golang 31 - Iris framework : Les sessions](https://www.youtube.com/watch?v=RnBwUrwgEZ8) από stephgdesign, πηγή: youtube, κόστος: **ΔΩΡΕΑΝ**
### Προσληφθείτε
Υπάρχουν πολλές νεοσύστατες εταιρείες που αναζητούν Go web developers με εμπειρία Iris ως απαίτηση, ψάχνουμε καθημερινά και δημοσιεύουμε αυτές τις πληροφορίες μέσω της [σελίδας μας στο facebook](https://www.facebook.com/iris.framework), κάντε like για να λαμβάνετε ειδοποιήσεις, έχουμε ήδη δημοσιεύσει ορισμένες από αυτές(τις θέσεις εργασίας).
## License
Το Iris διαθέτει άδεια βάσει του [3-Clause BSD License](LICENSE). Το Iris είναι 100% δωρεάν και ανοιχτού κώδικα λογισμικό.
Για τυχόν ερωτήσεις σχετικά με την άδεια παρακαλώ στείλτε [e-mail](mailto:kataras2006@hotmail.com?subject=Iris%20License).
Το Iris Web Framework είναι δωρεάν λογισμικό ανοιχτού λογισμικού με άδεια χρήσης [3-Clause BSD](LICENSE).

View File

@ -1,237 +0,0 @@
# Iris Web Framework <a href="README.md"> <img width="20px" src="https://iris-go.com/images/flag-unitedkingdom.svg?v=10" /> </a> <a href="README_ZH.md"> <img width="20px" src="https://iris-go.com/images/flag-china.svg?v=10" /> </a> <a href="README_RU.md"><img width="20px" src="https://iris-go.com/images/flag-russia.svg?v=10" /></a> <a href="README_GR.md"><img width="20px" src="https://iris-go.com/images/flag-greece.svg?v=10" /></a> <a href="README_PT_BR.md"><img width="20px" src="https://iris-go.com/images/flag-pt-br.svg?v=10" /></a> <a href="README_JPN.md"><img width="20px" src="https://iris-go.com/images/flag-japan.svg?v=10" /></a>
<a href="https://iris-go.com"> <img align="right" width="169px" src="https://iris-go.com/images/icon.svg?v=a" title="logo created by @merry.dii" /> </a>
[![build status](https://img.shields.io/travis/kataras/iris/master.svg?style=flat-square)](https://travis-ci.org/kataras/iris)<!-- [![release](https://img.shields.io/github/release/kataras/iris.svg?style=flat-square)](https://github.com/kataras/iris/releases)--> [![report card](https://img.shields.io/badge/report%20card-a%2B-ff3333.svg?style=flat-square)](http://goreportcard.com/report/kataras/iris) [![vscode-iris](https://img.shields.io/badge/ext%20-vscode-0c77e3.svg?style=flat-square)](https://marketplace.visualstudio.com/items?itemName=kataras2006.iris)<!--[![github closed issues](https://img.shields.io/github/issues-closed-raw/kataras/iris.svg?style=flat-square)](https://github.com/kataras/iris/issues?q=is%3Aissue+is%3Aclosed)--> [![chat](https://img.shields.io/badge/community-%20chat-00BCD4.svg?style=flat-square)](https://kataras.rocket.chat/channel/iris) [![view examples](https://img.shields.io/badge/learn%20by-examples-0077b3.svg?style=flat-square)](https://github.com/kataras/iris/tree/master/_examples/routing) [![release](https://img.shields.io/badge/release%20-v11.1-0077b3.svg?style=flat-square)](https://github.com/kataras/iris/releases)
Iris adalah web framework yang cepat, sederhana namun berfitur lengkap dan sangat efisien untuk Go.
Iris menyediakan fondasi yang indah expresif dan mudah digunakan untuk website atau API anda selanjutnya.
Akhirnya, framework nyata yang setara dengan expressjs untuk Go Programming Language.
Pelajari apa yang [orang lain katakan tentang Iris](#support) dan [star](https://github.com/kataras/iris/stargazers) github repository ini untuk [mendapatkan informasi terbaru](https://facebook.com/iris.framework).
## Donatur
Terima kasih kepada seluruh donatur kami! 🙏 [Menjadi donatur](https://iris-go.com/donate)
<a href="https://iris-go.com/donate" target="_blank"><img src="https://iris-go.com/backers.svg?v=2"/></a>
```sh
$ cat example.go
```
```go
package main
import "github.com/kataras/iris"
func main() {
app := iris.New()
// Memuat semua template dari folder "./views"
// yang memiliki ekstensi ".html" dan menguraikannya
// menggunakan package standard `html/template`.
app.RegisterView(iris.HTML("./views", ".html"))
// Method: GET
// Resource: http://localhost:8080
app.Get("/", func(ctx iris.Context) {
// Bind: {{.message}} with "Hello world!"
ctx.ViewData("message", "Hello world!")
// Render template file: ./views/hello.html
ctx.View("hello.html")
})
// Method: GET
// Resource: http://localhost:8080/user/42
//
// Butuh menggunakan custom regexp sebagai gantinya?
// Mudah,
// cukup tandai tipe parameter menjadi 'string'
// yang akan menerima semua dan akan menggunakan
// fungsi macro `regexp`, Contoh:
// app.Get("/user/{id:string regexp(^[0-9]+$)}")
app.Get("/user/{id:long}", func(ctx iris.Context) {
userID, _ := ctx.Params().GetInt64("id")
ctx.Writef("User ID: %d", userID)
})
// Menyalakan server menggunakan network address.
app.Run(iris.Addr(":8080"))
}
```
> Pelajari lebih lanjut tentang tipe parameter di path dengan klik [disini](_examples/routing/dynamic-path/main.go#L31)
```html
<!-- file: ./views/hello.html -->
<html>
<head>
<title>Hello Page</title>
</head>
<body>
<h1>{{.message}}</h1>
</body>
</html>
```
```sh
$ go run example.go
Now listening on: http://localhost:8080
Application Started. Press CTRL+C to shut down.
_
```
## Instalasi
Satu - satunya persyaratan adalah [Go Programming Language](https://golang.org/dl/)
```sh
$ go get -u github.com/kataras/iris
```
Iris mengambil keuntungan dari fitur [vendor directory](https://docs.google.com/document/d/1Bz5-UB7g2uPBdOx-rw5t9MxJwkfpx90cqG9AFL0JAYo). Anda mendapatkan build yang benar - benar dapat direproduksi, karena metode ini menjaga terhadap penggantian nama dan penghapusan di upstream.
[![Iris vs .NET Core(C#) vs Node.js (Express)](https://iris-go.com/images/benchmark-new-gray.png)](_benchmarks/README_UNIX.md)
_Diperbarui pada: [Tuesday, 21 November 2017](_benchmarks/README_UNIX.md)_
<details>
<summary>Benchmarks dari sumber pihak ketiga terhadap rest web frameworks</summary>
![Perbandingan dengan framework lain](https://raw.githubusercontent.com/smallnest/go-web-framework-benchmark/4db507a22c964c9bc9774c5b31afdc199a0fe8b7/benchmark.png)
</details>
## Dukungan
- File [HISTORY](HISTORY_ID.md#fr-11-january-2019--v1111) adalah sahabat anda, file tersebut memiliki informasi terkait fitur dan perubahan terbaru
- Apakah anda menemukan bug? Laporkan itu melalui [github issues](https://github.com/kataras/iris/issues)
- Apakah anda memiliki pertanyaan atau butuh untuk bicara kepada seseorang yang sudah berpengalaman untuk menyelesaikan masalah secara langsung? Gabung bersama kami di [community chat](https://chat.iris-go.com)
- Lengkapi laporan user-experience berbasis formulir kami dengan tekan [disini](https://docs.google.com/forms/d/e/1FAIpQLSdCxZXPANg_xHWil4kVAdhmh7EBBHQZ_4_xSZVDL-oCC_z5pA/viewform?usp=sf_link)
- Apakah anda menyukai framework ini? Tweet sesuatu tentang ini! Orang - orang yang sudah berbicara:
<a href="https://twitter.com/gelnior/status/769100480706379776">
<img src="https://comments.iris-go.com/comment27_mini.png" width="350px">
</a>
<a href="https://twitter.com/MeAlex07/status/822799954188075008">
<img src="https://comments.iris-go.com/comment28_mini.png" width="350px">
</a>
<a href="https://twitter.com/_mgale/status/818591490305761280">
<img src="https://comments.iris-go.com/comment29_mini.png" width="350px">
</a>
<a href="https://twitter.com/VeayoX/status/813273328550973440">
<img src="https://comments.iris-go.com/comment30_mini.png" width="350px">
</a>
<a href="https://twitter.com/pvsukale/status/745328224876408832">
<img src="https://comments.iris-go.com/comment31_mini.png" width="350px">
</a>
<a href="https://twitter.com/blainsmith/status/745338092211560453">
<img src="https://comments.iris-go.com/comment32_mini.png" width="350px">
</a>
<a href="https://twitter.com/tjbyte/status/758287014210867200">
<img src="https://comments.iris-go.com/comment33_mini.png" width="350px">
</a>
<a href="https://twitter.com/tangzero/status/751050577220698112">
<img src="https://comments.iris-go.com/comment34_mini.png" width="350px">
</a>
<a href="https://twitter.com/tjbyte/status/758287244947972096">
<img src="https://comments.iris-go.com/comment33_2_mini.png" width="350px">
</a>
<a href="https://twitter.com/ferarias/status/902468752364773376">
<img src="https://comments.iris-go.com/comment41.png" width="350px">
</a>
<br/><br/>
Untuk informasi lebih lanjut mengenai kontribusi terhadap project Iris, mohon untuk mengecek file [CONTRIBUTING.md](CONTRIBUTING.md).
[Daftar seluruh Kontributor](https://github.com/kataras/iris/graphs/contributors)
## Belajar
Pertama - tama, cara yang paling tepat untuk memulai dengan web framework adalah dengan mempelajari dasar dari bahasa pemrograman dan kemampuan dasar `http`, apabila aplikasi web anda adalah proyek pribadi yang sangat sederhana tanpa kebutuhan kinerja dan pemeliharaan, anda dapat melanjutkan hanya dengan standard packages. Setelah itu, ikut petunjuknya:
- Kunjungi **100+1** **[contoh](_examples)** dan beberapa [iris starter kits](#iris-starter-kits) yang kami buat untuk anda
- Baca [godocs](https://godoc.org/github.com/kataras/iris) untuk penjelasan yang lebih detail
- Siapkan secangkir kopi atau teh, apapun yang paling menyenangkan anda, dan baca beberapa [artikel](#articles) yang kami temukan untuk anda
### Iris starter kits
<!-- table form
| Description | Link |
| -----------|-------------|
| Hasura hub starter project with a ready to deploy golang helloworld webapp with IRIS! | https://hasura.io/hub/project/hasura/hello-golang-iris |
| A basic web app built in Iris for Go |https://github.com/gauravtiwari/go_iris_app |
| A mini social-network created with the awesome Iris💖💖 | https://github.com/iris-contrib/Iris-Mini-Social-Network |
| Iris isomorphic react/hot reloadable/redux/css-modules starter kit | https://github.com/iris-contrib/iris-starter-kit |
| Demo project with react using typescript and Iris | https://github.com/ionutvilie/react-ts |
| Self-hosted Localization Management Platform built with Iris and Angular | https://github.com/iris-contrib/parrot |
| Iris + Docker and Kubernetes | https://github.com/iris-contrib/cloud-native-go |
| Quickstart for Iris with Nanobox | https://guides.nanobox.io/golang/iris/from-scratch |
-->
1. [snowlyg/IrisApiProject: Iris + gorm + jwt + sqlite3](https://github.com/snowlyg/IrisApiProject) **NEW-Chinese**
2. [yz124/superstar: Iris + xorm to implement the star library](https://github.com/yz124/superstar) **NEW-Chinese**
3. [jebzmos4/Iris-golang: A basic CRUD API in golang with Iris](https://github.com/jebzmos4/Iris-golang)
4. [gauravtiwari/go_iris_app: A basic web app built in Iris for Go](https://github.com/gauravtiwari/go_iris_app)
5. [A mini social-network created with the awesome Iris💖💖](https://github.com/iris-contrib/Iris-Mini-Social-Network)
6. [Iris isomorphic react/hot reloadable/redux/css-modules starter kit](https://github.com/iris-contrib/iris-starter-kit)
7. [ionutvilie/react-ts: Demo project with react using typescript and Iris](https://github.com/ionutvilie/react-ts)
8. [Self-hosted Localization Management Platform built with Iris and Angular](https://github.com/iris-contrib/parrot)
9. [Iris + Docker and Kubernetes](https://github.com/iris-contrib/cloud-native-go)
10. [nanobox.io: Quickstart for Iris with Nanobox](https://guides.nanobox.io/golang/iris/from-scratch)
11. [hasura.io: A Hasura starter project with a ready to deploy Golang hello-world web app with IRIS](https://hasura.io/hub/project/hasura/hello-golang-iris)
> Apakah anda membuat hal yang serupa? [Beritahu kami](https://github.com/kataras/iris/pulls)!
### Middleware
Iris memiliki koleksi handler yang hebat[[1]](middleware/)[[2]](https://github.com/iris-contrib/middleware) yang dapat anda gunakan berdampingan dengan aplikasi web anda. Namun, anda tidak terbatas oleh itu saja - anda bebas menggunakan third-party middleware yang compatible dengan package [net/http](https://golang.org/pkg/net/http/), [_examples/convert-handlers](_examples/convert-handlers) akan menunjukkan caranya.
Iris, tidak seperti yang lain, 100% compatible dengan standards dan maka dari itu mayoritas dari perusahaan besar yang mengadaptasi Go kepada alur kerja mereka, seperti Jaringan Telivisi yang sangat terkenal di US, mempercayai Iris; framework yang up-to-date dan ini akan selalu selaras dengan package std `net/http` yang dimodernisasi oleh Pencipta Go di setiap release dari Go Programming Language.
### Articles
* [CRUD REST API in Iris (a framework for golang)](https://medium.com/@jebzmos4/crud-rest-api-in-iris-a-framework-for-golang-a5d33652401e)
* [A Todo MVC Application using Iris and Vue.js](https://hackernoon.com/a-todo-mvc-application-using-iris-and-vue-js-5019ff870064)
* [A Hasura starter project with a ready to deploy Golang hello-world web app with IRIS](https://bit.ly/2lmKaAZ)
* [Top 6 web frameworks for Go as of 2017](https://blog.usejournal.com/top-6-web-frameworks-for-go-as-of-2017-23270e059c4b)
* [Iris Go Framework + MongoDB](https://medium.com/go-language/iris-go-framework-mongodb-552e349eab9c)
* [How to build a file upload form using DropzoneJS and Go](https://hackernoon.com/how-to-build-a-file-upload-form-using-dropzonejs-and-go-8fb9f258a991)
* [How to display existing files on server using DropzoneJS and Go](https://hackernoon.com/how-to-display-existing-files-on-server-using-dropzonejs-and-go-53e24b57ba19)
* [Iris, a modular web framework](https://medium.com/@corebreaker/iris-web-cd684b4685c7)
* [Go vs .NET Core in terms of HTTP performance](https://medium.com/@kataras/go-vs-net-core-in-terms-of-http-performance-7535a61b67b8)
* [Iris Go vs .NET Core Kestrel in terms of HTTP performance](https://hackernoon.com/iris-go-vs-net-core-kestrel-in-terms-of-http-performance-806195dc93d5)
* [How to Turn an Android Device into a Web Server](https://twitter.com/ThePracticalDev/status/892022594031017988)
* [Deploying a Iris Golang app in hasura](https://medium.com/@HasuraHQ/deploy-an-iris-golang-app-with-backend-apis-in-minutes-25a559bf530b)
* [A URL Shortener Service using Go, Iris and Bolt](https://medium.com/@kataras/a-url-shortener-service-using-go-iris-and-bolt-4182f0b00ae7)
### Video Courses
* [Daily Coding - Web Framework Golang: Iris Framework]( https://www.youtube.com/watch?v=BmOLFQ29J3s) by WarnabiruTV, sumber: youtube, biaya: **GRATIS**
* [Tutorial Golang MVC dengan Iris Framework & Mongo DB](https://www.youtube.com/watch?v=uXiNYhJqh2I&list=PLMrwI6jIZn-1tzskocnh1pptKhVmWdcbS) (19 parts so far) by Musobar Media, sumber: youtube, biaya: **GRATIS**
* [Go/Golang 27 - Iris framework : Routage de base](https://www.youtube.com/watch?v=rQxRoN6ub78) by stephgdesign, sumber: youtube, biaya: **GRATIS**
* [Go/Golang 28 - Iris framework : Templating](https://www.youtube.com/watch?v=nOKYV073S2Y) by stephgdesignn, sumber: youtube, biaya: **GRATIS**
* [Go/Golang 29 - Iris framework : Paramètres](https://www.youtube.com/watch?v=K2FsprfXs1E) by stephgdesign, sumber: youtube, biaya: **GRATIS**
* [Go/Golang 30 - Iris framework : Les middelwares](https://www.youtube.com/watch?v=BLPy1So6bhE) by stephgdesign, sumber: youtube, biaya: **GRATIS**
* [Go/Golang 31 - Iris framework : Les sessions](https://www.youtube.com/watch?v=RnBwUrwgEZ8) by stephgdesign, sumber: youtube, biaya: **GRATIS**
### Get hired
Ada beberapa perusahaan dan start-up yang mencari web developer Go yang memiliki pengalaman menggunakn Iris, kami mencarikan untuk anda setiap hari dan kami post informasi tersebut melalui [facebook page](https://www.facebook.com/iris.framework) kami, like page kami untuk mendapatkan notifikasi, kami sudah mempost beberapa dari mereka.
## License
Iris dilisensikan di bawah [3-Clause BSD License](LICENSE). Iris 100% gratis dan software open-source.
Apabila ada pertanyaan mengenai lisensi, anda dapat mengirimkan [e-mail](mailto:kataras2006@hotmail.com?subject=Iris%20License).

View File

@ -1,237 +0,0 @@
# Iris ウェブフレームワーク <a href="README.md"> <img width="20px" src="https://iris-go.com/images/flag-unitedkingdom.svg?v=10" /></a> <a href="README_ZH.md"> <img width="20px" src="https://iris-go.com/images/flag-china.svg?v=10" /></a> <a href="README_RU.md"><img width="20px" src="https://iris-go.com/images/flag-russia.svg?v=10" /></a> <a href="README_ID.md"> <img width="20px" src="https://iris-go.com/images/flag-indonesia.svg?v=10" /></a> <a href="README_GR.md"><img width="20px" src="https://iris-go.com/images/flag-greece.svg?v=10" /></a> <a href="README_PT_BR.md"><img width="20px" src="https://iris-go.com/images/flag-pt-br.svg?v=10" /></a>
<a href="https://iris-go.com"> <img align="right" width="169px" src="https://iris-go.com/images/icon.svg?v=a" title="logo created by @merry.dii" /> </a>
[![build status](https://img.shields.io/travis/kataras/iris/master.svg?style=flat-square)](https://travis-ci.org/kataras/iris)<!-- [![release](https://img.shields.io/github/release/kataras/iris.svg?style=flat-square)](https://github.com/kataras/iris/releases)--> [![report card](https://img.shields.io/badge/report%20card-a%2B-ff3333.svg?style=flat-square)](http://goreportcard.com/report/kataras/iris) [![vscode-iris](https://img.shields.io/badge/ext%20-vscode-0c77e3.svg?style=flat-square)](https://marketplace.visualstudio.com/items?itemName=kataras2006.iris)<!--[![github closed issues](https://img.shields.io/github/issues-closed-raw/kataras/iris.svg?style=flat-square)](https://github.com/kataras/iris/issues?q=is%3Aissue+is%3Aclosed)--> [![chat](https://img.shields.io/badge/community-%20chat-00BCD4.svg?style=flat-square)](https://kataras.rocket.chat/channel/iris) [![view examples](https://img.shields.io/badge/learn%20by-examples-0077b3.svg?style=flat-square)](https://github.com/kataras/iris/tree/master/_examples/routing) [![release](https://img.shields.io/badge/release%20-v11.1-0077b3.svg?style=flat-square)](https://github.com/kataras/iris/releases)
Irisはシンプルで高速、それにも関わらず充実した機能を有する効率的なGo言語のウェブフレームワークです。
Irisは表現力豊かなウェブサイトやAPIの基礎構造をいとも簡単に提供します。
Go言語におけるExpressjsと言っても過言ではないでしょう。
[皆様の声](#支援)をご覧ください。このレポジトリを[Star](https://github.com/kataras/iris/stargazers)し、[最新情報](https://facebook.com/iris.framework)を受け取りましょう。
## 支援者
支援者の方々、ありがとうございます! 🙏 [支援者になる](https://iris-go.com/donate)
<a href="https://iris-go.com/donate" target="_blank"><img src="https://iris-go.com/backers.svg?v=2"/></a>
```sh
$ cat example.go
```
```go
package main
import "github.com/kataras/iris"
func main() {
app := iris.New()
// Load all templates from the "./views" folder
// where extension is ".html" and parse them
// using the standard `html/template` package.
app.RegisterView(iris.HTML("./views", ".html"))
// Method: GET
// Resource: http://localhost:8080
app.Get("/", func(ctx iris.Context) {
// Bind: {{.message}} with "Hello world!"
ctx.ViewData("message", "Hello world!")
// Render template file: ./views/hello.html
ctx.View("hello.html")
})
// Method: GET
// Resource: http://localhost:8080/user/42
//
// Need to use a custom regexp instead?
// Easy,
// just mark the parameter's type to 'string'
// which accepts anything and make use of
// its `regexp` macro function, i.e:
// app.Get("/user/{id:string regexp(^[0-9]+$)}")
app.Get("/user/{id:long}", func(ctx iris.Context) {
userID, _ := ctx.Params().GetInt64("id")
ctx.Writef("User ID: %d", userID)
})
// Start the server using a network address.
app.Run(iris.Addr(":8080"))
}
```
> [here](_examples/routing/dynamic-path/main.go#L31)をクリックしてパスパラメータについて学ぶ
```html
<!-- file: ./views/hello.html -->
<html>
<head>
<title>Hello Page</title>
</head>
<body>
<h1>{{.message}}</h1>
</body>
</html>
```
```sh
$ go run example.go
Now listening on: http://localhost:8080
Application Started. Press CTRL+C to shut down.
_
```
## インストール
[Go Programming Language](https://golang.org/dl/)をインストールしていることが唯一の前提条件です。
```sh
$ go get -u github.com/kataras/iris
```
Irisは[vendor directory](https://docs.google.com/document/d/1Bz5-UB7g2uPBdOx-rw5t9MxJwkfpx90cqG9AFL0JAYo)機能の利点を活かしています。これが上流レポジトリの変更や削除を防ぐため、再現可能なビルドを実現します。
[![Iris vs .NET Core(C#) vs Node.js (Express)](https://iris-go.com/images/benchmark-new-gray.png)](_benchmarks/README_UNIX.md)
_Updated at: [Tuesday, 21 November 2017](_benchmarks/README_UNIX.md)_
<details>
<summary>他のウェブフレームワークとの比較</summary>
![Comparison with other frameworks](https://raw.githubusercontent.com/smallnest/go-web-framework-benchmark/4db507a22c964c9bc9774c5b31afdc199a0fe8b7/benchmark.png)
</details>
## 支援
- [HISTORY](HISTORY.md#fr-11-january-2019--v1111)ファイルはあなたの友人です。このファイルには、機能に関する最新の情報や変更点が記載されています。
- バグを発見しましたか?[github issues](https://github.com/kataras/iris/issues)に投稿をお願い致します。
- 質問がありますか?または問題を即時に解決するため、熟練者に相談する必要がありますか?[community chat](https://chat.iris-go.com)に参加しましょう。
- [here](https://docs.google.com/forms/d/e/1FAIpQLSdCxZXPANg_xHWil4kVAdhmh7EBBHQZ_4_xSZVDL-oCC_z5pA/viewform?usp=sf_link)をクリックしてユーザーとしての体験を報告しましょう。
- フレームワークを愛していますか?それならばツイートしましょう!他の人はこのようにツイートしています:
<a href="https://twitter.com/gelnior/status/769100480706379776">
<img src="https://comments.iris-go.com/comment27_mini.png" width="350px">
</a>
<a href="https://twitter.com/MeAlex07/status/822799954188075008">
<img src="https://comments.iris-go.com/comment28_mini.png" width="350px">
</a>
<a href="https://twitter.com/_mgale/status/818591490305761280">
<img src="https://comments.iris-go.com/comment29_mini.png" width="350px">
</a>
<a href="https://twitter.com/VeayoX/status/813273328550973440">
<img src="https://comments.iris-go.com/comment30_mini.png" width="350px">
</a>
<a href="https://twitter.com/pvsukale/status/745328224876408832">
<img src="https://comments.iris-go.com/comment31_mini.png" width="350px">
</a>
<a href="https://twitter.com/blainsmith/status/745338092211560453">
<img src="https://comments.iris-go.com/comment32_mini.png" width="350px">
</a>
<a href="https://twitter.com/tjbyte/status/758287014210867200">
<img src="https://comments.iris-go.com/comment33_mini.png" width="350px">
</a>
<a href="https://twitter.com/tangzero/status/751050577220698112">
<img src="https://comments.iris-go.com/comment34_mini.png" width="350px">
</a>
<a href="https://twitter.com/tjbyte/status/758287244947972096">
<img src="https://comments.iris-go.com/comment33_2_mini.png" width="350px">
</a>
<a href="https://twitter.com/ferarias/status/902468752364773376">
<img src="https://comments.iris-go.com/comment41.png" width="350px">
</a>
<br/><br/>
Irisプロジェクトに貢献して頂ける方は、[CONTRIBUTING.md](CONTRIBUTING.md) をお読みください.
[全貢献者リスト](https://github.com/kataras/iris/graphs/contributors)
## 学習する
ウェブフレームワークで開発を行う時には、まず言語の基本を学ぶこと、標準的なhttpで何ができるのか知ることが重要です。あなたのアプリケーションが個人的なもので、とてもシンプル、パフォーマンスとメンテナンス性にそこまで拘らない場合、標準パッケージでの開発が推奨されます。以下のガイドラインを参照してください。
- **100+1** **[examples](_examples)** や[Irisスターターキット](#Irisスターターキット)を学習する
- より詳しく知るために[godocs](https://godoc.org/github.com/kataras/iris)を読む
- 一息ついて、私たちが発見した[記事](#記事)を読む
### Irisスターターキット
<!-- table form
| Description | Link |
| -----------|-------------|
| Hasura hub starter project with a ready to deploy golang helloworld webapp with IRIS! | https://hasura.io/hub/project/hasura/hello-golang-iris |
| A basic web app built in Iris for Go |https://github.com/gauravtiwari/go_iris_app |
| A mini social-network created with the awesome Iris💖💖 | https://github.com/iris-contrib/Iris-Mini-Social-Network |
| Iris isomorphic react/hot reloadable/redux/css-modules starter kit | https://github.com/iris-contrib/iris-starter-kit |
| Demo project with react using typescript and Iris | https://github.com/ionutvilie/react-ts |
| Self-hosted Localization Management Platform built with Iris and Angular | https://github.com/iris-contrib/parrot |
| Iris + Docker and Kubernetes | https://github.com/iris-contrib/cloud-native-go |
| Quickstart for Iris with Nanobox | https://guides.nanobox.io/golang/iris/from-scratch |
-->
1. [snowlyg/IrisApiProject: Iris + gorm + jwt + sqlite3](https://github.com/snowlyg/IrisApiProject) **NEW-Chinese**
2. [yz124/superstar: Iris + xorm to implement the star library](https://github.com/yz124/superstar) **NEW-Chinese**
3. [jebzmos4/Iris-golang: A basic CRUD API in golang with Iris](https://github.com/jebzmos4/Iris-golang)
4. [gauravtiwari/go_iris_app: A basic web app built in Iris for Go](https://github.com/gauravtiwari/go_iris_app)
5. [A mini social-network created with the awesome Iris💖💖](https://github.com/iris-contrib/Iris-Mini-Social-Network)
6. [Iris isomorphic react/hot reloadable/redux/css-modules starter kit](https://github.com/iris-contrib/iris-starter-kit)
7. [ionutvilie/react-ts: Demo project with react using typescript and Iris](https://github.com/ionutvilie/react-ts)
8. [Self-hosted Localization Management Platform built with Iris and Angular](https://github.com/iris-contrib/parrot)
9. [Iris + Docker and Kubernetes](https://github.com/iris-contrib/cloud-native-go)
10. [nanobox.io: Quickstart for Iris with Nanobox](https://guides.nanobox.io/golang/iris/from-scratch)
11. [hasura.io: A Hasura starter project with a ready to deploy Golang hello-world web app with IRIS](https://hasura.io/hub/project/hasura/hello-golang-iris)
> 似たようなものを開発しましたか? [私たちにも教えてください!](https://github.com/kataras/iris/pulls)
### ミドルウェア
Irisはあなたのウェブアプリケーションにご使用いただけるハンドラー[[1]](middleware/)[[2]](https://github.com/iris-contrib/middleware)を多く有しています。さらに、[net/http](https://golang.org/pkg/net/http/)と互換性のある外部のミドルウェアもご使用いただけます。[examples/convert-handlers](_examples/convert-handlers)を参照してください。
Irisは他のフレームワークと異なり、標準パッケージと互換性があります。故に、米国の有名なテレビ局を含め、大企業のの大半がGoをワークフローに取り入れています。Irisは常にGo言語の最新版リリースに対応し、Goの作成者によって開発されている標準的な`net/http`パッケージに沿っています。
### 記事
* [CRUD REST API in Iris (a framework for golang)](https://medium.com/@jebzmos4/crud-rest-api-in-iris-a-framework-for-golang-a5d33652401e)
* [A Todo MVC Application using Iris and Vue.js](https://hackernoon.com/a-todo-mvc-application-using-iris-and-vue-js-5019ff870064)
* [A Hasura starter project with a ready to deploy Golang hello-world web app with IRIS](https://bit.ly/2lmKaAZ)
* [Top 6 web frameworks for Go as of 2017](https://blog.usejournal.com/top-6-web-frameworks-for-go-as-of-2017-23270e059c4b)
* [Iris Go Framework + MongoDB](https://medium.com/go-language/iris-go-framework-mongodb-552e349eab9c)
* [How to build a file upload form using DropzoneJS and Go](https://hackernoon.com/how-to-build-a-file-upload-form-using-dropzonejs-and-go-8fb9f258a991)
* [How to display existing files on server using DropzoneJS and Go](https://hackernoon.com/how-to-display-existing-files-on-server-using-dropzonejs-and-go-53e24b57ba19)
* [Iris, a modular web framework](https://medium.com/@corebreaker/iris-web-cd684b4685c7)
* [Go vs .NET Core in terms of HTTP performance](https://medium.com/@kataras/go-vs-net-core-in-terms-of-http-performance-7535a61b67b8)
* [Iris Go vs .NET Core Kestrel in terms of HTTP performance](https://hackernoon.com/iris-go-vs-net-core-kestrel-in-terms-of-http-performance-806195dc93d5)
* [How to Turn an Android Device into a Web Server](https://twitter.com/ThePracticalDev/status/892022594031017988)
* [Deploying a Iris Golang app in hasura](https://medium.com/@HasuraHQ/deploy-an-iris-golang-app-with-backend-apis-in-minutes-25a559bf530b)
* [A URL Shortener Service using Go, Iris and Bolt](https://medium.com/@kataras/a-url-shortener-service-using-go-iris-and-bolt-4182f0b00ae7)
### 動画
* [Daily Coding - Web Framework Golang: Iris Framework]( https://www.youtube.com/watch?v=BmOLFQ29J3s) by WarnabiruTV, source: youtube, cost: **FREE**
* [Tutorial Golang MVC dengan Iris Framework & Mongo DB](https://www.youtube.com/watch?v=uXiNYhJqh2I&list=PLMrwI6jIZn-1tzskocnh1pptKhVmWdcbS) (19 parts so far) by Musobar Media, source: youtube, cost: **FREE**
* [Go/Golang 27 - Iris framework : Routage de base](https://www.youtube.com/watch?v=rQxRoN6ub78) by stephgdesign, source: youtube, cost: **FREE**
* [Go/Golang 28 - Iris framework : Templating](https://www.youtube.com/watch?v=nOKYV073S2Y) by stephgdesignn, source: youtube, cost: **FREE**
* [Go/Golang 29 - Iris framework : Paramètres](https://www.youtube.com/watch?v=K2FsprfXs1E) by stephgdesign, source: youtube, cost: **FREE**
* [Go/Golang 30 - Iris framework : Les middelwares](https://www.youtube.com/watch?v=BLPy1So6bhE) by stephgdesign, source: youtube, cost: **FREE**
* [Go/Golang 31 - Iris framework : Les sessions](https://www.youtube.com/watch?v=RnBwUrwgEZ8) by stephgdesign, source: youtube, cost: **FREE**
### 雇用
多くの企業やスタートアップがIrisの使用経験を有するGo言語開発者を探しています。私たちは募集情報を毎日検索し、[facebook page](https://www.facebook.com/iris.framework)に投稿しています。既に投稿されている情報をご覧ください。Likeを押して通知を受け取りましょう。
## ライセンス
Iris[3-Clause BSD License](LICENSE)に基いています。Irisは完全無料のオープンソースソフトウェアです。
ライセンスに関するご質問は[e-mail](mailto:kataras2006@hotmail.com?subject=Iris%20License)までご連絡ください。

View File

@ -1,242 +0,0 @@
# Iris Web Framework <a href="README.md"> <img width="20px" src="https://iris-go.com/images/flag-unitedkingdom.svg?v=10" /></a> <a href="README_ZH.md"> <img width="20px" src="https://iris-go.com/images/flag-china.svg?v=10" /></a> <a href="README_RU.md"><img width="20px" src="https://iris-go.com/images/flag-russia.svg?v=10" /></a> <a href="README_ID.md"> <img width="20px" src="https://iris-go.com/images/flag-indonesia.svg?v=10" /></a> <a href="README_GR.md"><img width="20px" src="https://iris-go.com/images/flag-greece.svg?v=10" /></a> <a href="README_JPN.md"><img width="20px" src="https://iris-go.com/images/flag-japan.svg?v=10" /></a>
<a href="https://iris-go.com"> <img align="right" width="169px" src="https://iris-go.com/images/icon.svg?v=a" title="logo created by @merry.dii" /> </a>
[![build status](https://img.shields.io/travis/kataras/iris/master.svg?style=flat-square)](https://travis-ci.org/kataras/iris)<!-- [![release](https://img.shields.io/github/release/kataras/iris.svg?style=flat-square)](https://github.com/kataras/iris/releases)--> [![report card](https://img.shields.io/badge/report%20card-a%2B-ff3333.svg?style=flat-square)](http://goreportcard.com/report/kataras/iris) [![vscode-iris](https://img.shields.io/badge/ext%20-vscode-0c77e3.svg?style=flat-square)](https://marketplace.visualstudio.com/items?itemName=kataras2006.iris)<!--[![github closed issues](https://img.shields.io/github/issues-closed-raw/kataras/iris.svg?style=flat-square)](https://github.com/kataras/iris/issues?q=is%3Aissue+is%3Aclosed)--> [![chat](https://img.shields.io/badge/community-%20chat-00BCD4.svg?style=flat-square)](https://kataras.rocket.chat/channel/iris) [![view examples](https://img.shields.io/badge/learn%20by-examples-0077b3.svg?style=flat-square)](https://github.com/kataras/iris/tree/master/_examples/routing) [![release](https://img.shields.io/badge/release%20-v11.1-0077b3.svg?style=flat-square)](https://github.com/kataras/iris/releases)
Iris é um framework rápido, simples porém completo e muito eficiente para a linguagem Go.
Além disso, Iris proporciona uma base sólida que capricha na expressividade e facilidade de uso para seu próximo site ou API.
Por último, Iris é um framework equivalente ao expressjs no ecossistema da linguagem de programação Go.
Veja o que [as pessoas estão dizendo sobre o Iris](#support) e [deixe uma estrela](https://github.com/kataras/iris/stargazers) nesse repositório do github para se [manter atualizado](https://facebook.com/iris.framework).
## Apoiadores
Muito obrigado a todos que nos apoiam! 🙏 [Apoie a gente!](https://iris-go.com/donate)
<a href="https://iris-go.com/donate" target="_blank"><img src="https://iris-go.com/backers.svg?v=2"/></a>
```sh
$ cat example.go
```
```go
package main
import "github.com/kataras/iris"
func main() {
app := iris.New()
// Carrega todos os templates da pasta "./views"
// cuja extensão é ".html" e parseie-os utilizando
// a biblioteca `html/template`.
app.RegisterView(iris.HTML("./views", ".html"))
// Method: GET
// Resource: http://localhost:8080
app.Get("/", func(ctx iris.Context) {
// Associa {{.message}} a "Hello world!"
ctx.ViewData("message", "Hello world!")
// Renderiza o template: ./views/hello.html
ctx.View("hello.html")
})
// Method: GET
// Resource: http://localhost:8080/user/42
//
// Deseja utilizar uma expressão regular ?
// É fácil,
// é só marcar o type to parametro como 'string'
// e utilizar sua macro `regexp`, i.e:
// app.Get("/user/{id:string regexp(^[0-9]+$)}")
app.Get("/user/{id:long}", func(ctx iris.Context) {
userID, _ := ctx.Params().GetInt64("id")
ctx.Writef("User ID: %d", userID)
})
// Inicializa o servidor utilizando um endereço de rede.
app.Run(iris.Addr(":8080"))
}
```
> Aprenda mais sobre tipos dos parametros da URI clicando [aqui](_examples/routing/dynamic-path/main.go#L31)
```html
<!-- arquivo: ./views/hello.html -->
<html>
<head>
<title>Hello Page</title>
</head>
<body>
<h1>{{.message}}</h1>
</body>
</html>
```
```sh
$ go run example.go
Now listening on: http://localhost:8080
Application Started. Press CTRL+C to shut down.
_
```
## Instalação
O único pré requisito é a [Linguagem de Programação GO](https://golang.org/dl/)
```sh
$ go get -u github.com/kataras/iris
```
Iris lança mão da [pasta vendor](https://docs.google.com/document/d/1Bz5-UB7g2uPBdOx-rw5t9MxJwkfpx90cqG9AFL0JAYo). Dessa forma você conseguirá obter builds reprodutíveis já que esse método impede que nomes no branch upstream sejam renomeados ou deletados.
[![Iris vs .NET Core(C#) vs Node.js (Express)](https://iris-go.com/images/benchmark-new-gray.png)](_benchmarks/README_UNIX.md)
_Atualizado em : [Terça, 21 de Novembro de 2017](_benchmarks/README_UNIX.md)_
<details>
<summary>Benchmarks de fonte third-party acerca dos frameworks web</summary>
![Comparison with other frameworks](https://raw.githubusercontent.com/smallnest/go-web-framework-benchmark/4db507a22c964c9bc9774c5b31afdc199a0fe8b7/benchmark.png)
</details>
## Apoie
- [HISTORY](HISTORY.md#fr-11-january-2019--v1111) o arquivo HISTORY é o seu melhor amigo, ele contém informações sobre as últimas features e mudanças.
- Econtrou algum bug ? Poste-o nas [issues](https://github.com/kataras/iris/issues)
- Possui alguma dúvida ou gostaria de falar com alguém experiente para resolver seu problema em tempo real ? Junte-se ao [chat da nossa comunidade](https://chat.iris-go.com).
- Complete nosso formulário de experiência do usuário clicando [aqui](https://docs.google.com/forms/d/e/1FAIpQLSdCxZXPANg_xHWil4kVAdhmh7EBBHQZ_4_xSZVDL-oCC_z5pA/viewform?usp=sf_link)
- Gostou do framework ? Deixe um Tweet sobre ele! Veja o que os outros já disseram:
<a href="https://twitter.com/gelnior/status/769100480706379776">
<img src="https://comments.iris-go.com/comment27_mini.png" width="350px">
</a>
<a href="https://twitter.com/MeAlex07/status/822799954188075008">
<img src="https://comments.iris-go.com/comment28_mini.png" width="350px">
</a>
<a href="https://twitter.com/_mgale/status/818591490305761280">
<img src="https://comments.iris-go.com/comment29_mini.png" width="350px">
</a>
<a href="https://twitter.com/VeayoX/status/813273328550973440">
<img src="https://comments.iris-go.com/comment30_mini.png" width="350px">
</a>
<a href="https://twitter.com/pvsukale/status/745328224876408832">
<img src="https://comments.iris-go.com/comment31_mini.png" width="350px">
</a>
<a href="https://twitter.com/blainsmith/status/745338092211560453">
<img src="https://comments.iris-go.com/comment32_mini.png" width="350px">
</a>
<a href="https://twitter.com/tjbyte/status/758287014210867200">
<img src="https://comments.iris-go.com/comment33_mini.png" width="350px">
</a>
<a href="https://twitter.com/tangzero/status/751050577220698112">
<img src="https://comments.iris-go.com/comment34_mini.png" width="350px">
</a>
<a href="https://twitter.com/tjbyte/status/758287244947972096">
<img src="https://comments.iris-go.com/comment33_2_mini.png" width="350px">
</a>
<a href="https://twitter.com/ferarias/status/902468752364773376">
<img src="https://comments.iris-go.com/comment41.png" width="350px">
</a>
<br/><br/>
Para mais informações sobre como contribuir para o projeto Iris leia por favor o arquivo [CONTRIBUTING.md](CONTRIBUTING.md).
[Lista de todos os Contribuintes](https://github.com/kataras/iris/graphs/contributors)
## Aprenda
Primeiramente, a melhor maneira de começar a aprender um framework é
aprender os fundamentos da linguagem de programação em questão e
as funções principais da biblioteca `http`, se seu app é um projeto
pessoal muito simples que exija performance e manutenção contínua
é provável que você consiga seguir adiante apenas com a biblioteca
padrão. Feito isso, você pode seguir as seguintes diretrizes:
- Navegue por **100+1** **[exemplos](_examples)** e os [iris starter kits](#iris-starter-kits) que criamos para você
- Leia os [godocs](https://godoc.org/github.com/kataras/iris) para mais detalhes
- Prepare um chá ou cafezinho, ou o que lhe for mais conveniente, e leia alguns [artigos](#articles) que achamos para você
### Iris starter kits
<!-- table form
| Description | Link |
| -----------|-------------|
| Hasura hub starter project with a ready to deploy golang helloworld webapp with IRIS! | https://hasura.io/hub/project/hasura/hello-golang-iris |
| Web app básico utilizando o Iris |https://github.com/gauravtiwari/go_iris_app |
| Uma mini rede social criada com o incrível Iris💖💖 | https://github.com/iris-contrib/Iris-Mini-Social-Network |
| Iris isomorphic react/hot reloadable/redux/css-modules starter kit | https://github.com/iris-contrib/iris-starter-kit |
| Projeto demo usando react com typescript e Iris | https://github.com/ionutvilie/react-ts |
| Plataforma de Gerenciamento de Localização auto hospedada criada com Iris e Angular | https://github.com/iris-contrib/parrot |
| Iris + Docker e Kubernetes | https://github.com/iris-contrib/cloud-native-go |
| Quickstart do Iris com Nanobox | https://guides.nanobox.io/golang/iris/from-scratch |
-->
1. [snowlyg/IrisApiProject: Iris + gorm + jwt + sqlite3](https://github.com/snowlyg/IrisApiProject)
2. [yz124/superstar: Iris + xorm to implement the star library](https://github.com/yz124/superstar) **NEW-Chinese**
3. [jebzmos4/Iris-golang: A basic CRUD API in golang with Iris](https://github.com/jebzmos4/Iris-golang)
4. [gauravtiwari/go_iris_app: Web app básico utilizando o Iris](https://github.com/gauravtiwari/go_iris_app)
5. [Uma mini rede social criada com o incrível Iris💖💖](https://github.com/iris-contrib/Iris-Mini-Social-Network)
6. [Iris isomorphic react/hot reloadable/redux/css-modules starter kit](https://github.com/iris-contrib/iris-starter-kit)
7. [ionutvilie/react-ts: Projeto demo usando react com typescript e Iris](https://github.com/ionutvilie/react-ts)
8. [Plataforma de Gerenciamento de Localização auto hospedada criada com Iris e Angular](https://github.com/iris-contrib/parrot)
9. [Iris + Docker e Kubernetes](https://github.com/iris-contrib/cloud-native-go)
10. [nanobox.io: Quickstart do Iris com Nanobox](https://guides.nanobox.io/golang/iris/from-scratch)
11. [hasura.io: Um projeto Hasura para iniciantes pronto para o deply com um app Golang hello-world utilizando o IRIS](https://hasura.io/hub/project/hasura/hello-golang-iris)
> Voce criou algo parecido ? [Informe-nos](https://github.com/kataras/iris/pulls)!
### Middleware
Iris tem uma ótima coleção de handlers[[1]](middleware/)[[2]](https://github.com/iris-contrib/middleware) os quais você pode utilizar lado a lado com seus web apps. Entretanto, você não esta limitado a eles - você pode utilizar qualquer middleware de terceiros desde que seja compatível com a biblioteca [net/http](https://golang.org/pkg/net/http/), [_examples/convert-handlers](_examples/convert-handlers) é um exemplo que pode ser tomado como base para tal.
Iris, ao contrário dos demais, é 100% compatível com os padrões e esse é o motivo pelo qual a maioria das grandes empresas que inserem Go em seu fluxo operacional, tal qual a famosa US Television Network, usam e confiam no Iris; Ele é atualizado com frequencia e sempre estará alinhado com o padrão da biblioteca `net/http` que é periodicamente modernizada pelos autores da linguagem Go a cada novo release.
### Artigos
* [CRUD REST API in Iris (a framework for golang)](https://medium.com/@jebzmos4/crud-rest-api-in-iris-a-framework-for-golang-a5d33652401e)
* [Um aplicação Todo utilizando Iris e Vue.js](https://hackernoon.com/a-todo-mvc-application-using-iris-and-vue-js-5019ff870064)
* [Um projeto Hasura para iniciantes pronto para o deply com um app Golang hello-world utilizando o IRIS](https://bit.ly/2lmKaAZ)
* [Top 6 frameworks web do Go em 2017](https://blog.usejournal.com/top-6-web-frameworks-for-go-as-of-2017-23270e059c4b)
* [Framework Iris + MongoDB](https://medium.com/go-language/iris-go-framework-mongodb-552e349eab9c)
* [Como criar um formulário de upload de arquivos com DropzoneJS e Go](https://hackernoon.com/how-to-build-a-file-upload-form-using-dropzonejs-and-go-8fb9f258a991)
* [Como mostrar arquivos existentes no servidor utilizando DropzoneJS e Go](https://hackernoon.com/how-to-display-existing-files-on-server-using-dropzonejs-and-go-53e24b57ba19)
* [Iris,um web framework modular](https://medium.com/@corebreaker/iris-web-cd684b4685c7)
* [Go vs .NET Core em termos de performance HTTP](https://medium.com/@kataras/go-vs-net-core-in-terms-of-http-performance-7535a61b67b8)
* [Iris Go vs .NET Core Kestrel em termos de performance HTTP](https://hackernoon.com/iris-go-vs-net-core-kestrel-in-terms-of-http-performance-806195dc93d5)
* [Como transformar um aparelho Android em um servidor web](https://twitter.com/ThePracticalDev/status/892022594031017988)
* [Fazendo Deploy de um app Iris na hasura](https://medium.com/@HasuraHQ/deploy-an-iris-golang-app-with-backend-apis-in-minutes-25a559bf530b)
* [Um serviço encurtador de URL utilizando Go, Iris e Bolt](https://medium.com/@kataras/a-url-shortener-service-using-go-iris-and-bolt-4182f0b00ae7)
### Video Aulas
* [Daily Coding - Web Framework Golang: Iris Framework]( https://www.youtube.com/watch?v=BmOLFQ29J3s) por WarnabiruTV, fonte: youtube, custo: **GRATUITO**
* [Tutorial Golang MVC dengan Iris Framework & Mongo DB](https://www.youtube.com/watch?v=uXiNYhJqh2I&list=PLMrwI6jIZn-1tzskocnh1pptKhVmWdcbS) (19 ate o momento) por Musobar Media, fonte: youtube, custo: **GRATUITO**
* [Go/Golang 27 - Iris framework : Routage de base](https://www.youtube.com/watch?v=rQxRoN6ub78) por stephgdesign, fonte: youtube, custo: **GRATUITO**
* [Go/Golang 28 - Iris framework : Templating](https://www.youtube.com/watch?v=nOKYV073S2Y) por stephgdesignn, fonte: youtube, custo: **GRATUITO**
* [Go/Golang 29 - Iris framework : Paramètres](https://www.youtube.com/watch?v=K2FsprfXs1E) por stephgdesign, fonte: youtube, custo: **GRATUITO**
* [Go/Golang 30 - Iris framework : Les middelwares](https://www.youtube.com/watch?v=BLPy1So6bhE) por stephgdesign, fonte: youtube, custo: **GRATUITO**
* [Go/Golang 31 - Iris framework : Les sessions](https://www.youtube.com/watch?v=RnBwUrwgEZ8) por stephgdesign, fonte: youtube, custo: **GRATUITO**
### Seja contratado
Várias empresas e start-ups estão procurando por desenvolvedores web que sabem Go e possuam experiência com Iris como pré requisito, todos os dias estamos procurando informações sobre empregos e postando na nossa [página do facebook](https://www.facebook.com/iris.framework), de um like na página para ser notificado.
## Licença
Iris é licenciado sob a [Licença 3-Clause BSD](LICENSE). Iris é um software 100% gratuito e open-source.
Caso haja quaisquer dúvidas em relação a licença favor enviar um [e-mail](mailto:kataras2006@hotmail.com?subject=Iris%20License).

View File

@ -1,239 +0,0 @@
# Iris Web Framework <a href="README.md"> <img width="20px" src="https://iris-go.com/images/flag-unitedkingdom.svg?v=10" /></a> <a href="README_ZH.md"><img width="20px" src="https://iris-go.com/images/flag-china.svg?v=10" /></a> <a href="README_ID.md"> <img width="20px" src="https://iris-go.com/images/flag-indonesia.svg?v=10" /></a> <a href="README_GR.md"><img width="20px" src="https://iris-go.com/images/flag-greece.svg?v=10" /></a> <a href="README_PT_BR.md"><img width="20px" src="https://iris-go.com/images/flag-pt-br.svg?v=10" /></a> <a href="README_JPN.md"><img width="20px" src="https://iris-go.com/images/flag-japan.svg?v=10" /></a>
<a href="https://iris-go.com"> <img align="right" width="169px" src="https://iris-go.com/images/icon.svg?v=a" title="logo created by @merry.dii" /> </a>
[![build status](https://img.shields.io/travis/kataras/iris/master.svg?style=flat-square)](https://travis-ci.org/kataras/iris)<!-- [![release](https://img.shields.io/github/release/kataras/iris.svg?style=flat-square)](https://github.com/kataras/iris/releases)--> [![report card](https://img.shields.io/badge/report%20card-a%2B-ff3333.svg?style=flat-square)](http://goreportcard.com/report/kataras/iris) [![vscode-iris](https://img.shields.io/badge/ext%20-vscode-0c77e3.svg?style=flat-square)](https://marketplace.visualstudio.com/items?itemName=kataras2006.iris)<!--[![github closed issues](https://img.shields.io/github/issues-closed-raw/kataras/iris.svg?style=flat-square)](https://github.com/kataras/iris/issues?q=is%3Aissue+is%3Aclosed)--> [![chat](https://img.shields.io/badge/community-%20chat-00BCD4.svg?style=flat-square)](https://kataras.rocket.chat/channel/iris) [![view examples](https://img.shields.io/badge/learn%20by-examples-0077b3.svg?style=flat-square)](https://github.com/kataras/iris/tree/master/_examples/routing) [![release](https://img.shields.io/badge/release%20-v11.1-0077b3.svg?style=flat-square)](https://github.com/kataras/iris/releases)
Iris - это быстрая, простая, но полнофункциональная и очень эффективная веб-платформа для Go.
Iris предоставляет красиво выразительную и удобную основу для вашего следующего веб-сайта или API.
Наконец, настоящий эквивалент expressjs для языка программирования Go.
Узнайте, что [другие говорят об Iris](#support), и [запустите](https://github.com/kataras/iris/stargazers) этот github-хранилище, чтобы оставаться в курсе последних событий [актуальными](https://facebook.com/iris.framework).
## Сторонники
Спасибо всем, кто поддерживал нас! 🙏 [Поддержать нас](https://iris-go.com/donate)
<a href="https://iris-go.com/donate" target="_blank"><img src="https://iris-go.com/backers.svg?v=2"/></a>
```sh
$ cat example.go
```
```go
package main
import "github.com/kataras/iris"
func main() {
app := iris.New()
// Load all templates from the "./views" folder
// where extension is ".html" and parse them
// using the standard `html/template` package.
app.RegisterView(iris.HTML("./views", ".html"))
// Method: GET
// Resource: http://localhost:8080
app.Get("/", func(ctx iris.Context) {
// Bind: {{.message}} with "Hello world!"
ctx.ViewData("message", "Hello world!")
// Render template file: ./views/hello.html
ctx.View("hello.html")
})
// Method: GET
// Resource: http://localhost:8080/user/42
//
// Need to use a custom regexp instead?
// Easy,
// just mark the parameter's type to 'string'
// which accepts anything and make use of
// its `regexp` macro function, i.e:
// app.Get("/user/{id:string regexp(^[0-9]+$)}")
app.Get("/user/{id:long}", func(ctx iris.Context) {
userID, _ := ctx.Params().GetInt64("id")
ctx.Writef("User ID: %d", userID)
})
// Start the server using a network address.
app.Run(iris.Addr(":8080"))
}
```
> Чтобы узнать подробнее о типах пути параметров нажмите [здесь](_examples/routing/dynamic-path/main.go#L31)
```html
<!-- file: ./views/hello.html -->
<html>
<head>
<title>Hello Page</title>
</head>
<body>
<h1>{{.message}}</h1>
</body>
</html>
```
```sh
$ go run example.go
Now listening on: http://localhost:8080
Application Started. Press CTRL+C to shut down.
_
```
## Установка
Единственное требование [язык программирования Go.](https://golang.org/dl/)
```sh
$ go get -u github.com/kataras/iris
```
Iris использует преимущества функции [из каталога поставщика](https://docs.google.com/document/d/1Bz5-UB7g2uPBdOx-rw5t9MxJwkfpx90cqG9AFL0JAYo). Вы получаете действительно воспроизводимые конструкции, так как этот метод защищает от восходящего потока переименований и удалений.
[![Iris vs .NET Core(C#) vs Node.js (Express)](https://iris-go.com/images/benchmark-new-gray.png)](_benchmarks/README_UNIX.md)
_Обновлено: [Вторник, 21 ноября 2017 г.](_benchmarks/README_UNIX.md)_
<details>
<summary>Сравнительные тесты сторонних источников по остальным веб-фреймворкам</summary>
![Comparison with other frameworks](https://raw.githubusercontent.com/smallnest/go-web-framework-benchmark/4db507a22c964c9bc9774c5b31afdc199a0fe8b7/benchmark.png)
</details>
## Поддержка
- Файл [HISTORY](HISTORY.md#fr-11-january-2019--v1111) - ваш лучший друг, он содержит информацию о последних особенностях и всех изменениях
- Вы случайно обнаружили ошибку? Опубликуйте ее на [Github вопросы](https://github.com/kataras/iris/issues)
- У Вас есть какие-либо вопросы или Вам нужно поговорить с кем-то, кто бы смог решить Вашу проблему в режиме реального времени? Присоединяйтесь к нам в [чате сообщества](https://chat.iris-go.com)
- Заполните наш отчет о пользовательском опыте на основе формы, нажав [здесь](https://docs.google.com/forms/d/e/1FAIpQLSdCxZXPANg_xHWil4kVAdhmh7EBBHQZ_4_xSZVDL-oCC_z5pA/viewform?usp=sf_link)
- Вам нравится фреймворк? Поделись об этом в Twitter! Люди говорят:
<a href="https://twitter.com/gelnior/status/769100480706379776">
<img src="https://comments.iris-go.com/comment27_mini.png" width="350px">
</a>
<a href="https://twitter.com/MeAlex07/status/822799954188075008">
<img src="https://comments.iris-go.com/comment28_mini.png" width="350px">
</a>
<a href="https://twitter.com/_mgale/status/818591490305761280">
<img src="https://comments.iris-go.com/comment29_mini.png" width="350px">
</a>
<a href="https://twitter.com/VeayoX/status/813273328550973440">
<img src="https://comments.iris-go.com/comment30_mini.png" width="350px">
</a>
<a href="https://twitter.com/pvsukale/status/745328224876408832">
<img src="https://comments.iris-go.com/comment31_mini.png" width="350px">
</a>
<a href="https://twitter.com/blainsmith/status/745338092211560453">
<img src="https://comments.iris-go.com/comment32_mini.png" width="350px">
</a>
<a href="https://twitter.com/tjbyte/status/758287014210867200">
<img src="https://comments.iris-go.com/comment33_mini.png" width="350px">
</a>
<a href="https://twitter.com/tangzero/status/751050577220698112">
<img src="https://comments.iris-go.com/comment34_mini.png" width="350px">
</a>
<a href="https://twitter.com/tjbyte/status/758287244947972096">
<img src="https://comments.iris-go.com/comment33_2_mini.png" width="350px">
</a>
<a href="https://twitter.com/ferarias/status/902468752364773376">
<img src="https://comments.iris-go.com/comment41.png" width="350px">
</a>
<br/><br/>
Для получения дополнительной информации о внесении вклада в проект Iris, пожалуйста, проверьте файл [CONTRIBUTING.md](CONTRIBUTING.md).
[Список всех участников](https://github.com/kataras/iris/graphs/contributors)
## Учить
Прежде всего, самый правильный способ начать работу с веб-фрэймворк - изучить основы языка программирования и стандартные возможности `http`. Если Ваше веб-приложение представляет собой очень простой персональный проект без производительности и требований к техническому обслуживанию, тогда Вы возможно захотите развиваться просто со стандартным пакетом. После этого следуйте рекомендациям:
- Пройдитесь по **100+1** **[примерам](_examples)** и по некоторым [ стартовым Iris наборам](#iris-starter-kits), которые мы создали для вас
- Прочтите [godocs](https://godoc.org/github.com/kataras/iris) для любых подробностей
- Приготовьте чашечку кофе или чая, что вам больше нравится, и ознакомьтесь с некоторыми [статьями](#articles), которые мы нашли для вас
### Стартовые наборы IRIS:
<!-- table form
| Description | Link |
| -----------|-------------|
| Hasura hub starter project with a ready to deploy golang helloworld webapp with IRIS! | https://hasura.io/hub/project/hasura/hello-golang-iris |
| A basic web app built in Iris for Go |https://github.com/gauravtiwari/go_iris_app |
| A mini social-network created with the awesome Iris💖💖 | https://github.com/iris-contrib/Iris-Mini-Social-Network |
| Iris isomorphic react/hot reloadable/redux/css-modules starter kit | https://github.com/iris-contrib/iris-starter-kit |
| Demo project with react using typescript and Iris | https://github.com/ionutvilie/react-ts |
| Self-hosted Localization Management Platform built with Iris and Angular | https://github.com/iris-contrib/parrot |
| Iris + Docker and Kubernetes | https://github.com/iris-contrib/cloud-native-go |
| Quickstart for Iris with Nanobox | https://guides.nanobox.io/golang/iris/from-scratch |
-->
1. [snowlyg/IrisApiProject: Iris + gorm + jwt + sqlite3](https://github.com/snowlyg/IrisApiProject) **NEW-Chinese**
2. [yz124/superstar: Iris + xorm to implement the star library](https://github.com/yz124/superstar) **NEW-Chinese**
3. [jebzmos4/Iris-golang: A basic CRUD API in golang with Iris](https://github.com/jebzmos4/Iris-golang)
4. [gauravtiwari/go_iris_app: A basic web app built in Iris for Go](https://github.com/gauravtiwari/go_iris_app)
5. [A mini social-network created with the awesome Iris💖💖](https://github.com/iris-contrib/Iris-Mini-Social-Network)
6. [Iris isomorphic react/hot reloadable/redux/css-modules starter kit](https://github.com/iris-contrib/iris-starter-kit)
7. [ionutvilie/react-ts: Demo project with react using typescript and Iris](https://github.com/ionutvilie/react-ts)
8. [Self-hosted Localization Management Platform built with Iris and Angular](https://github.com/iris-contrib/parrot)
9. [Iris + Docker and Kubernetes](https://github.com/iris-contrib/cloud-native-go)
10. [nanobox.io: Quickstart for Iris with Nanobox](https://guides.nanobox.io/golang/iris/from-scratch)
11. [hasura.io: A Hasura starter project with a ready to deploy Golang hello-world web app with IRIS](https://hasura.io/hub/project/hasura/hello-golang-iris)
> Вы построили что-то подобное? Дайте нам [знать](https://github.com/kataras/iris/pulls)!
### Связующее программное обеспечение
У Iris есть отличный сбор обработчиков[[1]](middleware/)[[2]](https://github.com/iris-contrib/middleware) которые вы можете использовать бок о бок с вашими веб-приложениями. Однако вы не ограничены ими - вы можете использовать стороннее программное обеспечение, совместимое с [net/http](https://golang.org/pkg/net/http/) пакетом, [_examples/convert-handlers](_examples/convert-handlers) покажут вам путь.
Iris, в отличие от других, на 100% совместим со стандартами, и именно поэтому большинство крупных компаний, которые адаптируют Go к своему рабочему процессу, как и очень известная телевизионная сеть США, доверяют Iris; это всегда актуально, и он будет приведен в соответствии с пакетом - `net/http`, который будет модернизирован Автором Go при каждом новом выпуске языка программирования Go навсегда.
### Статьи
* [CRUD REST API in Iris (a framework for golang)](https://medium.com/@jebzmos4/crud-rest-api-in-iris-a-framework-for-golang-a5d33652401e)
* [Приложение Todo MVC с использованием Iris и Vue.js](https://hackernoon.com/a-todo-mvc-application-using-iris-and-vue-js-5019ff870064)
* [Стартовый проект Hasura с готовностью применять веб-приложение Golang hello-world с IRIS](bit.ly/2lmKaAZ)
* [Топ-6 веб-фреймворков для Go на 2017 год
](https://blog.usejournal.com/top-6-web-frameworks-for-go-as-of-2017-23270e059c4b)
* [Iris Go Framework + MongoDB](https://medium.com/go-language/iris-go-framework-mongodb-552e349eab9c)
* [Как создать форму загрузки файла с помощью DropzoneJS и Go](https://hackernoon.com/how-to-build-a-file-upload-form-using-dropzonejs-and-go-8fb9f258a991)
* [Как отображать существующие файлы на сервере с помощью DropzoneJS и Go](https://hackernoon.com/how-to-display-existing-files-on-server-using-dropzonejs-and-go-53e24b57ba19)
* [ Iris, модульная структура сети](https://medium.com/@corebreaker/iris-web-cd684b4685c7)
* [ Go vs .NET Core с точки зрения производительности HTTP](https://medium.com/@kataras/go-vs-net-core-in-terms-of-http-performance-7535a61b67b8)
* [ Iris Go vs .NET Core Kestrel с точки зрения производительности HTTP
](https://hackernoon.com/iris-go-vs-net-core-kestrel-in-terms-of-http-performance-806195dc93d5)
* [Как превратить Android-устройство в веб-сервер](https://twitter.com/ThePracticalDev/status/892022594031017988)
* [Применение приложения Iris Golang на Hasura](https://medium.com/@HasuraHQ/deploy-an-iris-golang-app-with-backend-apis-in-minutes-25a559bf530b)
* [URL-адрес Shortener Service с помощью Go, Iris и Bolt](https://medium.com/@kataras/a-url-shortener-service-using-go-iris-and-bolt-4182f0b00ae7)
### Video Courses
* [Daily Coding - Web Framework Golang: Iris Framework]( https://www.youtube.com/watch?v=BmOLFQ29J3s) by WarnabiruTV, source: youtube, cost: **FREE**
* [Tutorial Golang MVC dengan Iris Framework & Mongo DB](https://www.youtube.com/watch?v=uXiNYhJqh2I&list=PLMrwI6jIZn-1tzskocnh1pptKhVmWdcbS) (19 parts so far) by Musobar Media, source: youtube, cost: **FREE**
* [Go/Golang 27 - Iris framework : Routage de base](https://www.youtube.com/watch?v=rQxRoN6ub78) by stephgdesign, source: youtube, cost: **FREE**
* [Go/Golang 28 - Iris framework : Templating](https://www.youtube.com/watch?v=nOKYV073S2Y) by stephgdesignn, source: youtube, cost: **FREE**
* [Go/Golang 29 - Iris framework : Paramètres](https://www.youtube.com/watch?v=K2FsprfXs1E) by stephgdesign, source: youtube, cost: **FREE**
* [Go/Golang 30 - Iris framework : Les middelwares](https://www.youtube.com/watch?v=BLPy1So6bhE) by stephgdesign, source: youtube, cost: **FREE**
* [Go/Golang 31 - Iris framework : Les sessions](https://www.youtube.com/watch?v=RnBwUrwgEZ8) by stephgdesign, source: youtube, cost: **FREE**
### Получить работу
Есть много компаний и стартапов, находящиеся в поисках Go веб-разработчиков с опытом работы с Iris как в качестве требования, которые мы подыскиваем для вас каждый день. Мы публикуем эту информацию на нашей [странице в Facebook](https://www.facebook.com/iris.framework). Ставьте Like, чтобы получите уведомления. Мы уже опубликовали некоторые из них.
## Лицензия
Iris лицензируется в соответствии с [BSD 3-Clause лицензией](LICENSE). Iris - это бесплатное программное обеспечение с открытым исходным кодом на 100%.
По любым вопросам, касающимся лицензии, отправьте письмо на [почту](mailto:kataras2006@hotmail.com?subject=Iris%20License).

View File

@ -1,230 +0,0 @@
# Iris Web Framework <a href="README.md"> <img width="20px" src="https://iris-go.com/images/flag-unitedkingdom.svg?v=10" /></a> <a href="README_RU.md"><img width="20px" src="https://iris-go.com/images/flag-russia.svg?v=10" /></a> <a href="README_ID.md"> <img width="20px" src="https://iris-go.com/images/flag-indonesia.svg?v=10" /></a> <a href="README_GR.md"><img width="20px" src="https://iris-go.com/images/flag-greece.svg?v=10" /></a> <a href="README_PT_BR.md"><img width="20px" src="https://iris-go.com/images/flag-pt-br.svg?v=10" /></a> <a href="README_JPN.md"><img width="20px" src="https://iris-go.com/images/flag-japan.svg?v=10" /></a>
<a href="https://iris-go.com"> <img align="right" width="169px" src="https://iris-go.com/images/icon.svg?v=a" title="logo created by @merry.dii" /> </a>
[![build status](https://img.shields.io/travis/kataras/iris/master.svg?style=flat-square)](https://travis-ci.org/kataras/iris)<!-- [![release](https://img.shields.io/github/release/kataras/iris.svg?style=flat-square)](https://github.com/kataras/iris/releases)--> [![report card](https://img.shields.io/badge/report%20card-a%2B-ff3333.svg?style=flat-square)](http://goreportcard.com/report/kataras/iris) [![vscode-iris](https://img.shields.io/badge/ext%20-vscode-0c77e3.svg?style=flat-square)](https://marketplace.visualstudio.com/items?itemName=kataras2006.iris)<!--[![github closed issues](https://img.shields.io/github/issues-closed-raw/kataras/iris.svg?style=flat-square)](https://github.com/kataras/iris/issues?q=is%3Aissue+is%3Aclosed)--> [![chat](https://img.shields.io/badge/community-%20chat-00BCD4.svg?style=flat-square)](https://kataras.rocket.chat/channel/iris) [![view examples](https://img.shields.io/badge/learn%20by-examples-0077b3.svg?style=flat-square)](https://github.com/kataras/iris/tree/master/_examples/routing) [![release](https://img.shields.io/badge/release%20-v11.1-0077b3.svg?style=flat-square)](https://github.com/kataras/iris/releases)
Iris 是一款超快、简洁高效的 Go 语言 Web开发框架。
Iris 功能强大、使用简单它将会是你下一个网站、API 服务或者分布式应用基础框架的不二之选。
总之,是一款与 express.js 旗鼓相当的 Go 语言框架。
看看[别人是如何评价 Iris](#support),同时欢迎各位点亮 Iris [Star](https://github.com/kataras/iris/stargazers),或者关注 [Iris facebook 主页](https://facebook.com/iris.framework)。
## 支持者
感谢所有的支持者! 🙏 [支持我们](https://iris-go.com/donate)
<a href="https://iris-go.com/donate" target="_blank"><img src="https://iris-go.com/backers.svg?v=2"/></a>
```sh
$ cat example.go
```
```go
package main
import "github.com/kataras/iris"
func main() {
app := iris.New()
// 从 "./views" 目录加载HTML模板
// 模板解析 html 后缀文件
   // 此方式使用 `html/template` 标准包 (Iris 的模板引擎)
app.RegisterView(iris.HTML("./views", ".html"))
// 方法GET
// 路径http://localhost:8080
app.Get("/", func(ctx iris.Context) {
       // {{.message}} 和 "Hello world!" 字符串变量绑定
ctx.ViewData("message", "Hello world!")
// 映射 HTML 模板文件路径 ./views/hello.html
ctx.View("hello.html")
})
//方法GET
//路径http://localhost:8080/user/42
//
   // 使用正则表达式必须设置参数类型为 string
   // app.Get("/user/{id:string regexp(^[0-9]+$)}")
app.Get("/user/{id:long}", func(ctx iris.Context) {
userID, _ := ctx.Params().GetInt64("id")
ctx.Writef("User ID: %d", userID)
})
// 绑定端口并启动服务.
app.Run(iris.Addr(":8080"))
}
```
> 想要了解更多关于路径参数配置,戳[这里](_examples/routing/dynamic-path/main.go#L31)。
```html
<!-- file: ./views/hello.html -->
<html>
<head>
<title>Hello Page</title>
</head>
<body>
<h1>{{.message}}</h1>
</body>
</html>
```
```sh
$ go run example.go
Now listening on: http://localhost:8080
Application Started. Press CTRL+C to shut down.
_
```
## 安装
请确保安装 [Go Programming Language](https://golang.org/dl/)
```sh
$ go get -u github.com/kataras/iris
```
Iris 使用 [vendor](https://docs.google.com/document/d/1Bz5-UB7g2uPBdOx-rw5t9MxJwkfpx90cqG9AFL0JAYo) 包依赖管理方式。vendor 包管理的方式可以有效处理包依赖更新问题
[![Iris vs .NET Core(C#) vs Node.js (Express)](https://iris-go.com/images/benchmark-new-gray.png)](_benchmarks/README_UNIX.md)
_更新于: [2017年11月21日星期二](_benchmarks/README_UNIX.md)_
<details>
<summary>来自第三方的其他网络框架的基准测试</summary>
![Comparison with other frameworks](https://raw.githubusercontent.com/smallnest/go-web-framework-benchmark/4db507a22c964c9bc9774c5b31afdc199a0fe8b7/benchmark.png)
</details>
## 支持
- [更新记录](HISTORY_ZH.md#fr-11-january-2019--v1111) 是您最好的朋友,它包含有关最新功能和更改的信息
- 你碰巧找到了一个错误? 请提交 [github issues](https://github.com/kataras/iris/issues)
- 您是否有任何疑问或需要与有经验的人士交谈以实时解决问题? [加入我们的聊天](https://chat.iris-go.com)
- [点击这里完成我们基于表单的用户体验报告](https://docs.google.com/forms/d/e/1FAIpQLSdCxZXPANg_xHWil4kVAdhmh7EBBHQZ_4_xSZVDL-oCC_z5pA/viewform?usp=sf_link)
- 你喜欢这个框架吗? Twitter 上关于 Iris 的评价:
<a href="https://twitter.com/gelnior/status/769100480706379776">
<img src="https://comments.iris-go.com/comment27_mini.png" width="350px">
</a>
<a href="https://twitter.com/MeAlex07/status/822799954188075008">
<img src="https://comments.iris-go.com/comment28_mini.png" width="350px">
</a>
<a href="https://twitter.com/_mgale/status/818591490305761280">
<img src="https://comments.iris-go.com/comment29_mini.png" width="350px">
</a>
<a href="https://twitter.com/VeayoX/status/813273328550973440">
<img src="https://comments.iris-go.com/comment30_mini.png" width="350px">
</a>
<a href="https://twitter.com/pvsukale/status/745328224876408832">
<img src="https://comments.iris-go.com/comment31_mini.png" width="350px">
</a>
<a href="https://twitter.com/blainsmith/status/745338092211560453">
<img src="https://comments.iris-go.com/comment32_mini.png" width="350px">
</a>
<a href="https://twitter.com/tjbyte/status/758287014210867200">
<img src="https://comments.iris-go.com/comment33_mini.png" width="350px">
</a>
<a href="https://twitter.com/tangzero/status/751050577220698112">
<img src="https://comments.iris-go.com/comment34_mini.png" width="350px">
</a>
<a href="https://twitter.com/tjbyte/status/758287244947972096">
<img src="https://comments.iris-go.com/comment33_2_mini.png" width="350px">
</a>
<a href="https://twitter.com/ferarias/status/902468752364773376">
<img src="https://comments.iris-go.com/comment41.png" width="350px">
</a>
[如何贡献代码](CONTRIBUTING.md)
[贡献者列表](https://github.com/kataras/iris/graphs/contributors)
## 学习
首先,从 Web 框架开始的最正确的方法是学习 Golang 标准库 [net/http](https://golang.org/pkg/net/http/ "net/http") 的基础知识,如果您的 web 应用程序是一个非常简单的个人项目,没有性能和可维护性要求,您可能只需使用标准库即可。 之后,遵循以下指导原则:
- 浏览 **100+** **[例子](_examples)** 和 我们提供的 [一些入门经验](#iris-starter-kits)
- 通过 [godocs](https://godoc.org/github.com/kataras/iris) 阅读细节
- 准备一杯咖啡或茶,无论你喜欢什么,并阅读我们为你推荐的 [一些文章](#articles)
### Iris 入门
<!-- table form
| Description | Link |
| -----------|-------------|
| Hasura hub starter project with a ready to deploy golang helloworld webapp with IRIS! | https://hasura.io/hub/project/hasura/hello-golang-iris |
| A basic web app built in Iris for Go |https://github.com/gauravtiwari/go_iris_app |
| A mini social-network created with the awesome Iris💖💖 | https://github.com/iris-contrib/Iris-Mini-Social-Network |
| Iris isomorphic react/hot reloadable/redux/css-modules starter kit | https://github.com/iris-contrib/iris-starter-kit |
| Demo project with react using typescript and Iris | https://github.com/ionutvilie/react-ts |
| Self-hosted Localization Management Platform built with Iris and Angular | https://github.com/iris-contrib/parrot |
| Iris + Docker and Kubernetes | https://github.com/iris-contrib/cloud-native-go |
| Quickstart for Iris with Nanobox | https://guides.nanobox.io/golang/iris/from-scratch |
-->
1. [snowlyg/IrisApiProject: Iris + gorm + jwt + sqlite3](https://github.com/snowlyg/IrisApiProject) **NEW-Chinese**
2. [yz124/superstar: Iris + xorm to implement the star library](https://github.com/yz124/superstar) **NEW-Chinese**
3. [jebzmos4/Iris-golang: A basic CRUD API in golang with Iris](https://github.com/jebzmos4/Iris-golang)
4. [gauravtiwari/go_iris_app: A basic web app built in Iris for Go](https://github.com/gauravtiwari/go_iris_app)
5. [A mini social-network created with the awesome Iris💖💖](https://github.com/iris-contrib/Iris-Mini-Social-Network)
6. [Iris isomorphic react/hot reloadable/redux/css-modules starter kit](https://github.com/iris-contrib/iris-starter-kit)
7. [ionutvilie/react-ts: Demo project with react using typescript and Iris](https://github.com/ionutvilie/react-ts)
8. [Self-hosted Localization Management Platform built with Iris and Angular](https://github.com/iris-contrib/parrot)
9. [Iris + Docker and Kubernetes](https://github.com/iris-contrib/cloud-native-go)
10. [nanobox.io: Quickstart for Iris with Nanobox](https://guides.nanobox.io/golang/iris/from-scratch)
11. [hasura.io: A Hasura starter project with a ready to deploy Golang hello-world web app with IRIS](https://hasura.io/hub/project/hasura/hello-golang-iris)
> 如果你有类似的使用经验吗 [请提交给我们](https://github.com/kataras/iris/pulls)!
### 中间件
Iris 拥有大量的中间件 [[1]](middleware/)[[2]](https://github.com/iris-contrib/middleware) 供您的 Web 应用程序使用。 不过,您并不局限于此,您可以自由使用与 [net/http](https://golang.org/pkg/net/http/) 包兼容的任何第三方中间件,相关示例 [_examples/convert-handlers](_examples/convert-handlers) 。
### 相关文章(英文)
* [CRUD REST API in Iris (a framework for golang)](https://medium.com/@jebzmos4/crud-rest-api-in-iris-a-framework-for-golang-a5d33652401e)
* [A Todo MVC Application using Iris and Vue.js](https://hackernoon.com/a-todo-mvc-application-using-iris-and-vue-js-5019ff870064)
* [A Hasura starter project with a ready to deploy Golang hello-world web app with IRIS](bit.ly/2lmKaAZ)
* [Top 6 web frameworks for Go as of 2017](https://blog.usejournal.com/top-6-web-frameworks-for-go-as-of-2017-23270e059c4b)
* [Iris Go Framework + MongoDB](https://medium.com/go-language/iris-go-framework-mongodb-552e349eab9c)
* [How to build a file upload form using DropzoneJS and Go](https://hackernoon.com/how-to-build-a-file-upload-form-using-dropzonejs-and-go-8fb9f258a991)
* [How to display existing files on server using DropzoneJS and Go](https://hackernoon.com/how-to-display-existing-files-on-server-using-dropzonejs-and-go-53e24b57ba19)
* [Iris, a modular web framework](https://medium.com/@corebreaker/iris-web-cd684b4685c7)
* [Go vs .NET Core in terms of HTTP performance](https://medium.com/@kataras/go-vs-net-core-in-terms-of-http-performance-7535a61b67b8)
* [Iris Go vs .NET Core Kestrel in terms of HTTP performance](https://hackernoon.com/iris-go-vs-net-core-kestrel-in-terms-of-http-performance-806195dc93d5)
* [How to Turn an Android Device into a Web Server](https://twitter.com/ThePracticalDev/status/892022594031017988)
* [Deploying a Iris Golang app in hasura](https://medium.com/@HasuraHQ/deploy-an-iris-golang-app-with-backend-apis-in-minutes-25a559bf530b)
* [A URL Shortener Service using Go, Iris and Bolt](https://medium.com/@kataras/a-url-shortener-service-using-go-iris-and-bolt-4182f0b00ae7)
### 视频教程(英文) - Youtube
* [Daily Coding - Web Framework Golang: Iris Framework]( https://www.youtube.com/watch?v=BmOLFQ29J3s) by WarnabiruTV
* [Tutorial Golang MVC dengan Iris Framework & Mongo DB](https://www.youtube.com/watch?v=uXiNYhJqh2I&list=PLMrwI6jIZn-1tzskocnh1pptKhVmWdcbS) (19 parts so far) by Musobar Media
* [Go/Golang 27 - Iris framework : Routage de base](https://www.youtube.com/watch?v=rQxRoN6ub78) by stephgdesign
* [Go/Golang 28 - Iris framework : Templating](https://www.youtube.com/watch?v=nOKYV073S2Y) by stephgdesignn
* [Go/Golang 29 - Iris framework : Paramètres](https://www.youtube.com/watch?v=K2FsprfXs1E) by stephgdesign
* [Go/Golang 30 - Iris framework : Les middelwares](https://www.youtube.com/watch?v=BLPy1So6bhE) by stephgdesign
* [Go/Golang 31 - Iris framework : Les sessions](https://www.youtube.com/watch?v=RnBwUrwgEZ8) by stephgdesign
### 工作机会
有很多公司都在寻找具有 Iris 经验的 Go 网站开发者,我们通过 [facebook page](https://www.facebook.com/iris.framework) 发布这些招聘信息。
## 授权协议
Iris 授权基于 [3-Clause BSD License](LICENSE). Iris 是 100 免费和开源软件。
有关授权的任何问题,[请发送电子邮件](mailto:kataras2006@hotmail.com?subject=Iris%20License)。

View File

@ -1 +1 @@
11.1.1:https://github.com/kataras/iris/blob/master/HISTORY.md#fr-11-january-2019--v1111
11.2.0:https://dev.to/kataras/iris-version-11-2-released-22bc

View File

@ -19,7 +19,7 @@ const (
func main() {
app := iris.New()
app.RegisterView(iris.HTML("./views", ".html").Layout("shared/layout.html"))
app.StaticWeb("/public", publicDir)
app.HandleDir("/public", publicDir)
app.OnAnyErrorCode(onError)
mvc.New(app).Handle(new(controllers.HomeController))

View File

@ -1,9 +1,5 @@
package main
/// TODO: remove this on the "master" branch, or even replace it
// with the "iris-mvc" (the new implementatioin is even faster, close to handlers version,
// with bindings or without).
import (
"github.com/kataras/iris/_benchmarks/iris-mvc/controllers"

View File

@ -25,7 +25,7 @@ namespace netcore
services.AddRouting();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
var routeBuilder = new RouteBuilder(app);
routeBuilder.MapGet("api/values/{id}", context =>{

View File

@ -1,15 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
<TargetFramework>netcoreapp3.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.1.5" />
</ItemGroup>
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.4" />
</ItemGroup>
</Project>
</Project>

View File

@ -15,26 +15,8 @@ It doesn't always contain the "best ways" but it does cover each important featu
<details>
<summary>External packages</summary>
```bash
```sh
cd _examples && go get ./...
# or
go get github.com/iris-contrib/middleware/...
go get github.com/betacraft/yaag/irisyaag
go get github.com/markbates/goth/...
go get github.com/casbin/casbin
go get github.com/aws/aws-sdk-go/...
go get github.com/getsentry/raven-go/...
go get github.com/prometheus/client_golang/...
go get github.com/didip/tollbooth
go get github.com/valyala/quicktemplate
go get github.com/shiyanhui/hero
go get github.com/go-xorm/xorm
go get github.com/nfnt/resize
go get github.com/dgrijalva/jwt-go
go get github.com/newrelic/go-agent
go get github.com/valyala/tcplisten
go get github.com/kataras/bindata/cmd/bindata
go get github.com/jmespath/go-jmespath
```
</details>
@ -51,7 +33,7 @@ $ go run main.go
### Overview
- [Hello world!](hello-world/main.go)
- [Hello WebAssemply!](webassembly/basic/main.go) **NEW**
- [Hello WebAssemply!](webassembly/basic/main.go)
- [Glimpse](overview/main.go)
- [Tutorial: Online Visitors](tutorial/online-visitors/main.go)
- [Tutorial: A Todo MVC Application using Iris and Vue.js](https://hackernoon.com/a-todo-mvc-application-using-iris-and-vue-js-5019ff870064)
@ -62,7 +44,7 @@ $ go run main.go
- [Tutorial: DropzoneJS Uploader](tutorial/dropzonejs)
- [Tutorial: Caddy](tutorial/caddy)
- [Tutorial:Iris Go Framework + MongoDB](https://medium.com/go-language/iris-go-framework-mongodb-552e349eab9c)
- [Tutorial: API for Apache Kafka](tutorial/api-for-apache-kafka) **NEW**
- [Tutorial: API for Apache Kafka](tutorial/api-for-apache-kafka)
### Structuring
@ -78,6 +60,7 @@ Structuring depends on your own needs. We can't tell you how to design your own
### HTTP Listening
- [Common, with address](http-listening/listen-addr/main.go)
* [public domain address](http-listening/listen-addr-public/main.go) **NEW**
* [omit server errors](http-listening/listen-addr/omit-server-errors/main.go)
- [UNIX socket file](http-listening/listen-unix/main.go)
- [TLS](http-listening/listen-tls/main.go)
@ -87,6 +70,7 @@ Structuring depends on your own needs. We can't tell you how to design your own
* [common net.Listener](http-listening/custom-listener/main.go)
* [SO_REUSEPORT for unix systems](http-listening/custom-listener/unix-reuseport/main.go)
- Custom HTTP Server
* [HTTP/3 Quic](http-listening/http3-quic) **NEW**
* [easy way](http-listening/custom-httpserver/easy-way/main.go)
* [std way](http-listening/custom-httpserver/std-way/main.go)
* [multi server instances](http-listening/custom-httpserver/multi/main.go)
@ -146,10 +130,10 @@ Navigate through examples for a better understanding.
- [Custom HTTP Errors](routing/http-errors/main.go)
- [Dynamic Path](routing/dynamic-path/main.go)
* [root level wildcard path](routing/dynamic-path/root-wildcard/main.go)
- [Write your own custom parameter types](routing/macros/main.go) **NEW**
- [Write your own custom parameter types](routing/macros/main.go)
- [Reverse routing](routing/reverse/main.go)
- [Custom Router (high-level)](routing/custom-high-level-router/main.go) **NEW**
- [Custom Wrapper](routing/custom-wrapper/main.go)
- [Custom Router (high-level)](routing/custom-high-level-router/main.go)
- [Custom Wrapper](routing/custom-wrapper/main.go) **UPDATED**
- Custom Context
* [method overriding](routing/custom-context/method-overriding/main.go)
* [new implementation](routing/custom-context/new-implementation/main.go)
@ -163,157 +147,24 @@ Navigate through examples for a better understanding.
- [How it works](https://github.com/kataras/iris/blob/master/versioning/README.md)
- [Example](versioning/main.go)
### hero
### Dependency Injection
- [Basic](hero/basic/main.go)
- [Overview](hero/overview)
- [Sessions](hero/sessions) **NEW**
- [Sessions](hero/sessions)
- [Yet another dependency injection example and good practises at general](hero/smart-contract/main.go) **NEW**
### MVC
![](mvc/web_mvc_diagram.png)
Iris has **first-class support for the MVC (Model View Controller) pattern**, you'll not find
these stuff anywhere else in the Go world.
Iris web framework supports Request data, Models, Persistence Data and Binding
with the fastest possible execution.
**Characteristics**
All HTTP Methods are supported, for example if want to serve `GET`
then the controller should have a function named `Get()`,
you can define more than one method function to serve in the same Controller.
Serve custom controller's struct's methods as handlers with custom paths(even with regex parametermized path) via the `BeforeActivation` custom event callback, per-controller. Example:
```go
import (
"github.com/kataras/iris"
"github.com/kataras/iris/mvc"
)
func main() {
app := iris.New()
mvc.Configure(app.Party("/root"), myMVC)
app.Run(iris.Addr(":8080"))
}
func myMVC(app *mvc.Application) {
// app.Register(...)
// app.Router.Use/UseGlobal/Done(...)
app.Handle(new(MyController))
}
type MyController struct {}
func (m *MyController) BeforeActivation(b mvc.BeforeActivation) {
// b.Dependencies().Add/Remove
// b.Router().Use/UseGlobal/Done // and any standard API call you already know
// 1-> Method
// 2-> Path
// 3-> The controller's function name to be parsed as handler
// 4-> Any handlers that should run before the MyCustomHandler
b.Handle("GET", "/something/{id:long}", "MyCustomHandler", anyMiddleware...)
}
// GET: http://localhost:8080/root
func (m *MyController) Get() string { return "Hey" }
// GET: http://localhost:8080/root/something/{id:long}
func (m *MyController) MyCustomHandler(id int64) string { return "MyCustomHandler says Hey" }
```
Persistence data inside your Controller struct (share data between requests)
by defining services to the Dependencies or have a `Singleton` controller scope.
Share the dependencies between controllers or register them on a parent MVC Application, and ability
to modify dependencies per-controller on the `BeforeActivation` optional event callback inside a Controller,
i.e `func(c *MyController) BeforeActivation(b mvc.BeforeActivation) { b.Dependencies().Add/Remove(...) }`.
Access to the `Context` as a controller's field(no manual binding is neede) i.e `Ctx iris.Context` or via a method's input argument, i.e `func(ctx iris.Context, otherArguments...)`.
Models inside your Controller struct (set-ed at the Method function and rendered by the View).
You can return models from a controller's method or set a field in the request lifecycle
and return that field to another method, in the same request lifecycle.
Flow as you used to, mvc application has its own `Router` which is a type of `iris/router.Party`, the standard iris api.
`Controllers` can be registered to any `Party`, including Subdomains, the Party's begin and done handlers work as expected.
Optional `BeginRequest(ctx)` function to perform any initialization before the method execution,
useful to call middlewares or when many methods use the same collection of data.
Optional `EndRequest(ctx)` function to perform any finalization after any method executed.
Inheritance, recursively, see for example our `mvc.SessionController`, it has the `Session *sessions.Session` and `Manager *sessions.Sessions` as embedded fields
which are filled by its `BeginRequest`, [here](https://github.com/kataras/iris/blob/master/mvc/session_controller.go).
This is just an example, you could use the `sessions.Session` which returned from the manager's `Start` as a dynamic dependency to the MVC Application, i.e
`mvcApp.Register(sessions.New(sessions.Config{Cookie: "iris_session_id"}).Start)`.
Access to the dynamic path parameters via the controller's methods' input arguments, no binding is needed.
When you use the Iris' default syntax to parse handlers from a controller, you need to suffix the methods
with the `By` word, uppercase is a new sub path. Example:
If `mvc.New(app.Party("/user")).Handle(new(user.Controller))`
- `func(*Controller) Get()` - `GET:/user`.
- `func(*Controller) Post()` - `POST:/user`.
- `func(*Controller) GetLogin()` - `GET:/user/login`
- `func(*Controller) PostLogin()` - `POST:/user/login`
- `func(*Controller) GetProfileFollowers()` - `GET:/user/profile/followers`
- `func(*Controller) PostProfileFollowers()` - `POST:/user/profile/followers`
- `func(*Controller) GetBy(id int64)` - `GET:/user/{param:long}`
- `func(*Controller) PostBy(id int64)` - `POST:/user/{param:long}`
If `mvc.New(app.Party("/profile")).Handle(new(profile.Controller))`
- `func(*Controller) GetBy(username string)` - `GET:/profile/{param:string}`
If `mvc.New(app.Party("/assets")).Handle(new(file.Controller))`
- `func(*Controller) GetByWildard(path string)` - `GET:/assets/{param:path}`
Supported types for method functions receivers: int, int64, bool and string.
Response via output arguments, optionally, i.e
```go
func(c *ExampleController) Get() string |
(string, string) |
(string, int) |
int |
(int, string) |
(string, error) |
error |
(int, error) |
(any, bool) |
(customStruct, error) |
customStruct |
(customStruct, int) |
(customStruct, string) |
mvc.Result or (mvc.Result, error)
```
where [mvc.Result](https://github.com/kataras/iris/blob/master/mvc/go19.go#L10) is an [interface](https://github.com/kataras/iris/blob/master/hero/func_result.go#L18) which contains only that function: `Dispatch(ctx iris.Context)`.
## Using Iris MVC for code reuse
By creating components that are independent of one another, developers are able to reuse components quickly and easily in other applications. The same (or similar) view for one application can be refactored for another application with different data because the view is simply handling how the data is being displayed to the user.
If you're new to back-end web development read about the MVC architectural pattern first, a good start is that [wikipedia article](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller).
Follow the examples below,
- [Hello world](mvc/hello-world/main.go) **UPDATED**
- [Session Controller](mvc/session-controller/main.go) **UPDATED**
- [Overview - Plus Repository and Service layers](mvc/overview) **UPDATED**
- [Login showcase - Plus Repository and Service layers](mvc/login) **UPDATED**
- [Singleton](mvc/singleton) **NEW**
- [Websocket Controller](mvc/websocket) **NEW**
- [Register Middleware](mvc/middleware) **NEW**
- [Vue.js Todo MVC](tutorial/vuejs-todo-mvc) **NEW**
- [Hello world](mvc/hello-world/main.go)
- [Regexp](mvc/regexp/main.go) **NEW**
- [Session Controller](mvc/session-controller/main.go)
- [Overview - Plus Repository and Service layers](mvc/overview)
- [Login showcase - Plus Repository and Service layers](mvc/login)
- [Singleton](mvc/singleton)
- [Websocket Controller](mvc/websocket) **UPDATED**
- [Register Middleware](mvc/middleware)
- [Vue.js Todo MVC](tutorial/vuejs-todo-mvc)
### Subdomains
@ -331,14 +182,6 @@ Follow the examples below,
### View
| Engine | Declaration |
| -----------|-------------|
| template/html | `iris.HTML(...)` |
| django | `iris.Django(...)` |
| handlebars | `iris.Handlebars(...)` |
| amber | `iris.Amber(...)` |
| pug(jade) | `iris.Pug(...)` |
- [Overview](view/overview/main.go)
- [Hi](view/template_html_0/main.go)
- [A simple Layout](view/template_html_1/main.go)
@ -352,6 +195,8 @@ Follow the examples below,
- [Pug (Jade) Actions`](view/template_pug_1)
- [Pug (Jade) Includes`](view/template_pug_2)
- [Pug (Jade) Extends`](view/template_pug_3)
- [Jet](/view/template_jet_0) **NEW**
- [Jet Embedded](view/template_jet_1_embedded) **NEW**
You can serve [quicktemplate](https://github.com/valyala/quicktemplate) and [hero templates](https://github.com/shiyanhui/hero/hero) files too, simply by using the `context#ResponseWriter`, take a look at the [http_responsewriter/quicktemplate](http_responsewriter/quicktemplate) and [http_responsewriter/herotemplate](http_responsewriter/herotemplate) examples.
@ -359,20 +204,20 @@ You can serve [quicktemplate](https://github.com/valyala/quicktemplate) and [her
- [Basic Authentication](authentication/basicauth/main.go)
- [OAUth2](authentication/oauth2/main.go)
- [JWT](experimental-handlers/jwt/main.go)
- [Request Auth(JWT)](experimental-handlers/jwt/main.go)
- [Sessions](#sessions)
### File Server
- [Favicon](file-server/favicon/main.go)
- [Basic](file-server/basic/main.go)
- [Embedding Files Into App Executable File](file-server/embedding-files-into-app/main.go)
- [Embedding Gziped Files Into App Executable File](file-server/embedding-gziped-files-into-app/main.go) **NEW**
- [Basic](file-server/basic/main.go) **UPDATED**
- [Embedding Files Into App Executable File](file-server/embedding-files-into-app/main.go) **UPDATED**
- [Embedding Gziped Files Into App Executable File](file-server/embedding-gziped-files-into-app/main.go) **UPDATED**
- [Send/Force-Download Files](file-server/send-files/main.go)
- Single Page Applications
* [single Page Application](file-server/single-page-application/basic/main.go)
* [embedded Single Page Application](file-server/single-page-application/embedded-single-page-application/main.go)
* [embedded Single Page Application with other routes](file-server/single-page-application/embedded-single-page-application-with-other-routes/main.go)
* [single Page Application](file-server/single-page-application/basic/main.go) **UPDATED**
* [embedded Single Page Application](file-server/single-page-application/embedded-single-page-application/main.go) **UPDATED**
* [embedded Single Page Application with other routes](file-server/single-page-application/embedded-single-page-application-with-other-routes/main.go) **UPDATED**
### How to Read from `context.Request() *http.Request`
@ -382,9 +227,10 @@ You can serve [quicktemplate](https://github.com/valyala/quicktemplate) and [her
- [Read Form](http_request/read-form/main.go)
- [Read Custom per type](http_request/read-custom-per-type/main.go)
- [Read Custom via Unmarshaler](http_request/read-custom-via-unmarshaler/main.go)
- [Read Many times](http_request/read-many/main.go)
- [Upload/Read File](http_request/upload-file/main.go)
- [Upload multiple files with an easy way](http_request/upload-files/main.go)
- [Extract referrer from "referer" header or URL query parameter](http_request/extract-referer/main.go) **NEW**
- [Extract referrer from "referer" header or URL query parameter](http_request/extract-referer/main.go)
> The `context.Request()` returns the same *http.Request you already know, these examples show some places where the Context uses this object. Besides that you can use it as you did before iris.
@ -396,7 +242,7 @@ You can serve [quicktemplate](https://github.com/valyala/quicktemplate) and [her
- [Write Gzip](http_responsewriter/write-gzip/main.go)
- [Stream Writer](http_responsewriter/stream-writer/main.go)
- [Transactions](http_responsewriter/transactions/main.go)
- [SSE](http_responsewriter/sse/main.go) **NEW**
- [SSE](http_responsewriter/sse/main.go)
- [SSE (third-party package usage for server sent events)](http_responsewriter/sse-third-party/main.go)
> The `context/context#ResponseWriter()` returns an enchament version of a http.ResponseWriter, these examples show some places where the Context uses this object. Besides that you can use it as you did before iris.
@ -473,17 +319,13 @@ iris session manager lives on its own [package](https://github.com/kataras/iris/
### Websockets
iris websocket library lives on its own [package](https://github.com/kataras/iris/tree/master/websocket).
The package is designed to work with raw websockets although its API is similar to the famous [socket.io](https://socket.io). I have read an article recently and I felt very contented about my decision to design a **fast** websocket-**only** package for Iris and not a backwards socket.io-like package. You can read that article by following this link: https://medium.com/@ivanderbyl/why-you-don-t-need-socket-io-6848f1c871cd.
- [Chat](websocket/chat/main.go)
- [Native Messages](websocket/native-messages/main.go)
- [Connection List](websocket/connectionlist/main.go)
- [TLS Enabled](websocket/secure/main.go)
- [Custom Raw Go Client](websocket/custom-go-client/main.go)
> You're free to use your own favourite websockets package if you'd like so.
- [Basic](websocket/basic) **NEW**
* [Server](websocket/basic/server.go)
* [Go Client](websocket/basic/go-client/client.go)
* [Browser Client](websocket/basic/browser/index.html)
* [Browser NPM Client (browserify)](websocket/basic/browserify/app.js)
- [Native Messages](websocket/native-messages/main.go) **UPDATED**
- [TLS Enabled](websocket/secure/README.md)
### Typescript Automation Tools

View File

@ -10,7 +10,7 @@
### 概览
- [Hello world!](hello-world/main.go)
- [Hello WebAssemply!](webassembly/basic/main.go) **NEW**
- [Hello WebAssemply!](webassembly/basic/main.go)
- [基础](overview/main.go)
- [教程: 在线人数](tutorial/online-visitors/main.go)
- [教程: 一个“待完成”MVC Application基于Iris和Vue.js](https://hackernoon.com/a-todo-mvc-application-using-iris-and-vue-js-5019ff870064)
@ -21,7 +21,7 @@
- [教程: DropzoneJS 上传](tutorial/dropzonejs)
- [教程: Caddy 服务器使用](tutorial/caddy)
- [教程: Iris + MongoDB](https://medium.com/go-language/iris-go-framework-mongodb-552e349eab9c)
- [教程: Apache Kafka的API](tutorial/api-for-apache-kafka) **NEW**
- [教程: Apache Kafka的API](tutorial/api-for-apache-kafka)
### 目录结构
@ -45,7 +45,8 @@ Iris 是个底层框架, 对 MVC 模式有很好的支持,但不限制文件
- 自定义 TCP 监听器
   * [通用 net.Listener](http-listening/custom-listener/main.go)
* [unix系统的SO_REUSEPORT](http-listening/custom-listener/unix-reuseport/main.go)
- 自定义 HTTP 服务
- 自定义 HTTP 服务
* [HTTP/3 Quic](http-listening/http3-quic) **凊**
   * [简单方式](http-listening/custom-httpserver/easy-way/main.go)
* [标准方式](http-listening/custom-httpserver/std-way/main.go)
   * [多个服务示例](http-listening/custom-httpserver/multi/main.go)
@ -105,10 +106,10 @@ app.Get("{root:path}", rootWildcardHandler)
- [自定义 HTTP 错误](routing/http-errors/main.go)
- [动态路径](routing/dynamic-path/main.go)
* [根级通配符路径](routing/dynamic-path/root-wildcard/main.go)
- [编写你自己的参数类型](routing/macros/main.go) **NEW**
- [编写你自己的参数类型](routing/macros/main.go)
- [反向路由](routing/reverse/main.go)
- [自定义路由(高层级)](routing/custom-high-level-router/main.go) **NEW**
- [自定义包装](routing/custom-wrapper/main.go)
- [自定义路由(高层级)](routing/custom-high-level-router/main.go)
- [自定义包装](routing/custom-wrapper/main.go) **更新**
- 自定义上下文
   * [方法重写](routing/custom-context/method-overriding/main.go)
   * [新实现方式](routing/custom-context/new-implementation/main.go)
@ -121,8 +122,8 @@ app.Get("{root:path}", rootWildcardHandler)
- [基础](hero/basic/main.go)
- [概览](hero/overview)
- [Sessions](hero/sessions) **NEW**
- [另一种依赖注入的例子和通常的较好实践](hero/smart-contract/main.go) **NEW**
- [Sessions](hero/sessions)
- [另一种依赖注入的例子和通常的较好实践](hero/smart-contract/main.go) ****
### MVC 模式
@ -255,14 +256,14 @@ func(c *ExampleController) Get() string |
参考下面的示例
- [Hello world](mvc/hello-world/main.go) **UPDATED**
- [Session Controller](mvc/session-controller/main.go) **UPDATED**
- [Overview - Plus Repository and Service layers](mvc/overview) **UPDATED**
- [Login showcase - Plus Repository and Service layers](mvc/login) **UPDATED**
- [Singleton](mvc/singleton) **NEW**
- [Websocket Controller](mvc/websocket) **NEW**
- [Register Middleware](mvc/middleware) **NEW**
- [Vue.js Todo MVC](tutorial/vuejs-todo-mvc) **NEW**
- [Hello world](mvc/hello-world/main.go) **更新**
- [Session Controller](mvc/session-controller/main.go) **更新**
- [Overview - Plus Repository and Service layers](mvc/overview) **更新**
- [Login showcase - Plus Repository and Service layers](mvc/login) **更新**
- [Singleton](mvc/singleton) ****
- [Websocket Controller](mvc/websocket) ****
- [Register Middleware](mvc/middleware) ****
- [Vue.js Todo MVC](tutorial/vuejs-todo-mvc) ****
### 子域名
@ -316,14 +317,14 @@ You can serve [quicktemplate](https://github.com/valyala/quicktemplate) and [her
### 文件服务器
- [Favicon](file-server/favicon/main.go)
- [基础操作](file-server/basic/main.go)
- [把文件嵌入应用的可执行文件](file-server/embedding-files-into-app/main.go)
- [嵌入Gzip压缩的文件到可咨询文件](file-server/embedding-gziped-files-into-app/main.go) **NEW**
- [基础操作](file-server/basic/main.go) **更新**
- [把文件嵌入应用的可执行文件](file-server/embedding-files-into-app/main.go) **更新**
- [嵌入Gzip压缩的文件到可咨询文件](file-server/embedding-gziped-files-into-app/main.go) **更新**
- [上传/(强制)下载文件](file-server/send-files/main.go)
- 单页面应用(Single Page Applications)
* [单页面应用](file-server/single-page-application/basic/main.go)
* [嵌入式(embedded)单页面应用](file-server/single-page-application/embedded-single-page-application/main.go)
* [使用额外路由的嵌入式单页面应用](file-server/single-page-application/embedded-single-page-application-with-other-routes/main.go)
* [单页面应用](file-server/single-page-application/basic/main.go) **更新**
* [嵌入式(embedded)单页面应用](file-server/single-page-application/embedded-single-page-application/main.go) **更新**
* [使用额外路由的嵌入式单页面应用](file-server/single-page-application/embedded-single-page-application-with-other-routes/main.go) **更新**
### 如何读取`context.Request() *http.Request`
@ -346,7 +347,7 @@ You can serve [quicktemplate](https://github.com/valyala/quicktemplate) and [her
- [写入Gzip压缩](http_responsewriter/write-gzip/main.go)
- [流输出Stream Writer](http_responsewriter/stream-writer/main.go)
- [数据传递Transactions](http_responsewriter/transactions/main.go)
- [SSE](http_responsewriter/sse/main.go) **NEW**
- [SSE](http_responsewriter/sse/main.go)
- [SSE (third-party package usage for server sent events第三方库SSE)](http_responsewriter/sse-third-party/main.go)
> The `context/context#ResponseWriter()` returns an enchament version of a http.ResponseWriter, these examples show some places where the Context uses this object. Besides that you can use it as you did before iris.
@ -425,18 +426,13 @@ Iris session 管理独立包 [package](https://github.com/kataras/iris/tree/mast
### Websockets
iris websocket库依赖于它自己的[包](https://github.com/kataras/iris/tree/master/websocket).
设计这个包的目的是处理原始websockets虽然它的API和著名的[socket.io](https://socket.io)很像。我最近读了一片文章,并且对我
决定给iris设计一个**快速的**websocket**限定**包并且不是一个向后传递类socket.io的包。你可以阅读这个链接里的文章https://medium.com/@ivanderbyl/why-you-don-t-need-socket-io-6848f1c871cd。
- [聊天](websocket/chat/main.go)
- [原生消息](websocket/native-messages/main.go)
- [连接列表](websocket/connectionlist/main.go)
- [TLS支持](websocket/secure/main.go)
- [自定义原始Go客户端](websocket/custom-go-client/main.go)
> 如果你愿意你可以自由使用你自己喜欢的websockets包。
- [Basic](websocket/basic) **新**
* [Server](websocket/basic/server.go)
* [Go Client](websocket/basic/go-client/client.go)
* [Browser Client](websocket/basic/browser/index.html)
* [Browser NPM Client (browserify)](websocket/basic/browserify/app.js)
- [原生消息](websocket/native-messages/main.go) **更新**
- [TLS支持](websocket/secure/README.md)
### Typescript 自动化工具

View File

@ -2,5 +2,5 @@
- [Basic Authentication](basicauth/main.go)
- [OAUth2](oauth2/main.go)
- [JWT](https://github.com/kataras/iris/blob/master/_examples/experimental-handlers/jwt/main.go)
- [Request Auth(JWT)](https://github.com/iris-contrib/middleware/blob/master/jwt)
- [Sessions](https://github.com/kataras/iris/tree/master/_examples/#sessions)

View File

@ -74,7 +74,7 @@ func writeMarkdown(ctx iris.Context) {
ctx.Markdown(markdownContents)
}
/* Note that `StaticWeb` does use the browser's disk caching by-default
therefore, register the cache handler AFTER any StaticWeb calls,
/* Note that `HandleDir` does use the browser's disk caching by-default
therefore, register the cache handler AFTER any HandleDir calls,
for a faster solution that server doesn't need to keep track of the response
navigate to https://github.com/kataras/iris/blob/master/_examples/cache/client-side/main.go */

View File

@ -134,7 +134,7 @@ func main() {
```
## Built'n Configurators
## Builtin Configurators
```go
// WithoutServerError will cause to ignore the matched "errors"

View File

@ -1,5 +0,0 @@
# Install iris-contrib/middleware
```sh
$ go get -u github.com/iris-contrib/middleware/...
```

View File

@ -1,14 +0,0 @@
[request_definition]
r = sub, obj, act
[policy_definition]
p = sub, obj, act
[role_definition]
g = _, _
[policy_effect]
e = some(where (p.eft == allow))
[matchers]
m = g(r.sub, p.sub) && keyMatch(r.obj, p.obj) && (r.act == p.act || p.act == "*")

View File

@ -1,5 +0,0 @@
p, alice, /dataset1/*, GET
p, alice, /dataset1/resource1, POST
p, bob, /dataset2/resource1, *
p, bob, /dataset2/resource2, GET
p, bob, /dataset2/folder1/*, POST
1 p alice /dataset1/* GET
2 p alice /dataset1/resource1 POST
3 p bob /dataset2/resource1 *
4 p bob /dataset2/resource2 GET
5 p bob /dataset2/folder1/* POST

View File

@ -1,43 +0,0 @@
package main
import (
"github.com/kataras/iris"
"github.com/casbin/casbin"
cm "github.com/iris-contrib/middleware/casbin"
)
// $ go get github.com/casbin/casbin
// $ go run main.go
// Enforcer maps the model and the policy for the casbin service, we use this variable on the main_test too.
var Enforcer = casbin.NewEnforcer("casbinmodel.conf", "casbinpolicy.csv")
func newApp() *iris.Application {
casbinMiddleware := cm.New(Enforcer)
app := iris.New()
app.Use(casbinMiddleware.ServeHTTP)
app.Get("/", hi)
app.Get("/dataset1/{p:path}", hi) // p, alice, /dataset1/*, GET
app.Post("/dataset1/resource1", hi)
app.Get("/dataset2/resource2", hi)
app.Post("/dataset2/folder1/{p:path}", hi)
app.Any("/dataset2/resource1", hi)
return app
}
func main() {
app := newApp()
app.Run(iris.Addr(":8080"))
}
func hi(ctx iris.Context) {
ctx.Writef("Hello %s", cm.Username(ctx.Request()))
}

View File

@ -1,49 +0,0 @@
package main
import (
"testing"
"github.com/iris-contrib/httpexpect"
"github.com/kataras/iris/httptest"
)
func TestCasbinMiddleware(t *testing.T) {
app := newApp()
e := httptest.New(t, app, httptest.Debug(false))
type ttcasbin struct {
username string
path string
method string
status int
}
tt := []ttcasbin{
{"alice", "/dataset1/resource1", "GET", 200},
{"alice", "/dataset1/resource1", "POST", 200},
{"alice", "/dataset1/resource2", "GET", 200},
{"alice", "/dataset1/resource2", "POST", 404},
{"bob", "/dataset2/resource1", "GET", 200},
{"bob", "/dataset2/resource1", "POST", 200},
{"bob", "/dataset2/resource1", "DELETE", 200},
{"bob", "/dataset2/resource2", "GET", 200},
{"bob", "/dataset2/resource2", "POST", 404},
{"bob", "/dataset2/resource2", "DELETE", 404},
{"bob", "/dataset2/folder1/item1", "GET", 404},
{"bob", "/dataset2/folder1/item1", "POST", 200},
{"bob", "/dataset2/folder1/item1", "DELETE", 404},
{"bob", "/dataset2/folder1/item2", "GET", 404},
{"bob", "/dataset2/folder1/item2", "POST", 200},
{"bob", "/dataset2/folder1/item2", "DELETE", 404},
}
for _, tt := range tt {
check(e, tt.method, tt.path, tt.username, tt.status)
}
}
func check(e *httpexpect.Expect, method, path, username string, status int) {
e.Request(method, path).WithBasicAuth(username, "password").Expect().Status(status)
}

View File

@ -1,14 +0,0 @@
[request_definition]
r = sub, obj, act
[policy_definition]
p = sub, obj, act
[role_definition]
g = _, _
[policy_effect]
e = some(where (p.eft == allow))
[matchers]
m = g(r.sub, p.sub) && keyMatch(r.obj, p.obj) && (r.act == p.act || p.act == "*")

View File

@ -1,7 +0,0 @@
p, alice, /dataset1/*, GET
p, alice, /dataset1/resource1, POST
p, bob, /dataset2/resource1, *
p, bob, /dataset2/resource2, GET
p, bob, /dataset2/folder1/*, POST
p, dataset1_admin, /dataset1/*, *
g, cathrin, dataset1_admin
1 p, alice, /dataset1/*, GET
2 p, alice, /dataset1/resource1, POST
3 p, bob, /dataset2/resource1, *
4 p, bob, /dataset2/resource2, GET
5 p, bob, /dataset2/folder1/*, POST
6 p, dataset1_admin, /dataset1/*, *
7 g, cathrin, dataset1_admin

View File

@ -1,43 +0,0 @@
package main
import (
"github.com/kataras/iris"
"github.com/casbin/casbin"
cm "github.com/iris-contrib/middleware/casbin"
)
// $ go get github.com/casbin/casbin
// $ go run main.go
// Enforcer maps the model and the policy for the casbin service, we use this variable on the main_test too.
var Enforcer = casbin.NewEnforcer("casbinmodel.conf", "casbinpolicy.csv")
func newApp() *iris.Application {
casbinMiddleware := cm.New(Enforcer)
app := iris.New()
app.WrapRouter(casbinMiddleware.Wrapper())
app.Get("/", hi)
app.Any("/dataset1/{p:path}", hi) // p, dataset1_admin, /dataset1/*, * && p, alice, /dataset1/*, GET
app.Post("/dataset1/resource1", hi)
app.Get("/dataset2/resource2", hi)
app.Post("/dataset2/folder1/{p:path}", hi)
app.Any("/dataset2/resource1", hi)
return app
}
func main() {
app := newApp()
app.Run(iris.Addr(":8080"))
}
func hi(ctx iris.Context) {
ctx.Writef("Hello %s", cm.Username(ctx.Request()))
}

View File

@ -1,78 +0,0 @@
package main
import (
"testing"
"github.com/iris-contrib/httpexpect"
"github.com/kataras/iris/httptest"
)
func TestCasbinWrapper(t *testing.T) {
app := newApp()
e := httptest.New(t, app)
type ttcasbin struct {
username string
path string
method string
status int
}
tt := []ttcasbin{
{"alice", "/dataset1/resource1", "GET", 200},
{"alice", "/dataset1/resource1", "POST", 200},
{"alice", "/dataset1/resource2", "GET", 200},
{"alice", "/dataset1/resource2", "POST", 403},
{"bob", "/dataset2/resource1", "GET", 200},
{"bob", "/dataset2/resource1", "POST", 200},
{"bob", "/dataset2/resource1", "DELETE", 200},
{"bob", "/dataset2/resource2", "GET", 200},
{"bob", "/dataset2/resource2", "POST", 403},
{"bob", "/dataset2/resource2", "DELETE", 403},
{"bob", "/dataset2/folder1/item1", "GET", 403},
{"bob", "/dataset2/folder1/item1", "POST", 200},
{"bob", "/dataset2/folder1/item1", "DELETE", 403},
{"bob", "/dataset2/folder1/item2", "GET", 403},
{"bob", "/dataset2/folder1/item2", "POST", 200},
{"bob", "/dataset2/folder1/item2", "DELETE", 403},
}
for _, tt := range tt {
check(e, tt.method, tt.path, tt.username, tt.status)
}
ttAdmin := []ttcasbin{
{"cathrin", "/dataset1/item", "GET", 200},
{"cathrin", "/dataset1/item", "POST", 200},
{"cathrin", "/dataset1/item", "DELETE", 200},
{"cathrin", "/dataset2/item", "GET", 403},
{"cathrin", "/dataset2/item", "POST", 403},
{"cathrin", "/dataset2/item", "DELETE", 403},
}
for _, tt := range ttAdmin {
check(e, tt.method, tt.path, tt.username, tt.status)
}
Enforcer.DeleteRolesForUser("cathrin")
ttAdminDeleted := []ttcasbin{
{"cathrin", "/dataset1/item", "GET", 403},
{"cathrin", "/dataset1/item", "POST", 403},
{"cathrin", "/dataset1/item", "DELETE", 403},
{"cathrin", "/dataset2/item", "GET", 403},
{"cathrin", "/dataset2/item", "POST", 403},
{"cathrin", "/dataset2/item", "DELETE", 403},
}
for _, tt := range ttAdminDeleted {
check(e, tt.method, tt.path, tt.username, tt.status)
}
}
func check(e *httpexpect.Expect, method, path, username string, status int) {
e.Request(method, path).WithBasicAuth(username, "password").Expect().Status(status)
}

View File

@ -1,50 +0,0 @@
package main
import (
"time"
"github.com/kataras/iris"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/cloudwatch"
cw "github.com/iris-contrib/middleware/cloudwatch"
)
// $ go get github.com/aws/aws-sdk-go/...
// $ go run main.go
func main() {
app := iris.New()
app.Use(cw.New("us-east-1", "test").ServeHTTP)
app.Get("/", func(ctx iris.Context) {
put := cw.GetPutFunc(ctx)
put([]*cloudwatch.MetricDatum{
{
MetricName: aws.String("MyMetric"),
Dimensions: []*cloudwatch.Dimension{
{
Name: aws.String("ThingOne"),
Value: aws.String("something"),
},
{
Name: aws.String("ThingTwo"),
Value: aws.String("other"),
},
},
Timestamp: aws.Time(time.Now()),
Unit: aws.String("Count"),
Value: aws.Float64(42),
},
})
ctx.StatusCode(iris.StatusOK)
ctx.Text("success!\n")
})
// http://localhost:8080
// should give: NoCredentialProviders
// which is correct, you have to authorize your aws, we asumme that you know how to.
app.Run(iris.Addr(":8080"))
}

View File

@ -1,38 +0,0 @@
package main
import (
"github.com/kataras/iris"
)
// NOTE: THIS IS OPTIONALLY.
// It is just an example of communication between cors/simple/main.go and your app
// based on issues that beginners had with it.
// You should use your own favourite library for HTTP requests (any programming language ofc).
//
// Replace the '8fc93b1c.ngrok.io' with a domain which
// exposes the cors/simple/main.go server side.
const url = "http://8fc93b1c.ngrok.io/api/v1/mailer"
var clientSide = []byte(`<script type="text/javascript">
fetch("` + url + `", {
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
},
method: "POST",
mode: "cors",
body: JSON.stringify({ email: "mymail@mail.com" }),
});
</script>`)
func main() {
app := iris.New()
app.Get("/", func(ctx iris.Context) {
ctx.Write(clientSide)
})
// Start and navigate to http://localhost:8080
// and go to the previous terminal of your running cors/simple/main.go server
// and see the logs.
app.Run(iris.Addr(":8080"))
}

View File

@ -1,54 +0,0 @@
package main
import (
"github.com/kataras/iris"
)
func main() {
app := iris.New()
crs := func(ctx iris.Context) {
ctx.Header("Access-Control-Allow-Origin", "*")
ctx.Header("Access-Control-Allow-Credentials", "true")
ctx.Header("Access-Control-Allow-Headers", "Access-Control-Allow-Origin,Content-Type")
ctx.Next()
} // or "github.com/iris-contrib/middleware/cors"
v1 := app.Party("/api/v1", crs).AllowMethods(iris.MethodOptions) // <- important for the preflight.
{
v1.Post("/mailer", func(ctx iris.Context) {
var any iris.Map
err := ctx.ReadJSON(&any)
if err != nil {
ctx.WriteString(err.Error())
ctx.StatusCode(iris.StatusBadRequest)
return
}
ctx.Application().Logger().Infof("received %#+v", any)
})
v1.Get("/home", func(ctx iris.Context) {
ctx.WriteString("Hello from /home")
})
v1.Get("/about", func(ctx iris.Context) {
ctx.WriteString("Hello from /about")
})
v1.Post("/send", func(ctx iris.Context) {
ctx.WriteString("sent")
})
v1.Put("/send", func(ctx iris.Context) {
ctx.WriteString("updated")
})
v1.Delete("/send", func(ctx iris.Context) {
ctx.WriteString("deleted")
})
}
// iris.WithoutPathCorrectionRedirection | iris#Configuration.DisablePathCorrectionRedirection:
// CORS needs the allow origin headers in the redirect response as well, we have a solution for this:
// If you use iris >= v11.0.4 then add the `app.Run(..., iris.WithoutPathCorrectionRedirection)`
// on the server side if you wish
// to directly fire the handler instead of redirection (which is the default behavior)
// on request paths like "/v1/mailer/" when "/v1/mailer" route handler is registered.
app.Run(iris.Addr(":80"), iris.WithoutPathCorrectionRedirection)
}

View File

@ -1,55 +0,0 @@
// This middleware provides Cross-Site Request Forgery
// protection.
//
// It securely generates a masked (unique-per-request) token that
// can be embedded in the HTTP response (e.g. form field or HTTP header).
// The original (unmasked) token is stored in the session, which is inaccessible
// by an attacker (provided you are using HTTPS). Subsequent requests are
// expected to include this token, which is compared against the session token.
// Requests that do not provide a matching token are served with a HTTP 403
// 'Forbidden' error response.
package main
// $ go get -u github.com/iris-contrib/middleware/...
import (
"github.com/kataras/iris"
"github.com/iris-contrib/middleware/csrf"
)
func main() {
app := iris.New()
app.RegisterView(iris.HTML("./views", ".html"))
// Note that the authentication key provided should be 32 bytes
// long and persist across application restarts.
protect := csrf.Protect([]byte("9AB0F421E53A477C084477AEA06096F5"),
csrf.Secure(false)) // Defaults to true, but pass `false` while no https (devmode).
users := app.Party("/user", protect)
{
users.Get("/signup", getSignupForm)
// // POST requests without a valid token will return a HTTP 403 Forbidden.
users.Post("/signup", postSignupForm)
}
// GET: http://localhost:8080/user/signup
// POST: http://localhost:8080/user/signup
app.Run(iris.Addr(":8080"))
}
func getSignupForm(ctx iris.Context) {
// views/user/signup.html just needs a {{ .csrfField }} template tag for
// csrf.TemplateField to inject the CSRF token into. Easy!
ctx.ViewData(csrf.TemplateTag, csrf.TemplateField(ctx))
ctx.View("user/signup.html")
// We could also retrieve the token directly from csrf.Token(ctx) and
// set it in the request header - ctx.GetHeader("X-CSRF-Token", token)
// This is useful if you're sending JSON to clients or a front-end JavaScript
// framework.
}
func postSignupForm(ctx iris.Context) {
ctx.Writef("You're welcome mate!")
}

View File

@ -1,4 +0,0 @@
<form method="POST" action="/user/signup">
{{ .csrfField }}
<button type="submit">Proceed</button>
</form>

View File

@ -1,46 +0,0 @@
// iris provides some basic middleware, most for your learning curve.
// You can use any net/http compatible middleware with iris.FromStd wrapper.
//
// JWT net/http video tutorial for golang newcomers: https://www.youtube.com/watch?v=dgJFeqeXVKw
//
// This middleware is the only one cloned from external source: https://github.com/auth0/go-jwt-middleware
// (because it used "context" to define the user but we don't need that so a simple iris.FromStd wouldn't work as expected.)
package main
// $ go get -u github.com/dgrijalva/jwt-go
// $ go run main.go
import (
"github.com/kataras/iris"
"github.com/dgrijalva/jwt-go"
jwtmiddleware "github.com/iris-contrib/middleware/jwt"
)
func myHandler(ctx iris.Context) {
user := ctx.Values().Get("jwt").(*jwt.Token)
ctx.Writef("This is an authenticated request\n")
ctx.Writef("Claim content:\n")
ctx.Writef("%s", user.Signature)
}
func main() {
app := iris.New()
jwtHandler := jwtmiddleware.New(jwtmiddleware.Config{
ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
return []byte("My Secret"), nil
},
// When set, the middleware verifies that tokens are signed with the specific signing algorithm
// If the signing method is not constant the ValidationKeyGetter callback can be used to implement additional checks
// Important to avoid security issues described here: https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/
SigningMethod: jwt.SigningMethodHS256,
})
app.Use(jwtHandler.Serve)
app.Get("/ping", myHandler)
app.Run(iris.Addr("localhost:3001"))
} // don't forget to look ../jwt_test.go to see how to set your own custom claims

View File

@ -1,24 +0,0 @@
package main
import (
"github.com/kataras/iris"
"github.com/iris-contrib/middleware/newrelic"
)
func main() {
app := iris.New()
config := newrelic.Config("APP_SERVER_NAME", "NEWRELIC_LICENSE_KEY")
config.Enabled = true
m, err := newrelic.New(config)
if err != nil {
app.Logger().Fatal(err)
}
app.Use(m.ServeHTTP)
app.Get("/", func(ctx iris.Context) {
ctx.Writef("success!\n")
})
app.Run(iris.Addr(":8080"))
}

View File

@ -1,40 +0,0 @@
package main
import (
"math/rand"
"time"
"github.com/kataras/iris"
prometheusMiddleware "github.com/iris-contrib/middleware/prometheus"
"github.com/prometheus/client_golang/prometheus"
)
func main() {
app := iris.New()
m := prometheusMiddleware.New("serviceName", 300, 1200, 5000)
app.Use(m.ServeHTTP)
app.OnErrorCode(iris.StatusNotFound, func(ctx iris.Context) {
// error code handlers are not sharing the same middleware as other routes, so we have
// to call them inside their body.
m.ServeHTTP(ctx)
ctx.Writef("Not Found")
})
app.Get("/", func(ctx iris.Context) {
sleep := rand.Intn(4999) + 1
time.Sleep(time.Duration(sleep) * time.Millisecond)
ctx.Writef("Slept for %d milliseconds", sleep)
})
app.Get("/metrics", iris.FromStd(prometheus.Handler()))
// http://localhost:8080/
// http://localhost:8080/anotfound
// http://localhost:8080/metrics
app.Run(iris.Addr(":8080"))
}

View File

@ -1,38 +0,0 @@
package main
import (
"github.com/kataras/iris"
"github.com/iris-contrib/middleware/secure"
)
func main() {
s := secure.New(secure.Options{
AllowedHosts: []string{"ssl.example.com"}, // AllowedHosts is a list of fully qualified domain names that are allowed. Default is empty list, which allows any and all host names.
SSLRedirect: true, // If SSLRedirect is set to true, then only allow HTTPS requests. Default is false.
SSLTemporaryRedirect: false, // If SSLTemporaryRedirect is true, the a 302 will be used while redirecting. Default is false (301).
SSLHost: "ssl.example.com", // SSLHost is the host name that is used to redirect HTTP requests to HTTPS. Default is "", which indicates to use the same host.
SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, // SSLProxyHeaders is set of header keys with associated values that would indicate a valid HTTPS request. Useful when using Nginx: `map[string]string{"X-Forwarded-Proto": "https"}`. Default is blank map.
STSSeconds: 315360000, // STSSeconds is the max-age of the Strict-Transport-Security header. Default is 0, which would NOT include the header.
STSIncludeSubdomains: true, // If STSIncludeSubdomains is set to true, the `includeSubdomains` will be appended to the Strict-Transport-Security header. Default is false.
STSPreload: true, // If STSPreload is set to true, the `preload` flag will be appended to the Strict-Transport-Security header. Default is false.
ForceSTSHeader: false, // STS header is only included when the connection is HTTPS. If you want to force it to always be added, set to true. `IsDevelopment` still overrides this. Default is false.
FrameDeny: true, // If FrameDeny is set to true, adds the X-Frame-Options header with the value of `DENY`. Default is false.
CustomFrameOptionsValue: "SAMEORIGIN", // CustomFrameOptionsValue allows the X-Frame-Options header value to be set with a custom value. This overrides the FrameDeny option.
ContentTypeNosniff: true, // If ContentTypeNosniff is true, adds the X-Content-Type-Options header with the value `nosniff`. Default is false.
BrowserXSSFilter: true, // If BrowserXssFilter is true, adds the X-XSS-Protection header with the value `1; mode=block`. Default is false.
ContentSecurityPolicy: "default-src 'self'", // ContentSecurityPolicy allows the Content-Security-Policy header value to be set with a custom value. Default is "".
PublicKey: `pin-sha256="base64+primary=="; pin-sha256="base64+backup=="; max-age=5184000; includeSubdomains; report-uri="https://www.example.com/hpkp-report"`, // PublicKey implements HPKP to prevent MITM attacks with forged certificates. Default is "".
IsDevelopment: true, // This will cause the AllowedHosts, SSLRedirect, and STSSeconds/STSIncludeSubdomains options to be ignored during development. When deploying to production, be sure to set this to false.
})
app := iris.New()
app.Use(s.Serve)
app.Get("/home", func(ctx iris.Context) {
ctx.Writef("Hello from /home")
})
app.Run(iris.Addr(":8080"))
}

View File

@ -1,31 +0,0 @@
package main
import (
"github.com/kataras/iris"
"github.com/didip/tollbooth"
"github.com/iris-contrib/middleware/tollboothic"
)
// $ go get github.com/didip/tollbooth
// $ go run main.go
func main() {
app := iris.New()
limiter := tollbooth.NewLimiter(1, nil)
//
// or create a limiter with expirable token buckets
// This setting means:
// create a 1 request/second limiter and
// every token bucket in it will expire 1 hour after it was initially set.
// limiter := tollbooth.NewLimiter(1, &limiter.ExpirableOptions{DefaultExpirationTTL: time.Hour})
app.Get("/", tollboothic.LimitHandler(limiter), func(ctx iris.Context) {
ctx.HTML("<b>Hello, world!</b>")
})
app.Run(iris.Addr(":8080"))
}
// Read more at: https://github.com/didip/tollbooth

View File

@ -0,0 +1 @@
just a text.

View File

@ -0,0 +1 @@
<h1>Hello App2App3 index</h1>

View File

@ -0,0 +1 @@
<h1>Hello App2 index</h1>

View File

@ -4,38 +4,48 @@ import (
"github.com/kataras/iris"
)
func main() {
func newApp() *iris.Application {
app := iris.New()
app.Favicon("./assets/favicon.ico")
// enable gzip, optionally:
// if used before the `StaticXXX` handlers then
// the content byte range feature is gone.
// recommend: turn off for large files especially
// when server has low memory,
// turn on for medium-sized files
// or for large-sized files if they are zipped already,
// i.e "zippedDir/file.gz"
//
// app.Use(iris.Gzip)
// first parameter is the request path
// second is the system directory
//
// app.StaticWeb("/css", "./assets/css")
// app.StaticWeb("/js", "./assets/js")
//
app.StaticWeb("/static", "./assets")
// app.HandleDir("/css", "./assets/css")
// app.HandleDir("/js", "./assets/js")
app.HandleDir("/static", "./assets", iris.DirOptions{
// Defaults to "/index.html", if request path is ending with **/*/$IndexName
// then it redirects to **/*(/) which another handler is handling it,
// that another handler, called index handler, is auto-registered by the framework
// if end developer does not managed to handle it by hand.
IndexName: "/index.html",
// When files should served under compression.
Gzip: false,
// List the files inside the current requested directory if `IndexName` not found.
ShowList: false,
// If `ShowList` is true then this function will be used instead of the default one to show the list of files of a current requested directory(dir).
// DirList: func(ctx context.Context, dirName string, dir http.File) error { ... }
//
// Optional validator that loops through each requested resource.
// AssetValidator: func(ctx iris.Context, name string) bool { ... }
})
// You can also register any index handler manually, order of registration does not matter:
// app.Get("/static", [...custom middleware...], func(ctx iris.Context) {
// [...custom code...]
// ctx.ServeFile("./assets/index.html", false)
// })
// http://localhost:8080/static
// http://localhost:8080/static/css/main.css
// http://localhost:8080/static/js/jquery-2.1.1.js
// http://localhost:8080/static/favicon.ico
app.Run(iris.Addr(":8080"))
// Note:
// Routing doesn't allows something .StaticWeb("/", "./assets")
//
// To see how you can wrap the router in order to achieve
// wildcard on root path, see "single-page-application".
return app
}
func main() {
app := newApp()
app.Run(iris.Addr(":8080"))
}

View File

@ -0,0 +1,93 @@
package main
import (
"io/ioutil"
"path/filepath"
"strings"
"testing"
"github.com/kataras/iris/httptest"
)
type resource string
func (r resource) contentType() string {
switch filepath.Ext(r.String()) {
case ".js":
return "application/javascript"
case ".css":
return "text/css"
case ".ico":
return "image/x-icon"
case ".html", "":
return "text/html"
default:
return "text/plain"
}
}
func (r resource) String() string {
return string(r)
}
func (r resource) strip(strip string) string {
s := r.String()
return strings.TrimPrefix(s, strip)
}
func (r resource) loadFromBase(dir string) string {
filename := r.String()
filename = r.strip("/static")
if filepath.Ext(filename) == "" {
// root /.
filename = filename + "/index.html"
}
fullpath := filepath.Join(dir, filename)
b, err := ioutil.ReadFile(fullpath)
if err != nil {
panic(fullpath + " failed with error: " + err.Error())
}
result := string(b)
return result
}
func TestFileServerBasic(t *testing.T) {
var urls = []resource{
"/static/css/main.css",
"/static/js/jquery-2.1.1.js",
"/static/favicon.ico",
"/static/app2",
"/static/app2/app2app3",
"/static",
}
app := newApp()
// route := app.GetRouteReadOnly("GET/{file:path}")
// if route == nil {
// app.Logger().Fatalf("expected a route to serve files")
// }
// if expected, got := "./assets", route.StaticDir(); expected != got {
// app.Logger().Fatalf("expected route's static directory to be: '%s' but got: '%s'", expected, got)
// }
// if !route.StaticDirContainsIndex() {
// app.Logger().Fatalf("epxected ./assets to contain an %s file", "/index.html")
// }
e := httptest.New(t, app)
for _, u := range urls {
url := u.String()
contents := u.loadFromBase("./assets")
e.GET(url).Expect().
Status(httptest.StatusOK).
ContentType(u.contentType(), app.ConfigurationReadOnly().GetCharset()).
Body().Equal(contents)
}
}

View File

@ -14,8 +14,14 @@ import (
// See `file-server/embedding-gziped-files-into-app` example as well.
func newApp() *iris.Application {
app := iris.New()
app.Logger().SetLevel("debug")
app.StaticEmbedded("/static", "./assets", Asset, AssetNames)
app.HandleDir("/static", "./assets", iris.DirOptions{
Asset: Asset,
AssetInfo: AssetInfo,
AssetNames: AssetNames,
ShowList: true,
})
return app
}

View File

@ -66,12 +66,21 @@ var urls = []resource{
}
// if bindata's values matches with the assets/... contents
// and secondly if the StaticEmbedded had successfully registered
// and secondly if the HandleDir had successfully registered
// the routes and gave the correct response.
func TestEmbeddingFilesIntoApp(t *testing.T) {
app := newApp()
e := httptest.New(t, app)
route := app.GetRouteReadOnly("GET/static/{file:path}")
if route == nil {
t.Fatalf("expected a route to serve embedded files")
}
if len(route.StaticSites()) > 0 {
t.Fatalf("not expected a static site, the ./assets directory or its subdirectories do not contain any index.html")
}
if runtime.GOOS != "windows" {
// remove the embedded static favicon for !windows,
// it should be built for unix-specific in order to be work

View File

@ -16,12 +16,13 @@ import (
func newApp() *iris.Application {
app := iris.New()
// Note the `GzipAsset` and `GzipAssetNames` are different from `go-bindata`'s `Asset` and `AssetNames,
// that means that you can use both `go-bindata` and `bindata` tools,
// the `go-bindata` can be used for the view engine's `Binary` method
// and the `bindata` with the `StaticEmbeddedGzip` (x8 times faster than the StaticEmbeded with `go-bindata`).
app.StaticEmbeddedGzip("/static", "./assets", GzipAsset, GzipAssetNames)
// Note the `GzipAsset` and `GzipAssetNames` are different from `go-bindata`'s `Asset`,
// do not set the `Gzip` option to true, it's already managed by the kataras/bindata.
app.HandleDir("/static", "./assets", iris.DirOptions{
Asset: GzipAsset,
AssetInfo: GzipAssetInfo,
AssetNames: GzipAssetNames,
})
return app
}

View File

@ -67,7 +67,7 @@ var urls = []resource{
}
// if bindata's values matches with the assets/... contents
// and secondly if the StaticEmbedded had successfully registered
// and secondly if the HandleDir had successfully registered
// the routes and gave the correct response.
func TestEmbeddingGzipFilesIntoApp(t *testing.T) {
app := newApp()
@ -89,9 +89,10 @@ func TestEmbeddingGzipFilesIntoApp(t *testing.T) {
if expected, got := response.Raw().StatusCode, httptest.StatusOK; expected != got {
t.Fatalf("[%d] of '%s': expected %d status code but got %d", i, url, expected, got)
}
rawBody := response.Body().Raw()
func() {
reader, err := gzip.NewReader(bytes.NewBuffer(response.Content))
reader, err := gzip.NewReader(strings.NewReader(rawBody))
defer reader.Close()
if err != nil {
t.Fatalf("[%d] of '%s': %v", i, url, err)

View File

@ -20,15 +20,7 @@ func newApp() *iris.Application {
ctx.View("index.html")
})
// or just serve index.html as it is:
// app.Get("/{f:path}", func(ctx iris.Context) {
// ctx.ServeFile("index.html", false)
// })
assetHandler := app.StaticHandler("./public", false, false)
// as an alternative of SPA you can take a look at the /routing/dynamic-path/root-wildcard
// example too
app.SPA(assetHandler)
app.HandleDir("/", "./public")
return app
}

View File

@ -9,11 +9,21 @@ import "github.com/kataras/iris"
func newApp() *iris.Application {
app := iris.New()
app.OnErrorCode(404, func(ctx iris.Context) {
app.OnErrorCode(iris.StatusNotFound, func(ctx iris.Context) {
ctx.Writef("404 not found here")
})
app.StaticEmbedded("/", "./public", Asset, AssetNames)
app.HandleDir("/", "./public", iris.DirOptions{
Asset: Asset,
AssetInfo: AssetInfo,
AssetNames: AssetNames,
// IndexName: "index.html", // default.
// If you want to show a list of embedded files when inside a directory without an index file:
// ShowList: true,
// DirList: func(ctx iris.Context, dirName string, f http.File) error {
// // [Optional, custom code to show the html list].
// }
})
// Note:
// if you want a dynamic index page then see the file-server/embedded-single-page-application

View File

@ -22,16 +22,11 @@ func newApp() *iris.Application {
ctx.View("index.html")
})
assetHandler := iris.StaticEmbeddedHandler("./public", Asset, AssetNames, false) // keep that false if you use the `go-bindata` tool.
// as an alternative of SPA you can take a look at the /routing/dynamic-path/root-wildcard
// example too
// or
// app.StaticEmbedded if you don't want to redirect on index.html and simple serve your SPA app (recommended).
// public/index.html is a dynamic view, it's handlded by root,
// and we don't want to be visible as a raw data, so we will
// the return value of `app.SPA` to modify the `IndexNames` by;
app.SPA(assetHandler).AddIndexName("index.html")
app.HandleDir("/", "./public", iris.DirOptions{
Asset: Asset,
AssetInfo: AssetInfo,
AssetNames: AssetNames,
})
return app
}
@ -45,11 +40,3 @@ func main() {
// http://localhost:8080/css/main.css
app.Run(iris.Addr(":8080"))
}
// Note that app.Use/UseGlobal/Done will be executed
// only to the registered routes like our index (app.Get("/", ..)).
// The file server is clean, but you can still add middleware to that by wrapping its "assetHandler".
//
// With this method, unlike StaticWeb("/" , "./public") which is not working by-design anymore,
// all custom http errors and all routes are working fine with a file server that is registered
// to the root path of the server.

View File

@ -10,7 +10,7 @@ import (
func main() {
app := iris.New()
app.Logger().SetLevel("debug")
// Optionally, add two built'n handlers
// Optionally, add two builtin handlers
// that can recover from any http-relative panics
// and log the requests to the terminal.
app.Use(recover.New())

View File

@ -1,6 +1,6 @@
# hero: basic
## 1. Path Parameters - Built'n Dependencies
## 1. Path Parameters - Builtin Dependencies
![](https://github.com/kataras/explore/raw/master/iris/hero/hero-1-monokai.png)

View File

@ -19,7 +19,7 @@ var helloView = hero.View{
// Hello will return a predefined view with bind data.
//
// `hero.Result` is just an interface with a `Dispatch` function.
// `hero.Response` and `hero.View` are the built'n result type dispatchers
// `hero.Response` and `hero.View` are the builtin result type dispatchers
// you can even create custom response dispatchers by
// implementing the `github.com/kataras/iris/hero#Result` interface.
func Hello() hero.Result {

View File

@ -0,0 +1,7 @@
module github.com/kataras/iris/_examples/http-listening/http3-quic
go 1.12
require (
github.com/prometheus/client_golang v1.0.0
)

View File

@ -0,0 +1,18 @@
-----BEGIN CERTIFICATE-----
MIIC+zCCAeOgAwIBAgIJAI5gi8BzcdQgMA0GCSqGSIb3DQEBBQUAMBQxEjAQBgNV
BAMMCWxvY2FsaG9zdDAeFw0xOTA3MDkxMjExNDBaFw0yOTA3MDYxMjExNDBaMBQx
EjAQBgNVBAMMCWxvY2FsaG9zdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC
ggEBAM1eSGwoYznwYtt+/hrv9o4FYxJFlxIMX6WN3c2y3rr8uOwExkz2RuU9SzgF
qn0ctP1DoIKWNO0/L5j5Bjy2do0k8wHYPbTqb9zG64NGZj1lhkHgYXWyCD9U41DX
V1DiJ2JiCRBadowFRRf3/KIPf3xnrCBSCoQwdfIeJJtAF9El2/TnTrGq9N98FJqR
dCNyi+zY/iuymcA3aDOyYNjxSiuV//7ONEql5dxvRlhkjCHgrQ/rIbH/lSFAS+NG
H/6ksEBX2+Q1LlQBaFiGeEnjVpCymrRfADw7bKyqMav39Nndw4UZ1r5MSG20YtXM
dE4lA6VfAKzIZs2n87WF7OO8Y2sCAwEAAaNQME4wHQYDVR0OBBYEFKYItamcYz4Z
NiDy3I2zflU4A7ywMB8GA1UdIwQYMBaAFKYItamcYz4ZNiDy3I2zflU4A7ywMAwG
A1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBACSoSrEArlgPJ1ftlSMkThUR
atTqJ/yB0rSyRxsct0C04qX880VP7avnKc0UhaDruXRjdAVn4X8KI+j6azQSKT40
KRSVBinnonE0D4DBMCUVDFtkBW3FZJXAYyIYdF/6J3Khn/ksm7VDcVxYI1rjg87B
U6aJytOkoGA2WGQOB1L0HtnTsarg/SKP/LSDUFT+XK6zTE7uogAUrpbwlpIaxc+8
3jXvgxEdPj9Rq9Nt8/zjCkCGB2EusPPnqxcbqZb5WcGPCIlg3ChKq7vpaQld6KqG
70jT7BZ2fqWSVJ5szRoS8WpKy1SZEx/+AA7VojMzkkw4RLb66zr1v7029b51ol4=
-----END CERTIFICATE-----

View File

@ -0,0 +1,27 @@
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAzV5IbChjOfBi237+Gu/2jgVjEkWXEgxfpY3dzbLeuvy47ATG
TPZG5T1LOAWqfRy0/UOggpY07T8vmPkGPLZ2jSTzAdg9tOpv3Mbrg0ZmPWWGQeBh
dbIIP1TjUNdXUOInYmIJEFp2jAVFF/f8og9/fGesIFIKhDB18h4km0AX0SXb9OdO
sar033wUmpF0I3KL7Nj+K7KZwDdoM7Jg2PFKK5X//s40SqXl3G9GWGSMIeCtD+sh
sf+VIUBL40Yf/qSwQFfb5DUuVAFoWIZ4SeNWkLKatF8APDtsrKoxq/f02d3DhRnW
vkxIbbRi1cx0TiUDpV8ArMhmzafztYXs47xjawIDAQABAoIBADvaKok7DBAquuT1
keEP5m9lqoX8uhaMfKOnQOleJAOi+9HtYk2zyN2ui2l8XT+xSh41w2XLmQk7zQds
LCEtnEduaVQ0TWeYm5lgb+sGbW2fVQ2F82F1zWmHt+grmkr8XjYSFEor0zjjoEtn
/rzMf38mR8fzoRT9eqJhnpGQkGBnfo0SyDKIDu9yYFM7yJ5s4KOTVsMGfavjQYgJ
ssQm0KQTo8HbYHieS6drEYFRwAgT8U1NFoVq24yU+Voyy7CR5rjfOsO9gSyStVSH
nTkePmSIcpeQBfpfT3jh+STSS12eqhFCx1SqAUptUehQpOJhnWAyeSGjVLlrHqDR
bCtSWCECgYEA62J2AC8bRQ8omoEOc5h1/kwPTcLYjhOCxwwU8ky7qve173MYZUeT
dxWZx3haahccPyUKtsiGBdKYyYKSOIJMSMmwkG4uy6r5nhwNV+btEIL6Npj+XKMe
PaATA4gBLRQNwcbUlZWLYc0Y6CXFnPA+atEa7EOEBfdgUqHOym1HsAUCgYEA31rU
GPyv8R7Z1UXmxu70M8RwxKS4XhlP7RRg3Zuuqx6WWX4M85Np3wS4UWgQjGKICwoM
D4XKZQOya5p+v7a1RUZt/OD6eJ0TjypW5fBmK2yvBUQkQCsVcFjBL3F+yv2Yk1sh
KlPky4wXpDcmWXGmesgmyhpKIwL+qXEAJEaL0K8CgYABWqKlI6A7iHfKU726ioD7
QoLABsPqJVCWRoqETk6yEBS62OWmB4Bgqf4leJrEi3d9IYBrRsIGnIyGdDrVGmLH
9GkQm6GnSEeBUlX9UHXCp4467CxiagnNfvM9DPY8xSXDHJqydZbErEJda4I0gelK
AgPuogDLa/3g289tuK015QKBgQDKcj9Qrqiiur3jC8rTgX8i9OjptAvQbsz9LL1n
4FZ/j+fjEdeXZ4RMurB+SP7G4ABDUUYBQ9lhmeo8kfpUtryzH9VNonYkoOs7lrrR
DAbvUUGKWmspJmP2QtxHrm2ofBexaKY1AXmd7Ur4c2x1IggtvgE6qn2MIojE+EGS
n8bWzQKBgQClc/j4GYNNMUYOknxXMH/ec8PBDUtn098YuFL+s7DmRHimtkkjRo1A
BtV7F8KpLruWohxXWy4QZ6HsAO255gIJ8DCbEAFCj96EHNx8KADSm3qbslu2fIB0
zCsVaETGNAjV/d5hAEdYmgynCY49gNXV55ehV1UqzFoEfZVM9j5hUg==
-----END RSA PRIVATE KEY-----

View File

@ -0,0 +1,29 @@
package main
import (
"github.com/kataras/iris"
"github.com/lucas-clemente/quic-go/http3"
)
/*
$ go get -u github.com/lucas-clemente/quic-go/...
# or if you're using GO MODULES:
$ go get github.com/lucas-clemente/quic-go@master
*/
func main() {
app := iris.New()
app.Get("/", func(ctx iris.Context) {
ctx.Writef("Hello from Index")
})
// app.Configure(iris.WithOptimizations, or any other core config here)
// app.Build()
// http3.ListenAndServe(":443", "./localhost.cert", "./localhost.key", app)
// OR:
app.Run(iris.Raw(func() error {
return http3.ListenAndServe(":443", "./localhost.cert", "./localhost.key", app)
}))
}

View File

@ -0,0 +1 @@
![tunneling_screenshot.png](tunneling_screenshot.png)

View File

@ -0,0 +1,36 @@
package main
import "github.com/kataras/iris"
func main() {
app := iris.New()
app.Get("/", func(ctx iris.Context) {
ctx.HTML("<h1>Hello World!</h1>")
// Will print the ngrok public domain
// that your app is using to be served online.
ctx.Writef("From: %s",
ctx.Application().ConfigurationReadOnly().GetVHost())
})
app.Run(iris.Addr(":8080"), iris.WithTunneling)
/* The full configuration can be set as:
app.Run(iris.Addr(":8080"), iris.WithConfiguration(
iris.Configuration{
Tunneling: iris.TunnelingConfiguration{
AuthToken: "my-ngrok-auth-client-token",
Bin: "/bin/path/for/ngrok",
Region: "eu",
WebInterface: "127.0.0.1:4040",
Tunnels: []iris.Tunnel{
{
Name: "MyApp",
Addr: ":8080",
},
},
},
}))
*/
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 164 KiB

View File

@ -22,7 +22,7 @@ func main() {
// to start a new server listening at :80 and redirects
// to the secure address, then:
target, _ := url.Parse("https://127.0.0.1:443")
go host.NewRedirection("127.0.0.1:80", target, 301).ListenAndServe()
go host.NewRedirection("127.0.0.1:80", target, iris.StatusMovedPermanently).ListenAndServe()
// start the server (HTTPS) on port 443, this is a blocking func
app.Run(iris.TLS("127.0.0.1:443", "mycert.cert", "mykey.key"))

View File

@ -0,0 +1,60 @@
package main
import (
"github.com/kataras/iris"
)
func main() {
app := iris.New()
app.Post("/", logAllBody, logJSON, logFormValues, func(ctx iris.Context) {
body, err := ctx.GetBody()
if err != nil {
ctx.Writef("error while reading the requested body: %v", err)
return
}
if len(body) == 0 {
ctx.WriteString(`The body was empty
or iris.WithoutBodyConsumptionOnUnmarshal option is missing from app.Run.
Check the terminal window for any queries logs.`)
} else {
ctx.WriteString("OK body is still:\n")
ctx.Write(body)
}
})
// With ctx.UnmarshalBody, ctx.ReadJSON, ctx.ReadXML, ctx.ReadForm, ctx.FormValues
// and ctx.GetBody methods the default golang and net/http behavior
// is to consume the readen data - they are not available on any next handlers in the chain -
// to change that behavior just pass the `WithoutBodyConsumptionOnUnmarshal` option.
app.Run(iris.Addr(":8080"), iris.WithoutBodyConsumptionOnUnmarshal)
}
func logAllBody(ctx iris.Context) {
body, err := ctx.GetBody()
if err == nil && len(body) > 0 {
ctx.Application().Logger().Infof("logAllBody: %s", string(body))
}
ctx.Next()
}
func logJSON(ctx iris.Context) {
var p interface{}
if err := ctx.ReadJSON(&p); err == nil {
ctx.Application().Logger().Infof("logJSON: %#+v", p)
}
ctx.Next()
}
func logFormValues(ctx iris.Context) {
values := ctx.FormValues()
if values != nil {
ctx.Application().Logger().Infof("logFormValues: %v", values)
}
ctx.Next()
}

View File

@ -2,19 +2,56 @@ package main
import (
"fmt"
"io"
"os"
"runtime"
"strings"
"time"
"github.com/kataras/iris"
"github.com/kataras/iris/middleware/logger"
"github.com/kataras/golog"
)
const deleteFileOnExit = false
func newRequestLogger(newWriter io.Writer) iris.Handler {
c := logger.Config{}
// we don't want to use the logger
// to log requests to assets and etc
c.AddSkipper(func(ctx iris.Context) bool {
path := ctx.Path()
for _, ext := range excludeExtensions {
if strings.HasSuffix(path, ext) {
return true
}
}
return false
})
c.LogFuncCtx = func(ctx iris.Context, latency time.Duration) {
datetime := time.Now().Format(ctx.Application().ConfigurationReadOnly().GetTimeFormat())
customHandlerMessage := ctx.Values().GetString("log_message")
file, line := ctx.HandlerFileLine()
source := fmt.Sprintf("%s:%d", file, line)
// this will just append a line without an array of javascript objects, readers of this file should read one line per log javascript object,
// however, you can improve it even more, this is just a simple example on how to use the `LogFuncCtx`.
jsonStr := fmt.Sprintf(`{"datetime":"%s","level":"%s","source":"%s","latency": "%s","status": %d,"method":"%s","path":"%s","message":"%s"}`,
datetime, "INFO", source, latency.String(), ctx.GetStatusCode(), ctx.Method(), ctx.Path(), customHandlerMessage)
fmt.Fprintln(newWriter, jsonStr)
}
return logger.New(c)
}
func h(ctx iris.Context) {
ctx.Values().Set("log_message", "something to give more info to the request logger")
ctx.Writef("Hello from %s", ctx.Path())
}
func main() {
app := iris.New()
@ -26,56 +63,21 @@ func main() {
}
}()
// Handle the logs by yourself using the `app.Logger#Handle` method.
// Return true if that handled, otherwise will print to the screen.
// You can also use the `app.Logger#SetOutput/AddOutput` to change or add
// multi (io.Writer) outputs if you just want to print the message
// somewhere else than the terminal screen.
app.Logger().Handle(func(l *golog.Log) bool {
_, fn, line, _ := runtime.Caller(5)
var (
// formatted date string based on the `golog#TimeFormat`, which can be customized.
// Or use the golog.Log#Time field to get the exact time.Time instance.
datetime = l.FormatTime()
// the log's message level.
level = golog.GetTextForLevel(l.Level, false)
// the log's message.
message = l.Message
// the source code line of where it is called,
// this can differ on your app, see runtime.Caller(%d).
source = fmt.Sprintf("%s#%d", fn, line)
)
// You can always use a custom json structure and json.Marshal and logFile.Write(its result)
// but it is faster to just build your JSON string by yourself as we do below.
jsonStr := fmt.Sprintf(`{"datetime":"%s","level":"%s","message":"%s","source":"%s"}`, datetime, level, message, source)
fmt.Fprintln(logFile, jsonStr)
/* Example output:
{"datetime":"2018/10/31 13:13","level":"[INFO]","message":"My server started","source":"c:/mygopath/src/github.com/kataras/iris/_examples/http_request/request-logger/request-logger-file-json/main.go#71"}
*/
return true
})
r := newRequestLogger()
r := newRequestLogger(logFile)
app.Use(r)
app.OnAnyErrorCode(r, func(ctx iris.Context) {
ctx.HTML("<h1> Error: Please try <a href ='/'> this </a> instead.</h1>")
})
h := func(ctx iris.Context) {
ctx.Writef("Hello from %s", ctx.Path())
}
app.Get("/", h)
app.Get("/1", h)
app.Get("/2", h)
app.Logger().Info("My server started")
app.Get("/", h)
// http://localhost:8080
// http://localhost:8080/1
// http://localhost:8080/2
@ -92,29 +94,6 @@ var excludeExtensions = [...]string{
".svg",
}
func newRequestLogger() iris.Handler {
c := logger.Config{
Status: true,
IP: true,
Method: true,
Path: true,
}
// we don't want to use the logger
// to log requests to assets and etc
c.AddSkipper(func(ctx iris.Context) bool {
path := ctx.Path()
for _, ext := range excludeExtensions {
if strings.HasSuffix(path, ext) {
return true
}
}
return false
})
return logger.New(c)
}
// get a filename based on the date, file logs works that way the most times
// but these are just a sugar.
func todayFilename() string {

View File

@ -85,10 +85,10 @@ func newRequestLogger() (h iris.Handler, close func() error) {
return err
}
c.LogFunc = func(now time.Time, latency time.Duration, status, ip, method, path string, message interface{}, headerMessage interface{}) {
output := logger.Columnize(now.Format("2006/01/02 - 15:04:05"), latency, status, ip, method, path, message, headerMessage)
c.LogFunc = func(endTime time.Time, latency time.Duration, status, ip, method, path string, message interface{}, headerMessage interface{}) {
output := logger.Columnize(endTime.Format("2006/01/02 - 15:04:05"), latency, status, ip, method, path, message, headerMessage)
logFile.Write([]byte(output))
}
} // or make use of the `LogFuncCtx`, see the '../request-logger-file-json' example for more.
// we don't want to use the logger
// to log requests to assets and etc

View File

@ -59,6 +59,19 @@ func newApp() *iris.Application {
"key2", fromSecondFileValue)
})
// using in inside your templates:
view := iris.HTML("./templates", ".html")
app.RegisterView(view)
app.Get("/templates", func(ctx iris.Context) {
ctx.View("index.html", iris.Map{
"tr": ctx.Translate,
})
// it will return "hello, iris"
// when {{call .tr "hi" "iris"}}
})
//
return app
}

View File

@ -0,0 +1 @@
{{call .tr "hi" "iris"}}

View File

@ -1,146 +0,0 @@
# MVC
![](https://github.com/kataras/iris/raw/master/_examples/mvc/web_mvc_diagram.png)
Iris has **first-class support for the MVC pattern**, you'll not find
these stuff anywhere else in the Go world.
Iris supports Request data, Models, Persistence Data and Binding
with the fastest possible execution.
## Characteristics
All HTTP Methods are supported, for example if want to serve `GET`
then the controller should have a function named `Get()`,
you can define more than one method function to serve in the same Controller.
Serve custom controller's struct's methods as handlers with custom paths(even with regex parametermized path)
via the `BeforeActivation` custom event callback, per-controller. Example:
```go
import (
"github.com/kataras/iris"
"github.com/kataras/iris/mvc"
)
func main() {
app := iris.New()
mvc.Configure(app.Party("/root"), myMVC)
app.Run(iris.Addr(":8080"))
}
func myMVC(app *mvc.Application) {
// app.Register(...)
// app.Router.Use/UseGlobal/Done(...)
app.Handle(new(MyController))
}
type MyController struct {}
func (m *MyController) BeforeActivation(b mvc.BeforeActivation) {
// b.Dependencies().Add/Remove
// b.Router().Use/UseGlobal/Done // and any standard API call you already know
// 1-> Method
// 2-> Path
// 3-> The controller's function name to be parsed as handler
// 4-> Any handlers that should run before the MyCustomHandler
b.Handle("GET", "/something/{id:long}", "MyCustomHandler", anyMiddleware...)
}
// GET: http://localhost:8080/root
func (m *MyController) Get() string { return "Hey" }
// GET: http://localhost:8080/root/something/{id:long}
func (m *MyController) MyCustomHandler(id int64) string { return "MyCustomHandler says Hey" }
```
Persistence data inside your Controller struct (share data between requests)
by defining services to the Dependencies or have a `Singleton` controller scope.
Share the dependencies between controllers or register them on a parent MVC Application, and ability
to modify dependencies per-controller on the `BeforeActivation` optional event callback inside a Controller,
i.e `func(c *MyController) BeforeActivation(b mvc.BeforeActivation) { b.Dependencies().Add/Remove(...) }`.
Access to the `Context` as a controller's field(no manual binding is neede) i.e `Ctx iris.Context` or via a method's input argument, i.e `func(ctx iris.Context, otherArguments...)`.
Models inside your Controller struct (set-ed at the Method function and rendered by the View).
You can return models from a controller's method or set a field in the request lifecycle
and return that field to another method, in the same request lifecycle.
Flow as you used to, mvc application has its own `Router` which is a type of `iris/router.Party`, the standard iris api.
`Controllers` can be registered to any `Party`, including Subdomains, the Party's begin and done handlers work as expected.
Optional `BeginRequest(ctx)` function to perform any initialization before the method execution,
useful to call middlewares or when many methods use the same collection of data.
Optional `EndRequest(ctx)` function to perform any finalization after any method executed.
Inheritance, recursively, see for example our `mvc.SessionController`, it has the `Session *sessions.Session` and `Manager *sessions.Sessions` as embedded fields
which are filled by its `BeginRequest`, [here](https://github.com/kataras/iris/blob/master/mvc/session_controller.go).
This is just an example, you could use the `sessions.Session` as a dependency to the MVC Application, i.e
`mvcApp.Register(sessions.New(sessions.Config{Cookie: "iris_session_id"}).Start)`.
Access to the dynamic path parameters via the controller's methods' input arguments, no binding is needed.
When you use the Iris' default syntax to parse handlers from a controller, you need to suffix the methods
with the `By` word, uppercase is a new sub path. Example:
If `mvc.New(app.Party("/user")).Handle(new(user.Controller))`
- `func(*Controller) Get()` - `GET:/user`.
- `func(*Controller) Post()` - `POST:/user`.
- `func(*Controller) GetLogin()` - `GET:/user/login`
- `func(*Controller) PostLogin()` - `POST:/user/login`
- `func(*Controller) GetProfileFollowers()` - `GET:/user/profile/followers`
- `func(*Controller) PostProfileFollowers()` - `POST:/user/profile/followers`
- `func(*Controller) GetBy(id int64)` - `GET:/user/{param:long}`
- `func(*Controller) PostBy(id int64)` - `POST:/user/{param:long}`
If `mvc.New(app.Party("/profile")).Handle(new(profile.Controller))`
- `func(*Controller) GetBy(username string)` - `GET:/profile/{param:string}`
If `mvc.New(app.Party("/assets")).Handle(new(file.Controller))`
- `func(*Controller) GetByWildard(path string)` - `GET:/assets/{param:path}`
Supported types for method functions receivers: int, int64, bool and string.
Response via output arguments, optionally, i.e
```go
func(c *ExampleController) Get() string |
(string, string) |
(string, int) |
int |
(int, string) |
(string, error) |
error |
(int, error) |
(any, bool) |
(customStruct, error) |
customStruct |
(customStruct, int) |
(customStruct, string) |
mvc.Result or (mvc.Result, error)
```
where [mvc.Result](https://github.com/kataras/iris/blob/master/mvc/func_result.go) is an interface which contains only that function: `Dispatch(ctx iris.Context)`.
## Using Iris MVC for code reuse
By creating components that are independent of one another, developers are able to reuse components quickly and easily in other applications. The same (or similar) view for one application can be refactored for another application with different data because the view is simply handling how the data is being displayed to the user.
If you're new to back-end web development read about the MVC architectural pattern first, a good start is that [wikipedia article](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller).
## Examples
- [Hello world](hello-world/main.go) **UPDATED**
- [Session Controller](session-controller/main.go) **UPDATED**
- [Overview - Plus Repository and Service layers](overview) **UPDATED**
- [Login showcase - Plus Repository and Service layers](login) **UPDATED**
- [Singleton](singleton) **NEW**
- [Websocket Controller](websocket) **NEW**
- [Register Middleware](middleware) **NEW**
Folder structure guidelines can be found at the [_examples/#structuring](https://github.com/kataras/iris/tree/master/_examples/#structuring) section.

View File

@ -4,6 +4,7 @@ import (
"fmt"
"github.com/kataras/iris"
"github.com/kataras/iris/middleware/recover"
"github.com/kataras/iris/sessions"
"github.com/kataras/iris/mvc"
@ -11,6 +12,7 @@ import (
func main() {
app := iris.New()
app.Use(recover.New())
app.Logger().SetLevel("debug")
mvc.Configure(app.Party("/basic"), basicMVC)
@ -34,6 +36,7 @@ func basicMVC(app *mvc.Application) {
// GET: http://localhost:8080/basic
// GET: http://localhost:8080/basic/custom
// GET: http://localhost:8080/basic/custom2
app.Handle(new(basicController))
// All dependencies of the parent *mvc.Application
@ -71,7 +74,7 @@ type basicController struct {
}
func (c *basicController) BeforeActivation(b mvc.BeforeActivation) {
b.Handle("GET", "/custom", "Custom")
b.HandleMany("GET", "/custom /custom2", "Custom")
}
func (c *basicController) AfterActivation(a mvc.AfterActivation) {

View File

@ -0,0 +1,39 @@
package main
import (
"fmt"
"github.com/kataras/iris"
"github.com/kataras/iris/mvc"
)
func main() {
app := iris.New()
app.Logger().SetLevel("debug")
mvcApp := mvc.New(app)
// To all controllers, it can optionally be overridden per-controller
// if the controller contains the `HandleError(ctx iris.Context, err error)` function.
//
mvcApp.HandleError(func(ctx iris.Context, err error) {
ctx.HTML(fmt.Sprintf("<b>%s</b>", err.Error()))
})
//
mvcApp.Handle(new(myController))
// http://localhost:8080
app.Run(iris.Addr(":8080"))
}
type myController struct {
}
// overriddes the mvcApp.HandleError function.
func (c *myController) HandleError(ctx iris.Context, err error) {
ctx.HTML(fmt.Sprintf("<i>%s</i>", err.Error()))
}
func (c *myController) Get() error {
return fmt.Errorf("error here")
}

View File

@ -32,7 +32,7 @@ import (
// for the main_test.go.
func newApp() *iris.Application {
app := iris.New()
// Optionally, add two built'n handlers
// Optionally, add two builtin handlers
// that can recover from any http-relative panics
// and log the requests to the terminal.
app.Use(recover.New())

View File

@ -28,7 +28,7 @@ func main() {
Reload(true)
app.RegisterView(tmpl)
app.StaticWeb("/public", "./web/public")
app.HandleDir("/public", "./web/public")
app.OnAnyErrorCode(func(ctx iris.Context) {
ctx.ViewData("Message", ctx.Values().

View File

@ -23,7 +23,7 @@ var helloView = mvc.View{
// Get will return a predefined view with bind data.
//
// `mvc.Result` is just an interface with a `Dispatch` function.
// `mvc.Response` and `mvc.View` are the built'n result type dispatchers
// `mvc.Response` and `mvc.View` are the builtin result type dispatchers
// you can even create custom response dispatchers by
// implementing the `github.com/kataras/iris/hero#Result` interface.
func (c *HelloController) Get() mvc.Result {

View File

@ -0,0 +1,49 @@
// Package main shows how to match "/xxx.json" in MVC handler.
package main
/*
There is no MVC naming pattern for such these things,you can imagine the limitations of that.
Instead you can use the `BeforeActivation` on your controller to add more advanced routing features
(https://github.com/kataras/iris/tree/master/_examples/routing).
You can also create your own macro,
i.e: /{file:json} or macro function of a specific parameter type i.e: (/{file:string json()}).
Read the routing examples and you will gain a deeper view, there are all covered.
*/
import (
"github.com/kataras/iris"
"github.com/kataras/iris/mvc"
)
func main() {
app := iris.New()
mvcApp := mvc.New(app.Party("/module"))
mvcApp.Handle(new(myController))
// http://localhost:8080/module/xxx.json (OK)
// http://localhost:8080/module/xxx.xml (Not Found)
app.Run(iris.Addr(":8080"))
}
type myController struct{}
func (m *myController) BeforeActivation(b mvc.BeforeActivation) {
// b.Dependencies().Add/Remove
// b.Router().Use/UseGlobal/Done // and any standard API call you already know
// 1-> Method
// 2-> Path
// 3-> The controller's function name to be parsed as handler
// 4-> Any handlers that should run before the HandleJSON
// "^[a-zA-Z0-9_.-]+.json$)" to validate file-name pattern and json
// or just: ".json$" to validate suffix.
b.Handle("GET", "/{file:string regexp(^[a-zA-Z0-9_.-]+.json$))}", "HandleJSON" /*optionalMiddleware*/)
}
func (m *myController) HandleJSON(file string) string {
return "custom serving of json: " + file
}

View File

@ -63,10 +63,10 @@ func newApp() *iris.Application {
func main() {
app := newApp()
// 1. open the browser (no in private mode)
// 1. open the browser
// 2. navigate to http://localhost:8080
// 3. refresh the page some times
// 4. close the browser
// 5. re-open the browser and re-play 2.
// 5. re-open the browser (if it wasn't in private mode) and re-play 2.
app.Run(iris.Addr(":8080"))
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

View File

@ -0,0 +1,106 @@
<html>
<head>
<title>Online visitors MVC example</title>
<style>
body {
margin: 0;
font-family: -apple-system, "San Francisco", "Helvetica Neue", "Noto", "Roboto", "Calibri Light", sans-serif;
color: #212121;
font-size: 1.0em;
line-height: 1.6;
}
.container {
max-width: 750px;
margin: auto;
padding: 15px;
}
#online_visitors {
font-weight: bold;
font-size: 18px;
}
</style>
</head>
<body>
<div class="container">
<span id="online_visitors">1 online visitor</span>
</div>
<!-- the message's input -->
<input id="input" type="text" />
<!-- when clicked then a websocket event will be sent to the server, at this example we registered the 'chat' -->
<button id="sendBtn" disabled>Send</button>
<!-- the messages will be shown here -->
<pre id="output"></pre>
<!-- import the iris client-side library for browser from a CDN or locally.
However, `neffos.(min.)js` is a NPM package too so alternatively,
you can use it as dependency on your package.json and all nodejs-npm tooling become available:
see the "browserify" example for more-->
<script src="https://cdn.jsdelivr.net/npm/neffos.js@latest/dist/neffos.min.js"></script>
<script type="text/javascript">
const wsURL = "ws://localhost:8080/websocket"
var outputTxt = document.getElementById("output");
function addMessage(msg) {
outputTxt.innerHTML += msg + "\n";
}
async function runExample() {
try {
const conn = await neffos.dial(wsURL, {
default: { // "default" namespace.
_OnNamespaceConnected: function (nsConn, msg) {
if (nsConn.conn.wasReconnected()) {
addMessage("re-connected after " + nsConn.conn.reconnectTries.toString() + " trie(s)");
}
let inputTxt = document.getElementById("input");
let sendBtn = document.getElementById("sendBtn");
sendBtn.disabled = false;
sendBtn.onclick = function () {
const input = inputTxt.value;
inputTxt.value = "";
nsConn.emit("OnChat", input);
addMessage("Me: " + input);
};
addMessage("connected to namespace: " + msg.Namespace);
},
_OnNamespaceDisconnect: function (nsConn, msg) {
addMessage("disconnected from namespace: " + msg.Namespace);
},
OnChat: function (nsConn, msg) { // "OnChat" event.
console.log(msg);
addMessage(msg.Body);
},
OnVisit: function (nsConn, msg) {
const newCount = Number(msg.Body); // or parseInt.
console.log("visit websocket event with newCount of: ", newCount);
var text = "1 online visitor";
if (newCount > 1) {
text = newCount + " online visitors";
}
document.getElementById("online_visitors").innerHTML = text;
},
}
});
conn.connect("default");
} catch (err) {
console.log(err)
}
}
runExample();
</script>
</body>
</html>

View File

@ -1,6 +1,7 @@
package main
import (
"fmt"
"sync/atomic"
"github.com/kataras/iris"
@ -10,32 +11,29 @@ import (
func main() {
app := iris.New()
app.Logger().SetLevel("debug")
// load templates.
app.RegisterView(iris.HTML("./views", ".html"))
// render the ./views/index.html.
app.Get("/", func(ctx iris.Context) {
ctx.View("index.html")
})
// render the ./browser/index.html.
app.HandleDir("/", "./browser")
mvc.Configure(app.Party("/websocket"), configureMVC)
// Or mvc.New(app.Party(...)).Configure(configureMVC)
websocketAPI := app.Party("/websocket")
m := mvc.New(websocketAPI)
m.Register(
&prefixedLogger{prefix: "DEV"},
)
m.HandleWebsocket(&websocketController{Namespace: "default", Age: 42, Otherstring: "other string"})
websocketServer := websocket.New(websocket.DefaultGorillaUpgrader, m)
websocketAPI.Get("/", websocket.Handler(websocketServer))
// http://localhost:8080
app.Run(iris.Addr(":8080"))
}
func configureMVC(m *mvc.Application) {
ws := websocket.New(websocket.Config{})
// http://localhost:8080/websocket/iris-ws.js
m.Router.Any("/iris-ws.js", websocket.ClientHandler())
// This will bind the result of ws.Upgrade which is a websocket.Connection
// to the controller(s) served by the `m.Handle`.
m.Register(ws.Upgrade)
m.Handle(new(websocketController))
}
var visits uint64
func increment() uint64 {
@ -47,36 +45,74 @@ func decrement() uint64 {
}
type websocketController struct {
// Note that you could use an anonymous field as well, it doesn't matter, binder will find it.
//
// This is the current websocket connection, each client has its own instance of the *websocketController.
Conn websocket.Connection
*websocket.NSConn `stateless:"true"`
Namespace string
Age int
Otherstring string
Logger LoggerService
}
func (c *websocketController) onLeave(roomName string) {
// or
// func (c *websocketController) Namespace() string {
// return "default"
// }
func (c *websocketController) OnNamespaceDisconnect(msg websocket.Message) error {
c.Logger.Log("Disconnected")
// visits--
newCount := decrement()
// This will call the "visit" event on all clients, except the current one,
// This will call the "OnVisit" event on all clients, except the current one,
// (it can't because it's left but for any case use this type of design)
c.Conn.To(websocket.Broadcast).Emit("visit", newCount)
c.Conn.Server().Broadcast(nil, websocket.Message{
Namespace: msg.Namespace,
Event: "OnVisit",
Body: []byte(fmt.Sprintf("%d", newCount)),
})
return nil
}
func (c *websocketController) update() {
func (c *websocketController) OnNamespaceConnected(msg websocket.Message) error {
// println("Broadcast prefix is: " + c.BroadcastPrefix)
c.Logger.Log("Connected")
// visits++
newCount := increment()
// This will call the "visit" event on all clients, including the current
// This will call the "OnVisit" event on all clients, including the current one,
// with the 'newCount' variable.
//
// There are many ways that u can do it and faster, for example u can just send a new visitor
// and client can increment itself, but here we are just "showcasing" the websocket controller.
c.Conn.To(websocket.All).Emit("visit", newCount)
c.Conn.Server().Broadcast(nil, websocket.Message{
Namespace: msg.Namespace,
Event: "OnVisit",
Body: []byte(fmt.Sprintf("%d", newCount)),
})
return nil
}
func (c *websocketController) Get( /* websocket.Connection could be lived here as well, it doesn't matter */ ) {
c.Conn.OnLeave(c.onLeave)
c.Conn.On("visit", c.update)
func (c *websocketController) OnChat(msg websocket.Message) error {
ctx := websocket.GetContext(c.Conn)
// call it after all event callbacks registration.
c.Conn.Wait()
ctx.Application().Logger().Infof("[IP: %s] [ID: %s] broadcast to other clients the message [%s]",
ctx.RemoteAddr(), c, string(msg.Body))
c.Conn.Server().Broadcast(c, msg)
return nil
}
type LoggerService interface {
Log(string)
}
type prefixedLogger struct {
prefix string
}
func (s *prefixedLogger) Log(msg string) {
fmt.Printf("%s: %s\n", s.prefix, msg)
}

View File

@ -1,63 +0,0 @@
<html>
<head>
<title>Online visitors MVC example</title>
<style>
body {
margin: 0;
font-family: -apple-system, "San Francisco", "Helvetica Neue", "Noto", "Roboto", "Calibri Light", sans-serif;
color: #212121;
font-size: 1.0em;
line-height: 1.6;
}
.container {
max-width: 750px;
margin: auto;
padding: 15px;
}
#online_visitors {
font-weight: bold;
font-size: 18px;
}
</style>
</head>
<body>
<div class="container">
<span id="online_visitors">1 online visitor</span>
</div>
<script src="/websocket/iris-ws.js"></script>
<script type="text/javascript">
(function () {
var socket = new Ws("ws://localhost:8080/websocket");
socket.OnConnect(function(){
// update the rest of connected clients, including "myself" when "my" connection is 100% ready.
socket.Emit("visit");
});
socket.On("visit", function (newCount) {
console.log("visit websocket event with newCount of: ", newCount);
var text = "1 online visitor";
if (newCount > 1) {
text = newCount + " online visitors";
}
document.getElementById("online_visitors").innerHTML = text;
});
socket.OnDisconnect(function () {
document.getElementById("online_visitors").innerHTML = "you've been disconnected";
});
})();
</script>
</body>
</html>

View File

@ -0,0 +1,5 @@
# GORM
This example is pull by [#1275 PR](https://github.com/kataras/iris/pull/1275) by [@wuxiaoxiaoshen](https://github.com/wuxiaoxiaoshen).
A more complete and real-world example can be found at the <https://github.com/snowlyg/IrisApiProject> project created by [@snowlyg](https://github.com/snowlyg).

View File

@ -559,89 +559,72 @@ Example Code:
package main
import (
"net/http"
"strings"
"net/http"
"strings"
"github.com/kataras/iris"
"github.com/kataras/iris"
)
// In this example you'll just see one use case of .WrapRouter.
// 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.
//
// To see how you can serve files on root "/" without a custom wrapper
// just navigate to the "file-server/single-page-application" example.
//
// This is just for the proof of concept, you can skip this tutorial if it's too much for you.
func newApp() *iris.Application {
app := iris.New()
app.OnErrorCode(iris.StatusNotFound, func(ctx iris.Context) {
ctx.HTML("<b>Resource Not found</b>")
})
app.Get("/profile/{username}", func(ctx iris.Context) {
ctx.Writef("Hello %s", ctx.Params().Get("username"))
})
app.HandleDir("/", "./public")
myOtherHandler := func(ctx iris.Context) {
ctx.Writef("inside a handler which is fired manually by our custom router wrapper")
}
// wrap the router with a native net/http handler.
// if url does not contain any "." (i.e: .css, .js...)
// (depends on the app , you may need to add more file-server exceptions),
// then the handler will execute the router that is responsible for the
// registered routes (look "/" and "/profile/{username}")
// if not then it will serve the files based on the root "/" path.
app.WrapRouter(func(w http.ResponseWriter, r *http.Request, router http.HandlerFunc) {
path := r.URL.Path
if strings.HasPrefix(path, "/other") {
// acquire and release a context in order to use it to execute
// our custom handler
// remember: we use net/http.Handler because here we are in the "low-level", before the router itself.
ctx := app.ContextPool.Acquire(w, r)
myOtherHandler(ctx)
app.ContextPool.Release(ctx)
return
}
router.ServeHTTP(w, r) // else continue serving routes as usual.
})
return app
}
func main() {
app := iris.New()
app := newApp()
app.OnErrorCode(iris.StatusNotFound, func(ctx iris.Context) {
ctx.HTML("<b>Resource Not found</b>")
})
// http://localhost:8080
// http://localhost:8080/index.html
// http://localhost:8080/app.js
// http://localhost:8080/css/main.css
// http://localhost:8080/profile/anyusername
// http://localhost:8080/other/random
app.Run(iris.Addr(":8080"))
app.Get("/", func(ctx iris.Context) {
ctx.ServeFile("./public/index.html", false)
})
app.Get("/profile/{username}", func(ctx iris.Context) {
ctx.Writef("Hello %s", ctx.Params().Get("username"))
})
// serve files from the root "/", if we used .StaticWeb it could override
// all the routes because of the underline need of wildcard.
// Here we will see how you can by-pass this behavior
// by creating a new file server handler and
// setting up a wrapper for the router(like a "low-level" middleware)
// in order to manually check if we want to process with the router as normally
// or execute the file server handler instead.
// use of the .StaticHandler
// which is the same as StaticWeb but it doesn't
// registers the route, it just returns the handler.
fileServer := app.StaticHandler("./public", false, false)
// wrap the router with a native net/http handler.
// if url does not contain any "." (i.e: .css, .js...)
// (depends on the app , you may need to add more file-server exceptions),
// then the handler will execute the router that is responsible for the
// registered routes (look "/" and "/profile/{username}")
// if not then it will serve the files based on the root "/" path.
app.WrapRouter(func(w http.ResponseWriter, r *http.Request, router http.HandlerFunc) {
path := r.URL.Path
// Note that if path has suffix of "index.html" it will auto-permant redirect to the "/",
// so our first handler will be executed instead.
if !strings.Contains(path, ".") {
// if it's not a resource then continue to the router as normally. <-- IMPORTANT
router(w, r)
return
}
// acquire and release a context in order to use it to execute
// our file server
// remember: we use net/http.Handler because here we are in the "low-level", before the router itself.
ctx := app.ContextPool.Acquire(w, r)
fileServer(ctx)
app.ContextPool.Release(ctx)
})
// http://localhost:8080
// http://localhost:8080/index.html
// http://localhost:8080/app.js
// http://localhost:8080/css/main.css
// http://localhost:8080/profile/anyusername
app.Run(iris.Addr(":8080"))
// Note: In this example we just saw one use case,
// you may want to .WrapRouter or .Downgrade in order to bypass the iris' default router, i.e:
// you can use that method to setup custom proxies too.
//
// If you just want to serve static files on other path than root
// you can just use the StaticWeb, i.e:
// .StaticWeb("/static", "./public")
// ________________________________requestPath, systemPath
// Note: In this example we just saw one use case,
// you may want to .WrapRouter or .Downgrade in order to bypass the iris' default router, i.e:
// you can use that method to setup custom proxies too.
}
```
@ -702,6 +685,25 @@ The `iris.Context` source code can be found [here](https://github.com/kataras/ir
// context.Context is very extensible and developers can override
// its methods if that is actually needed.
type Context interface {
// BeginRequest is executing once for each request
// it should prepare the (new or acquired from pool) context's fields for the new request.
//
// To follow the iris' flow, developer should:
// 1. reset handlers to nil
// 2. reset values to empty
// 3. reset sessions to nil
// 4. reset response writer to the http.ResponseWriter
// 5. reset request to the *http.Request
// and any other optional steps, depends on dev's application type.
BeginRequest(http.ResponseWriter, *http.Request)
// EndRequest is executing once after a response to the request was sent and this context is useless or released.
//
// To follow the iris' flow, developer should:
// 1. flush the response writer's result
// 2. release the response writer
// and any other optional steps, depends on dev's application type.
EndRequest()
// ResponseWriter returns an http.ResponseWriter compatible response writer, as expected.
ResponseWriter() ResponseWriter
// ResetResponseWriter should change or upgrade the Context's ResponseWriter.
@ -709,6 +711,18 @@ type Context interface {
// Request returns the original *http.Request, as expected.
Request() *http.Request
// ResetRequest sets the Context's Request,
// It is useful to store the new request created by a std *http.Request#WithContext() into Iris' Context.
// Use `ResetRequest` when for some reason you want to make a full
// override of the *http.Request.
// Note that: when you just want to change one of each fields you can use the Request() which returns a pointer to Request,
// so the changes will have affect without a full override.
// Usage: you use a native http handler which uses the standard "context" package
// to get values instead of the Iris' Context#Values():
// r := ctx.Request()
// stdCtx := context.WithValue(r.Context(), key, val)
// ctx.ResetRequest(r.WithContext(stdCtx)).
ResetRequest(r *http.Request)
// SetCurrentRouteName sets the route's name internally,
// in order to be able to find the correct current "read-only" Route when
@ -749,7 +763,7 @@ type Context interface {
// HandlerIndex sets the current index of the
// current context's handlers chain.
// If -1 passed then it just returns the
// current handler index without change the current index.rns that index, useless return value.
// current handler index without change the current index.
//
// Look Handlers(), Next() and StopExecution() too.
HandlerIndex(n int) (currentIndex int)
@ -792,6 +806,12 @@ type Context interface {
Proceed(Handler) bool
// HandlerName returns the current handler's name, helpful for debugging.
HandlerName() string
// HandlerFileLine returns the current running handler's function source file and line information.
// Useful mostly when debugging.
HandlerFileLine() (file string, line int)
// RouteName returns the route name that this handler is running on.
// Note that it will return empty on not found handlers.
RouteName() string
// Next calls all the next handler from the handlers chain,
// it should be used inside a middleware.
//
@ -870,7 +890,8 @@ type Context interface {
// that can be used to share information between handlers and middleware.
Values() *memstore.Store
// Translate is the i18n (localization) middleware's function,
// it calls the Get("translate") to return the translated value.
// it calls the Values().Get(ctx.Application().ConfigurationReadOnly().GetTranslateFunctionContextKey())
// to execute the translate function and return the localized text value.
//
// Example: https://github.com/kataras/iris/tree/master/_examples/miscellaneous/i18n
Translate(format string, args ...interface{}) string
@ -887,7 +908,6 @@ type Context interface {
// RequestPath returns the full request path,
// based on the 'escape'.
RequestPath(escape bool) string
// Host returns the host part of the current url.
Host() string
// Subdomain returns the subdomain of this request, if any.
@ -895,6 +915,9 @@ type Context interface {
Subdomain() (subdomain string)
// IsWWW returns true if the current subdomain (if any) is www.
IsWWW() bool
// FullRqeuestURI returns the full URI,
// including the scheme, the host and the relative requested path/resource.
FullRequestURI() string
// RemoteAddr tries to parse and return the real client's request IP.
//
// Based on allowed headers names that can be modified from Configuration.RemoteAddrHeaders.
@ -1206,7 +1229,7 @@ type Context interface {
// Note that it has nothing to do with server-side caching.
// It does those checks by checking if the "If-Modified-Since" request header
// sent by client or a previous server response header
// (e.g with WriteWithExpiration or StaticEmbedded or Favicon etc.)
// (e.g with WriteWithExpiration or HandleDir or Favicon etc.)
// is a valid one and it's before the "modtime".
//
// A check for !modtime && err == nil is necessary to make sure that
@ -1355,7 +1378,7 @@ type Context interface {
// You can define your own "Content-Type" with `context#ContentType`, before this function call.
//
// This function doesn't support resuming (by range),
// use ctx.SendFile or router's `StaticWeb` instead.
// use ctx.SendFile or router's `HandleDir` instead.
ServeContent(content io.ReadSeeker, filename string, modtime time.Time, gzipCompression bool) error
// ServeFile serves a file (to send a file, a zip for example to the client you should use the `SendFile` instead)
// receives two parameters
@ -1365,7 +1388,7 @@ type Context interface {
// You can define your own "Content-Type" with `context#ContentType`, before this function call.
//
// This function doesn't support resuming (by range),
// use ctx.SendFile or router's `StaticWeb` instead.
// use ctx.SendFile or router's `HandleDir` instead.
//
// Use it when you want to serve dynamic files to the client.
ServeFile(filename string, gzipCompression bool) error

View File

@ -0,0 +1,49 @@
package main
import (
"github.com/kataras/iris"
)
func main() {
app := iris.New()
v1 := app.Party("/api/v1")
myFilter := func(ctx iris.Context) bool {
// don't do that on production, use session or/and database calls and etc.
ok, _ := ctx.URLParamBool("admin")
return ok
}
onlyWhenFilter1 := func(ctx iris.Context) {
ctx.Application().Logger().Infof("admin: %s", ctx.Params())
ctx.Next()
}
onlyWhenFilter2 := func(ctx iris.Context) {
// You can always use the per-request storage
// to perform actions like this ofc.
//
// this handler: ctx.Values().Set("is_admin", true)
// next handler: isAdmin := ctx.Values().GetBoolDefault("is_admin", false)
//
// but, let's simplify it:
ctx.HTML("<h1>Hello Admin</h1><br>")
ctx.Next()
}
// HERE:
// It can be registered anywhere, as a middleware.
// It will fire the `onlyWhenFilter1` and `onlyWhenFilter2` as middlewares (with ctx.Next())
// if myFilter pass otherwise it will just continue the handler chain with ctx.Next() by ignoring
// the `onlyWhenFilter1` and `onlyWhenFilter2`.
myMiddleware := iris.NewConditionalHandler(myFilter, onlyWhenFilter1, onlyWhenFilter2)
v1UsersRouter := v1.Party("/users", myMiddleware)
v1UsersRouter.Get("/", func(ctx iris.Context) {
ctx.HTML("requested: <b>/api/v1/users</b>")
})
// http://localhost:8080/api/v1/users
// http://localhost:8080/api/v1/users?admin=true
app.Run(iris.Addr(":8080"))
}

View File

@ -10,11 +10,6 @@ import (
// In this example you'll just see one use case of .WrapRouter.
// 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.
//
// To see how you can serve files on root "/" without a custom wrapper
// just navigate to the "file-server/single-page-application" example.
//
// This is just for the proof of concept, you can skip this tutorial if it's too much for you.
func newApp() *iris.Application {
app := iris.New()
@ -23,26 +18,15 @@ func newApp() *iris.Application {
ctx.HTML("<b>Resource Not found</b>")
})
app.Get("/", func(ctx iris.Context) {
ctx.ServeFile("./public/index.html", false)
})
app.Get("/profile/{username}", func(ctx iris.Context) {
ctx.Writef("Hello %s", ctx.Params().Get("username"))
})
// serve files from the root "/", if we used .StaticWeb it could override
// all the routes because of the underline need of wildcard.
// Here we will see how you can by-pass this behavior
// by creating a new file server handler and
// setting up a wrapper for the router(like a "low-level" middleware)
// in order to manually check if we want to process with the router as normally
// or execute the file server handler instead.
app.HandleDir("/", "./public")
// use of the .StaticHandler
// which is the same as StaticWeb but it doesn't
// registers the route, it just returns the handler.
fileServer := app.StaticHandler("./public", false, false)
myOtherHandler := func(ctx iris.Context) {
ctx.Writef("inside a handler which is fired manually by our custom router wrapper")
}
// wrap the router with a native net/http handler.
// if url does not contain any "." (i.e: .css, .js...)
@ -52,19 +36,18 @@ func newApp() *iris.Application {
// if not then it will serve the files based on the root "/" path.
app.WrapRouter(func(w http.ResponseWriter, r *http.Request, router http.HandlerFunc) {
path := r.URL.Path
// Note that if path has suffix of "index.html" it will auto-permant redirect to the "/",
// so our first handler will be executed instead.
if !strings.Contains(path, ".") { // if it's not a resource then continue to the router as normally.
router(w, r)
if strings.HasPrefix(path, "/other") {
// acquire and release a context in order to use it to execute
// our custom handler
// remember: we use net/http.Handler because here we are in the "low-level", before the router itself.
ctx := app.ContextPool.Acquire(w, r)
myOtherHandler(ctx)
app.ContextPool.Release(ctx)
return
}
// acquire and release a context in order to use it to execute
// our file server
// remember: we use net/http.Handler because here we are in the "low-level", before the router itself.
ctx := app.ContextPool.Acquire(w, r)
fileServer(ctx)
app.ContextPool.Release(ctx)
router.ServeHTTP(w, r) // else continue serving routes as usual.
})
return app
@ -78,14 +61,10 @@ func main() {
// http://localhost:8080/app.js
// http://localhost:8080/css/main.css
// http://localhost:8080/profile/anyusername
// http://localhost:8080/other/random
app.Run(iris.Addr(":8080"))
// Note: In this example we just saw one use case,
// you may want to .WrapRouter or .Downgrade in order to bypass the iris' default router, i.e:
// you can use that method to setup custom proxies too.
//
// If you just want to serve static files on other path than root
// you can just use the StaticWeb, i.e:
// .StaticWeb("/static", "./public")
// ________________________________requestPath, systemPath
}

View File

@ -56,4 +56,6 @@ func TestCustomWrapper(t *testing.T) {
Status(httptest.StatusOK).
Body().Equal(contents)
}
e.GET("/other/something").Expect().Status(httptest.StatusOK)
}

View File

@ -1,7 +1,7 @@
<html>
<head>
<title>{{ .Page.Title }}</title>
<title>Index Page</title>
</head>
<body>

View File

@ -52,7 +52,7 @@ func main() {
/*
http://localhost:8080/test_slice_hero/myvaluei1/myavlue2 ->
myparam's value (a trailing path parameter type) is: []string{"myvaluei1", "myavlue2"}
myparam's value (a trailing path parameter type) is: []string{"myvalue1", "myavlue2"}
*/
app.Get("/test_slice_hero/{myparam:slice}", hero.Handler(func(myparam []string) string {
return fmt.Sprintf("myparam's value (a trailing path parameter type) is: %#v\n", myparam)
@ -66,7 +66,7 @@ func main() {
myparam's value (a trailing path parameter type) is: []string{"value1", "value2"}
*/
app.Get("/test_slice_contains/{myparam:slice contains([value1,value2])}", func(ctx context.Context) {
// When it is not a built'n function available to retrieve your value with the type you want, such as ctx.Params().GetInt
// When it is not a builtin function available to retrieve your value with the type you want, such as ctx.Params().GetInt
// then you can use the `GetEntry.ValueRaw` to get the real value, which is set-ed by your macro above.
myparam := ctx.Params().GetEntry("myparam").ValueRaw.([]string)
ctx.Writef("myparam's value (a trailing path parameter type) is: %#v\n", myparam)

View File

@ -35,17 +35,17 @@ func main() {
// maps to ./public/assets/css/bootstrap.min.css file at system location.
// GET: http://localhost:8080/assets/js/react.min.js
// maps to ./public/assets/js/react.min.js file at system location.
app.StaticWeb("/assets", "./public/assets")
app.HandleDir("/assets", "./public/assets")
/* OR
// GET: http://localhost:8080/js/react.min.js
// maps to ./public/assets/js/react.min.js file at system location.
app.StaticWeb("/js", "./public/assets/js")
app.HandleDir("/js", "./public/assets/js")
// GET: http://localhost:8080/css/bootstrap.min.css
// maps to ./public/assets/css/bootstrap.min.css file at system location.
app.StaticWeb("/css", "./public/assets/css")
app.HandleDir("/css", "./public/assets/css")
*/

View File

@ -1,119 +0,0 @@
# Sessions
Iris provides a fast, fully featured and easy to use sessions manager.
Iris sessions manager lives on its own [kataras/iris/sessions](https://github.com/kataras/iris/tree/master/sessions) package.
Some trivial examples,
- [Overview](https://github.com/kataras/iris/blob/master/_examples/sessions/overview/main.go)
- [Standalone](https://github.com/kataras/iris/blob/master/_examples/sessions/standalone/main.go)
- [Secure Cookie](https://github.com/kataras/iris/blob/master/_examples/sessions/securecookie/main.go)
- [Flash Messages](https://github.com/kataras/iris/blob/master/_examples/sessions/flash-messages/main.go)
- [Databases](https://github.com/kataras/iris/tree/master/_examples/sessions/database)
* [Badger](https://github.com/kataras/iris/blob/master/_examples/sessions/database/badger/main.go) **fastest**
* [BoltDB](https://github.com/kataras/iris/blob/master/_examples/sessions/database/boltdb/main.go)
* [Redis](https://github.com/kataras/iris/blob/master/_examples/sessions/database/redis/main.go)
## Overview
```go
import "github.com/kataras/iris/sessions"
manager := sessions.Start(iris.Context)
manager.
ID() string
Get(string) interface{}
HasFlash() bool
GetFlash(string) interface{}
GetFlashString(string) string
GetString(key string) string
GetInt(key string) (int, error)
GetInt64(key string) (int64, error)
GetFloat32(key string) (float32, error)
GetFloat64(key string) (float64, error)
GetBoolean(key string) (bool, error)
GetAll() map[string]interface{}
GetFlashes() map[string]interface{}
VisitAll(cb func(k string, v interface{}))
Set(string, interface{})
SetImmutable(key string, value interface{})
SetFlash(string, interface{})
Delete(string)
Clear()
ClearFlashes()
```
This example will show how to store data from a session.
You don't need any third-party library except Iris, but if you want you can use anything, remember Iris is fully compatible with the standard library. You can find a more detailed examples by pressing [here](https://github.com/kataras/iris/tree/master/_examples/sessions).
In this example we will only allow authenticated users to view our secret message on the `/secret` age. To get access to it, the will first have to visit `/login` to get a valid session cookie, hich logs him in. Additionally he can visit `/logout` to revoke his access to our secret message.
```go
// sessions.go
package main
import (
"github.com/kataras/iris"
"github.com/kataras/iris/sessions"
)
var (
cookieNameForSessionID = "mycookiesessionnameid"
sess = sessions.New(sessions.Config{Cookie: cookieNameForSessionID, AllowReclaim: true})
)
func secret(ctx iris.Context) {
// Check if user is authenticated
if auth, _ := sess.Start(ctx).GetBoolean("authenticated"); !auth {
ctx.StatusCode(iris.StatusForbidden)
return
}
// Print secret message
ctx.WriteString("The cake is a lie!")
}
func login(ctx iris.Context) {
session := sess.Start(ctx)
// Authentication goes here
// ...
// Set user as authenticated
session.Set("authenticated", true)
}
func logout(ctx iris.Context) {
session := sess.Start(ctx)
// Revoke users authentication
session.Set("authenticated", false)
}
func main() {
app := iris.New()
app.Get("/secret", secret)
app.Get("/login", login)
app.Get("/logout", logout)
app.Run(iris.Addr(":8080"))
}
```
```bash
$ go run sessions.go
$ curl -s http://localhost:8080/secret
Forbidden
$ curl -s -I http://localhost:8080/login
Set-Cookie: mysessionid=MTQ4NzE5Mz...
$ curl -s --cookie "mysessionid=MTQ4NzE5Mz..." http://localhost:8080/secret
The cake is a lie!
```

View File

@ -7,22 +7,21 @@ import (
"github.com/kataras/iris/sessions"
"github.com/kataras/iris/sessions/sessiondb/redis"
"github.com/kataras/iris/sessions/sessiondb/redis/service"
)
// tested with redis version 3.0.503.
// for windows see: https://github.com/ServiceStack/redis-windows
func main() {
// replace with your running redis' server settings:
db := redis.New(service.Config{
Network: "tcp",
Addr: "127.0.0.1:6379",
Password: "",
Database: "",
MaxIdle: 0,
MaxActive: 0,
IdleTimeout: time.Duration(5) * time.Minute,
Prefix: ""}) // optionally configure the bridge between your redis server
db := redis.New(redis.Config{
Network: "tcp",
Addr: "127.0.0.1:6379",
Timeout: time.Duration(30) * time.Second,
MaxActive: 10,
Password: "",
Database: "",
Prefix: "",
}) // optionally configure the bridge between your redis server.
// close connection when control+C/cmd+C
iris.RegisterOnInterrupt(func() {
@ -33,10 +32,9 @@ func main() {
sess := sessions.New(sessions.Config{
Cookie: "sessionscookieid",
Expires: 45 * time.Minute, // <=0 means unlimited life. Defaults to 0.
Expires: 0, // defaults to 0: unlimited life. Another good value is: 45 * time.Minute,
AllowReclaim: true,
},
)
})
//
// IMPORTANT:
@ -45,6 +43,7 @@ func main() {
// the rest of the code stays the same.
app := iris.New()
// app.Logger().SetLevel("debug")
app.Get("/", func(ctx iris.Context) {
ctx.Writef("You should navigate to the /set, /get, /delete, /clear,/destroy instead")

View File

@ -54,14 +54,10 @@ func (b *Bootstrapper) SetupSessions(expires time.Duration, cookieHashKey, cooki
}
// SetupWebsockets prepares the websocket server.
func (b *Bootstrapper) SetupWebsockets(endpoint string, onConnection websocket.ConnectionFunc) {
ws := websocket.New(websocket.Config{})
ws.OnConnection(onConnection)
func (b *Bootstrapper) SetupWebsockets(endpoint string, handler websocket.ConnHandler) {
ws := websocket.New(websocket.DefaultGorillaUpgrader, handler)
b.Get(endpoint, ws.Handler())
b.Any("/iris-ws.js", func(ctx iris.Context) {
ctx.Write(websocket.ClientSource)
})
b.Get(endpoint, websocket.Handler(ws))
}
// SetupErrorHandlers prepares the http error handlers
@ -112,7 +108,7 @@ func (b *Bootstrapper) Bootstrap() *Bootstrapper {
// static files
b.Favicon(StaticAssets + Favicon)
b.StaticWeb(StaticAssets[1:len(StaticAssets)-1], StaticAssets)
b.HandleDir(StaticAssets[1:len(StaticAssets)-1], StaticAssets)
// middleware, after static files
b.Use(recover.New())

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