mirror of
https://github.com/kataras/iris.git
synced 2025-02-02 15:30:36 +01:00
Publish the new version ✈️ | Look description please!
# FAQ ### Looking for free support? http://support.iris-go.com https://kataras.rocket.chat/channel/iris ### Looking for previous versions? https://github.com/kataras/iris#version ### Should I upgrade my Iris? Developers are not forced to upgrade if they don't really need it. Upgrade whenever you feel ready. > Iris uses the [vendor directory](https://docs.google.com/document/d/1Bz5-UB7g2uPBdOx-rw5t9MxJwkfpx90cqG9AFL0JAYo) feature, so you get truly reproducible builds, as this method guards against upstream renames and deletes. **How to upgrade**: Open your command-line and execute this command: `go get -u github.com/kataras/iris`. For further installation support, please click [here](http://support.iris-go.com/d/16-how-to-install-iris-web-framework). ### About our new home page http://iris-go.com Thanks to [Santosh Anand](https://github.com/santoshanand) the http://iris-go.com has been upgraded and it's really awesome! [Santosh](https://github.com/santoshanand) is a freelancer, he has a great knowledge of nodejs and express js, Android, iOS, React Native, Vue.js etc, if you need a developer to find or create a solution for your problem or task, please contact with him. The amount of the next two or three donations you'll send they will be immediately transferred to his own account balance, so be generous please! Read more at https://github.com/kataras/iris/blob/master/HISTORY.md Former-commit-id: eec2d71bbe011d6b48d2526eb25919e36e5ad94e
This commit is contained in:
parent
03bcadadec
commit
5e4b63acb2
35
.github/CONTRIBUTING.md
vendored
35
.github/CONTRIBUTING.md
vendored
|
@ -1,38 +1,23 @@
|
|||
If you wanna contribute please submit a PR to one of the [iris-contrib organisation's](https://github.com/iris-contrib) projects.
|
||||
## Code Of Conduct
|
||||
|
||||
##### Note that I do not accept pull requests here and that I use the issue tracker for bug reports and proposals only. Please ask questions on the [https://kataras.rocket.chat/channel/iris][Chat] or [http://stackoverflow.com/](http://stackoverflow.com).
|
||||
The community should respect and follow our new [Code of Conduct](https://github.com/kataras/iris/blob/master/CODE-OF-CONDUCT.md).
|
||||
|
||||
## Before Submitting an Issue
|
||||
|
||||
First, please do a search in [open issues](http://support.iris-go.com) to see if the issue or feature request has already been filed. If there is an issue add your comments to this issue.
|
||||
Navigate through [issues](https://github.com/kataras/issues) and check if it has been already filled by other person.
|
||||
|
||||
The Iris project is distributed across multiple repositories, try to file the issue against the correct repository,
|
||||
|
||||
- [Community iris-specific middleware](https://github.com/iris-contrib/middleware/issues?utf8=%E2%9C%93&q=is%3Aopen+is%3Aissue)
|
||||
- [App reloader and command line tool](https://github.com/kataras/rizla/issues?utf8=%E2%9C%93&q=is%3Aopen+is%3Aissue)
|
||||
- [View Engine](https://github.com/kataras/go-template/issues?utf8=%E2%9C%93&q=is%3Aopen+is%3Aissue)
|
||||
- [Sessions](https://github.com/kataras/go-sessions/issues?utf8=%E2%9C%93&q=is%3Aopen+is%3Aissue)
|
||||
- [About docs.iris-go.com](https://github.com/iris-contrib/gitbook/issues?utf8=%E2%9C%93&q=is%3Aopen+is%3Aissue)
|
||||
- [About examples](https://github.com/iris-contrib/examples/issues?utf8=%E2%9C%93&q=is%3Aopen+is%3Aissue)
|
||||
- [Iris main(core)](http://support.iris-go.com)
|
||||
Before post a new issue, please do an upgrade:
|
||||
|
||||
Before post a new issue do an iris upgrade:
|
||||
|
||||
- Delete `$GOPATH/src/gopkg.in/kataras`
|
||||
- Open shell and execute the command: `go get -u gopkg.in/kataras/iris.v6/iris`
|
||||
- Delete `$GOPATH/src/github.com/kataras`
|
||||
- Open shell and execute the command: `go get -u github.com/kataras/iris`
|
||||
- Try to re-produce the issue
|
||||
- If the issue still exists, then post the issue with the necessary information.
|
||||
|
||||
To be aware of the framework's changes and updates please **[star](https://github.com/kataras/iris/stargazers)** and **[watch](https://github.com/kataras/iris/watchers)** the repository.
|
||||
|
||||
If the issue is after an upgrade, please read the [HISTORY.md](https://github.com/kataras/iris/blob/v6/HISTORY.md) for any breaking-changes and fixes.
|
||||
|
||||
The author answers the same day, perhaps the same hour you post the issue.
|
||||
|
||||
It is impossible to notify each user on every change, so to be aware of the framework's changes and be notify about updates
|
||||
please **star** or **watch** the repository.
|
||||
|
||||
If your issue is a closed-personal question then please ask that question on [community chat][Chat].
|
||||
Do not discuss things that they're not relative to the framework, keep Github issues useful for newcomers. A Github issue should exists to solve or report a problem.
|
||||
|
||||
> If you want to talk about something else that can't be inside Github issues please [chat](https://gitter.im/iris-go/Lobby) with us.
|
||||
|
||||
## Writing Good Bug Reports and Feature Requests
|
||||
|
||||
|
@ -47,5 +32,3 @@ The more information you can provide, the more likely someone will be successful
|
|||
* Version of Iris
|
||||
* Errors in the Terminal/Console
|
||||
* When you have glide/godep installed, can you reproduce the issue when starting Iris' station without these?
|
||||
|
||||
[Chat]: https://kataras.rocket.chat/channel/iris
|
||||
|
|
2
.github/ISSUE_TEMPLATE.md
vendored
2
.github/ISSUE_TEMPLATE.md
vendored
|
@ -1,6 +1,6 @@
|
|||
Please answer these questions before submitting your issue. Thanks!
|
||||
|
||||
- [x] I have read the [GopherBOOk](http://gopherbook.iris-go.com), [Examples](https://github.com/iris-contrib/examples), [Contributing File](https://github.com/kataras/iris/blob/v6/.github/CONTRIBUTING.md) and **I'm sure that this issue is not [posted](http://support.iris-go.com)** before.
|
||||
- [x] I have read the [_examples](https://github.com/kataras/iris/tree/master/_examples), [Contributing File](https://github.com/kataras/iris/blob/master/.github/CONTRIBUTING.md).
|
||||
|
||||
|
||||
### What version of Go are you using, minimum 1.8 (`go version`)?
|
||||
|
|
20
.github/PULL_REQUEST_TEMPLATE.md
vendored
20
.github/PULL_REQUEST_TEMPLATE.md
vendored
|
@ -1,20 +1,6 @@
|
|||
This repository follows the official [golang](https://github.com/golang/go#contributing) guidelines for the contributions:
|
||||
I'd love to see more contributions!
|
||||
|
||||
##### Note that I do not accept pull requests here and that I use the issue tracker proposals only. Please ask questions on the http://support.iris-go.com or [https://kataras.rocket.chat/channel/iris][chat].
|
||||
|
||||
Iris' features are not directly adopted to Iris. A component's feature/change should be tested for some time before being part of the Iris which users install.
|
||||
|
||||
Do PRs at the iris' components instead of the core.
|
||||
You can find many repositories to help Iris with your contribution. The [iris-contrib](https://github.com/iris-contrib) is open for any
|
||||
kind of PR, community is 100% responsible for the whole organisation.
|
||||
|
||||
- [Community iris-specific middleware](https://github.com/iris-contrib/middleware/issues?utf8=%E2%9C%93&q=is%3Aopen+is%3Aissue)
|
||||
- [App reloader and command line tool](https://github.com/kataras/rizla/issues?utf8=%E2%9C%93&q=is%3Aopen+is%3Aissue)
|
||||
- [View Engine](https://github.com/kataras/go-template/issues?utf8=%E2%9C%93&q=is%3Aopen+is%3Aissue)
|
||||
- [Sessions](https://github.com/kataras/go-sessions/issues?utf8=%E2%9C%93&q=is%3Aopen+is%3Aissue)
|
||||
- [For docs.iris-go.com](https://github.com/iris-contrib/gitbook/issues?utf8=%E2%9C%93&q=is%3Aopen+is%3Aissue)
|
||||
- [For examples](https://github.com/iris-contrib/examples/issues?utf8=%E2%9C%93&q=is%3Aopen+is%3Aissue)
|
||||
If you are interested in contributing to the Iris project, please read and understand the [Code of Conduct](https://github.com/kataras/iris/blob/master/CODE-OF-CONDUCT.md) before submitting your [PR](https://github.com/kataras/iris/pulls).
|
||||
|
||||
|
||||
**Only one term to future authors**: A contributor should be responsible and answer to the future users' issues that are relative to her/his code. PR's authors must provide adequate support.
|
||||
**Users is the most important part, we, as software authors, have to respect them. I don't accept any form of contempt to them(users) by anyone.**
|
||||
Don't forget to, first, open an [issue](https://github.com/kataras/iris) to discuss what changes you're willing to push.
|
6
.gitignore
vendored
6
.gitignore
vendored
|
@ -1,5 +1,5 @@
|
|||
.settings
|
||||
.project
|
||||
# my own configuration for vs code, my lovely editor, if someone of you want this, contact with me
|
||||
.vscode
|
||||
specs
|
||||
# turn off these for now
|
||||
.github
|
||||
specs
|
12
.travis.yml
12
.travis.yml
|
@ -1,6 +1,10 @@
|
|||
language: go
|
||||
|
||||
os:
|
||||
- linux
|
||||
- osx
|
||||
go:
|
||||
- go1.8
|
||||
|
||||
go_import_path: gopkg.in/kataras/iris.v6
|
||||
- go1.8
|
||||
- tip
|
||||
go_import_path: github.com/kataras/iris
|
||||
before_install:
|
||||
- if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then sudo apt-get install libgtk-3-dev libappindicator3-dev ; fi
|
41
CODE-OF-CONDUCT.md
Normal file
41
CODE-OF-CONDUCT.md
Normal file
|
@ -0,0 +1,41 @@
|
|||
# Iris Open Source Code of Conduct
|
||||
|
||||
This code of conduct outlines expectations for participation in kataras-managed open source communities, as well as steps for reporting unacceptable behavior. We are committed to providing a welcoming and inspiring community for all. People violating this code of conduct may be banned from the community.
|
||||
|
||||
Our open source communities strive to:
|
||||
|
||||
* **Be friendly and patient**: Remember you might not be communicating in someone else's primary spoken or programming language, and others may not have your level of understanding.
|
||||
* **Be welcoming**: Our communities welcome and support people of all backgrounds and identities. This includes, but is not limited to members of any race, ethnicity, culture, national origin, color, immigration status, social and economic class, educational level, sex, sexual orientation, gender identity and expression, age, size, family status, political belief, religion, and mental and physical ability.
|
||||
* **Be respectful**: We are a world-wide community of professionals, and we conduct ourselves professionally. Disagreement is no excuse for poor behavior and poor manners. Disrespectful and unacceptable behavior includes, but is not limited to:
|
||||
* Violent threats or language.
|
||||
* Discriminatory or derogatory jokes and language.
|
||||
* Posting sexually explicit or violent material.
|
||||
* Posting, or threatening to post, people's personally identifying information ("doxing").
|
||||
* Insults, especially those using discriminatory terms or slurs.
|
||||
* Behavior that could be perceived as sexual attention.
|
||||
* Advocating for or encouraging any of the above behaviors.
|
||||
* **Understand disagreements**: Disagreements, both social and technical, are useful learning opportunities. Seek to understand the other viewpoints and resolve differences constructively.
|
||||
* This code is not exhaustive or complete. It serves to capture our common understanding of a productive, collaborative environment. We expect the code to be followed in spirit as much as in the letter.
|
||||
|
||||
## Scope
|
||||
|
||||
This code of conduct applies to all repos and communities for kataras-managed open source projects regardless of whether or not the repo explicitly calls out its use of this code. The code also applies in public spaces when an individual is representing a project or its community. Examples include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
|
||||
|
||||
|
||||
## Reporting Code of Conduct Issues
|
||||
|
||||
We encourage all communities to resolve issues on their own whenever possible. This builds a broader and deeper understanding and ultimately a healthier interaction. In the event that an issue cannot be resolved locally, please feel free to report your concerns by contacting kataras@tutanota.com.
|
||||
|
||||
In your report please include:
|
||||
|
||||
* Your contact information.
|
||||
* Names (real, usernames or pseudonyms) of any individuals involved. If there are additional witnesses, please include them as well.
|
||||
* Your account of what occurred, and if you believe the incident is ongoing. If there is a publicly available record (e.g. a mailing list archive or a public chat log), please include a link or attachment.
|
||||
* Any additional information that may be helpful.
|
||||
|
||||
|
||||
All reports will be reviewed by [kataras](https://github.com/kataras) and will result in a response that is deemed necessary and appropriate to the circumstances. Where additional perspectives are needed, I may seek insight from others with relevant expertise or experience. The confidentiality of the person reporting the incident will be kept at all times. Involved parties are never part of the review team.
|
||||
|
||||
Anyone asked to stop unacceptable behavior is expected to comply immediately. If an individual engages in **unacceptable behavior**, the review team may take any action they deem appropriate, **including a permanent ban from the community**.
|
||||
|
||||
This code of conduct is based on the [template](http://todogroup.org/opencodeofconduct) established by the [TODO Group](http://todogroup.org/) and used by numerous other large communities (e.g., [Facebook](https://code.facebook.com/pages/876921332402685/open-source-code-of-conduct), [Yahoo](https://yahoo.github.io/codeofconduct), [Twitter](https://engineering.twitter.com/opensource/code-of-conduct), [GitHub](http://todogroup.org/opencodeofconduct/#opensource@github.com)) and the Scope section from the [Contributor Covenant version 1.4](http://contributor-covenant.org/version/1/4/).
|
66
DONATIONS.md
66
DONATIONS.md
|
@ -1,66 +0,0 @@
|
|||
The main purpose of donations to open source is to say "thank you" to the developer rather than actually advancing the project.
|
||||
|
||||
|
||||
Open source projects don’t need the money like those charities do—and so it’s usually phrased like: *Buy the developer a cup of coffee*.
|
||||
|
||||
|
||||
<!--It's true that I am spending all my available time for Iris and its related projects, therefore I have no income value.
|
||||
|
||||
However, I am not asking from people to change the system. I know that the majority of us(devs) don't really care how authors of projects like Iris survive. I totally understand that.
|
||||
|
||||
If somebody out there can
|
||||
help developers like me to worry less about daily life's dilemmas it would be easier for them to make the particular project(s) even better.
|
||||
There are no limits to the Iris' potentials.
|
||||
|
||||
|
||||
I am a realistic person. If things won't change for my daily life I will be forced to give Iris' managment to somebody else(that community could trust).-->
|
||||
|
||||
# Buy me a cup of coffee?
|
||||
|
||||
Iris is free and open source but developing it has taken thousands of hours of my time and a large part of my sanity. If you feel this web framework useful to you, it would go a great way to ensuring that I can afford to take the time to continue to develop it.
|
||||
|
||||
|
||||
I spend all my time in the construction of Iris, therefore I have no income value.
|
||||
|
||||
Feel free to send **any** amount through paypal
|
||||
|
||||
[![](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=kataras2006%40hotmail%2ecom&lc=GR&item_name=Iris%20web%20framework&item_number=iriswebframeworkdonationid2016¤cy_code=EUR&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted)
|
||||
|
||||
|
||||
Some of the benefits are listed here:
|
||||
|
||||
- Your github username, after your approval, is visible here as a "premium" community member.
|
||||
- Access to the 'donors' [private chat room](https://kataras.rocket.chat/group/donors) gives you real-time assistance by Iris' Author.
|
||||
|
||||
## More about your donations
|
||||
|
||||
[Juan Sebastián Suárez Valencia](https://github.com/Juanses) donated 20 EUR at September 11
|
||||
|
||||
[Bob Lee](https://github.com/li3p) donated 20 EUR at September 16
|
||||
|
||||
[Celso Luiz](https://github.com/celsosz) donated 50 EUR at September 29
|
||||
|
||||
[Ankur Srivastava](https://github.com/ansrivas) donated 20 EUR at October 2
|
||||
|
||||
[Damon Zhao](https://github.com/se77en) donated 20 EUR at October 21
|
||||
|
||||
[exponity - consulting & digital transformation](https://github.com/exponity) donated 30 EUR at November 4
|
||||
|
||||
[Thomas Fritz](https://github.com/thomasfr) donated 25 EUR at Jenuary 8 of 2017
|
||||
|
||||
[Thanos V.](http://mykonosbiennale.com/) donated 20 EUR at Jenuary 16 of 2017
|
||||
|
||||
[George Opritescu](https://github.com/International) donated 20 EUR at February 7 of 2017
|
||||
|
||||
[Lex Tang](https://github.com/lexrus) donated 20 EUR at February 22 of 2017
|
||||
|
||||
[Conrad Steenberg](https://github.com/hengestone) donated 25 EUR at March 23 of 2017
|
||||
|
||||
*ANONYMOUS* donated 356 EUR, last anonymous donation at March 22 of 2017
|
||||
|
||||
> The names, shown at the [legends](https://github.com/kataras/iris#legends-) list, are sorted by **date** and **NOT by the amount** of the donation.
|
||||
|
||||
|
||||
> *ANONYMOUS*: People who donate but don't want to be shown here. *ANONYMOUS* are listed as one group instead of an individual entry, in order to protect their exact date of their donation.
|
||||
|
||||
# Thanks for your gratitude and finance help ♡
|
309
Gopkg.lock
generated
Normal file
309
Gopkg.lock
generated
Normal file
|
@ -0,0 +1,309 @@
|
|||
# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'.
|
||||
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/BurntSushi/toml"
|
||||
packages = ["."]
|
||||
revision = "b26d9c308763d68093482582cea63d69be07a0f0"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/Joker/jade"
|
||||
packages = ["."]
|
||||
revision = "35b3f5bdbcc920cd31f4870536dbc63be8530541"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/Unknwon/i18n"
|
||||
packages = ["."]
|
||||
revision = "8372b908b5876d26cfa46a85fc4851b981dad102"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/ajg/form"
|
||||
packages = ["."]
|
||||
revision = "523a5da1a92f01b01f840b61689c0340a0243532"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/aymerick/raymond"
|
||||
packages = [".","ast","lexer","parser"]
|
||||
revision = "72acac2207479d21dd45898c2a4264246c818148"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/davecgh/go-spew"
|
||||
packages = ["spew"]
|
||||
revision = "346938d642f2ec3594ed81d874461961cd0faa76"
|
||||
version = "v1.1.0"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/eknkc/amber"
|
||||
packages = [".","parser"]
|
||||
revision = "f0d8fdb67f9f4a2c0d02fb6ce4830b8b6754de10"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/esemplastic/unis"
|
||||
packages = [".","logger"]
|
||||
revision = "6e30ed034e8cb31227b24057d030fdd0261bcfc6"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/fatih/structs"
|
||||
packages = ["."]
|
||||
revision = "74a29b9fac7397d933f47e33eba94d2d83a464a2"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/flosch/pongo2"
|
||||
packages = ["."]
|
||||
revision = "1d0f0d3af150c4a65dfd424d742f7374819e7d29"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/garyburd/redigo"
|
||||
packages = ["internal","redis"]
|
||||
revision = "433969511232c397de61b1442f9fd49ec06ae9ba"
|
||||
version = "v1.1.0"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/gavv/monotime"
|
||||
packages = ["."]
|
||||
revision = "47d58efa69556a936a3c15eb2ed42706d968ab01"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/getlantern/context"
|
||||
packages = ["."]
|
||||
revision = "624d99b1798d7c5375ea1d3ca4c5b04d58f7c775"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/getlantern/errors"
|
||||
packages = ["."]
|
||||
revision = "99fa440517e8f3d1e4cd8d6dbed6b41f4c1ed3d6"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/getlantern/filepersist"
|
||||
packages = ["."]
|
||||
revision = "c5f0cd24e7991579ba6f5f1bd20a1ad2c9f06cd4"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/getlantern/golog"
|
||||
packages = ["."]
|
||||
revision = "cca714f7feb5df8e455f409b549d384441ac4578"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/getlantern/hex"
|
||||
packages = ["."]
|
||||
revision = "083fba3033ad473db3dd31c9bb368473d37581a7"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/getlantern/hidden"
|
||||
packages = ["."]
|
||||
revision = "d52a649ab33af200943bb599898dbdcfdbc94cb7"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/getlantern/ops"
|
||||
packages = ["."]
|
||||
revision = "b70875f5d689a9438bca72aefd7142a2af889b18"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/getlantern/stack"
|
||||
packages = ["."]
|
||||
revision = "02f928aad224fbccd50d66edd776fc9d1e9f2f2b"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/getlantern/systray"
|
||||
packages = ["."]
|
||||
revision = "0068f6ae40ea39bfd683043e8452024097fff0e4"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/google/go-querystring"
|
||||
packages = ["query"]
|
||||
revision = "53e6ce116135b80d037921a7fdd5138cf32d7a8a"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/gorilla/websocket"
|
||||
packages = ["."]
|
||||
revision = "3ab3a8b8831546bd18fd182c20687ca853b2bb13"
|
||||
version = "v1.1.0"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/imdario/mergo"
|
||||
packages = ["."]
|
||||
revision = "3e95a51e0639b4cf372f2ccf74c86749d747fbdc"
|
||||
version = "0.2.2"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/imkira/go-interpol"
|
||||
packages = ["."]
|
||||
revision = "5accad8134979a6ac504d456a6c7f1c53da237ca"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/iris-contrib/httpexpect"
|
||||
packages = ["."]
|
||||
revision = "ed44d3c477393b96a598a38730f128dffee33068"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/juju/errors"
|
||||
packages = ["."]
|
||||
revision = "8234c829496aaeae67c5c71235a2cbcc289e960a"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/klauspost/compress"
|
||||
packages = ["flate","gzip"]
|
||||
revision = "f3dce52e0576655d55fd69e74b63da96ad1108f3"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/klauspost/cpuid"
|
||||
packages = ["."]
|
||||
revision = "09cded8978dc9e80714c4d85b0322337b0a1e5e0"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/microcosm-cc/bluemonday"
|
||||
packages = ["."]
|
||||
revision = "e79763773ab6222ca1d5a7cbd9d62d83c1f77081"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/monoculum/formam"
|
||||
packages = ["."]
|
||||
revision = "334e05a3c7f95d500715d7c0405937ac933b28cb"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/moul/http2curl"
|
||||
packages = ["."]
|
||||
revision = "4e24498b31dba4683efb9d35c1c8a91e2eda28c8"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/oxtoacart/bpool"
|
||||
packages = ["."]
|
||||
revision = "4e1c5567d7c2dd59fa4c7c83d34c2f3528b025d6"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/pmezard/go-difflib"
|
||||
packages = ["difflib"]
|
||||
revision = "792786c7400a136282c1664665ae0a8db921c6c2"
|
||||
version = "v1.0.0"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/russross/blackfriday"
|
||||
packages = ["."]
|
||||
revision = "0ba0f2b6ed7c475a92e4df8641825cb7a11d1fa3"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/satori/go.uuid"
|
||||
packages = ["."]
|
||||
revision = "5bf94b69c6b68ee1b541973bb8e1144db23a194b"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/sergi/go-diff"
|
||||
packages = ["diffmatchpatch"]
|
||||
revision = "feef008d51ad2b3778f85d387ccf91735543008d"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/stretchr/testify"
|
||||
packages = ["assert","require"]
|
||||
revision = "f6abca593680b2315d2075e0f5e2a9751e3f431a"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/valyala/bytebufferpool"
|
||||
packages = ["."]
|
||||
revision = "e746df99fe4a3986f4d4f79e13c1e0117ce9c2f7"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/xeipuuv/gojsonpointer"
|
||||
packages = ["."]
|
||||
revision = "6fe8760cad3569743d51ddbb243b26f8456742dc"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/xeipuuv/gojsonreference"
|
||||
packages = ["."]
|
||||
revision = "e02fc20de94c78484cd5ffb007f8af96be030a45"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/xeipuuv/gojsonschema"
|
||||
packages = ["."]
|
||||
revision = "0c8571ac0ce161a5feb57375a9cdf148c98c0f70"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/yalp/jsonpath"
|
||||
packages = ["."]
|
||||
revision = "31a79c7593bb93eb10b163650d4a3e6ca190e4dc"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/yudai/gojsondiff"
|
||||
packages = [".","formatter"]
|
||||
revision = "7b1b7adf999dab73a6eb02669c3d82dbb27a3dd6"
|
||||
version = "1.0.0"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/yudai/golcs"
|
||||
packages = ["."]
|
||||
revision = "ecda9a501e8220fae3b4b600c3db4b0ba22cfc68"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "golang.org/x/crypto"
|
||||
packages = ["acme","acme/autocert"]
|
||||
revision = "e1a4589e7d3ea14a3352255d04b6f1a418845e5e"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "golang.org/x/net"
|
||||
packages = ["html","html/atom","idna","publicsuffix"]
|
||||
revision = "e4fa1c5465ad6111f206fc92186b8c83d64adbe1"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "golang.org/x/text"
|
||||
packages = ["internal/gen","internal/triegen","internal/ucd","secure/bidirule","transform","unicode/bidi","unicode/cldr","unicode/norm","unicode/rangetable"]
|
||||
revision = "ccbd3f7822129ff389f8ca4858a9b9d4d910531c"
|
||||
|
||||
[[projects]]
|
||||
name = "gopkg.in/ini.v1"
|
||||
packages = ["."]
|
||||
revision = "d3de07a94d22b4a0972deb4b96d790c2c0ce8333"
|
||||
version = "v1.28.0"
|
||||
|
||||
[[projects]]
|
||||
branch = "v2"
|
||||
name = "gopkg.in/yaml.v2"
|
||||
packages = ["."]
|
||||
revision = "cd8b52f8269e0feb286dfeef29f8fe4d5b397e0b"
|
||||
|
||||
[solve-meta]
|
||||
analyzer-name = "dep"
|
||||
analyzer-version = 1
|
||||
inputs-digest = "415eba3367a3b497ce9c74414ba802d5902d5b7fefc7dfc99cff6af102ec40fe"
|
||||
solver-name = "gps-cdcl"
|
||||
solver-version = 1
|
179
Gopkg.toml
Normal file
179
Gopkg.toml
Normal file
|
@ -0,0 +1,179 @@
|
|||
|
||||
## Gopkg.toml example (these lines may be deleted)
|
||||
|
||||
## "metadata" defines metadata about the project that could be used by other independent
|
||||
## systems. The metadata defined here will be ignored by dep.
|
||||
# [metadata]
|
||||
# key1 = "value that convey data to other systems"
|
||||
# system1-data = "value that is used by a system"
|
||||
# system2-data = "value that is used by another system"
|
||||
|
||||
## "required" lists a set of packages (not projects) that must be included in
|
||||
## Gopkg.lock. This list is merged with the set of packages imported by the current
|
||||
## project. Use it when your project needs a package it doesn't explicitly import -
|
||||
## including "main" packages.
|
||||
# required = ["github.com/user/thing/cmd/thing"]
|
||||
|
||||
## "ignored" lists a set of packages (not projects) that are ignored when
|
||||
## dep statically analyzes source code. Ignored packages can be in this project,
|
||||
## or in a dependency.
|
||||
# ignored = ["github.com/user/project/badpkg"]
|
||||
|
||||
## Constraints are rules for how directly imported projects
|
||||
## may be incorporated into the depgraph. They are respected by
|
||||
## dep whether coming from the Gopkg.toml of the current project or a dependency.
|
||||
# [[constraint]]
|
||||
## Required: the root import path of the project being constrained.
|
||||
# name = "github.com/user/project"
|
||||
#
|
||||
## Recommended: the version constraint to enforce for the project.
|
||||
## Only one of "branch", "version" or "revision" can be specified.
|
||||
# version = "1.0.0"
|
||||
# branch = "master"
|
||||
# revision = "abc123"
|
||||
#
|
||||
## Optional: an alternate location (URL or import path) for the project's source.
|
||||
# source = "https://github.com/myfork/package.git"
|
||||
#
|
||||
## "metadata" defines metadata about the dependency or override that could be used
|
||||
## by other independent systems. The metadata defined here will be ignored by dep.
|
||||
# [metadata]
|
||||
# key1 = "value that convey data to other systems"
|
||||
# system1-data = "value that is used by a system"
|
||||
# system2-data = "value that is used by another system"
|
||||
|
||||
## Overrides have the same structure as [[constraint]], but supersede all
|
||||
## [[constraint]] declarations from all projects. Only [[override]] from
|
||||
## the current project's are applied.
|
||||
##
|
||||
## Overrides are a sledgehammer. Use them only as a last resort.
|
||||
# [[override]]
|
||||
## Required: the root import path of the project being constrained.
|
||||
# name = "github.com/user/project"
|
||||
#
|
||||
## Optional: specifying a version constraint override will cause all other
|
||||
## constraints on this project to be ignored; only the overridden constraint
|
||||
## need be satisfied.
|
||||
## Again, only one of "branch", "version" or "revision" can be specified.
|
||||
# version = "1.0.0"
|
||||
# branch = "master"
|
||||
# revision = "abc123"
|
||||
#
|
||||
## Optional: specifying an alternate source location as an override will
|
||||
## enforce that the alternate location is used for that project, regardless of
|
||||
## what source location any dependent projects specify.
|
||||
# source = "https://github.com/myfork/package.git"
|
||||
|
||||
|
||||
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "github.com/BurntSushi/toml"
|
||||
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "github.com/Joker/jade"
|
||||
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "github.com/Unknwon/i18n"
|
||||
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "github.com/aymerick/raymond"
|
||||
|
||||
[[constraint]]
|
||||
name = "github.com/davecgh/go-spew"
|
||||
version = "1.1.0"
|
||||
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "github.com/eknkc/amber"
|
||||
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "github.com/esemplastic/unis"
|
||||
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "github.com/flosch/pongo2"
|
||||
|
||||
[[constraint]]
|
||||
name = "github.com/garyburd/redigo"
|
||||
version = "1.1.0"
|
||||
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "github.com/gavv/monotime"
|
||||
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "github.com/getlantern/systray"
|
||||
|
||||
[[constraint]]
|
||||
name = "github.com/gorilla/websocket"
|
||||
version = "1.1.0"
|
||||
|
||||
[[constraint]]
|
||||
name = "github.com/imdario/mergo"
|
||||
version = "0.2.2"
|
||||
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "github.com/iris-contrib/httpexpect"
|
||||
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "github.com/klauspost/compress"
|
||||
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "github.com/microcosm-cc/bluemonday"
|
||||
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "github.com/monoculum/formam"
|
||||
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "github.com/moul/http2curl"
|
||||
|
||||
[[constraint]]
|
||||
name = "github.com/pmezard/go-difflib"
|
||||
version = "1.0.0"
|
||||
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "github.com/russross/blackfriday"
|
||||
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "github.com/satori/go.uuid"
|
||||
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "github.com/valyala/bytebufferpool"
|
||||
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "github.com/xeipuuv/gojsonschema"
|
||||
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "github.com/yalp/jsonpath"
|
||||
|
||||
[[constraint]]
|
||||
name = "github.com/yudai/gojsondiff"
|
||||
version = "1.0.0"
|
||||
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "golang.org/x/crypto"
|
||||
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "golang.org/x/text"
|
||||
|
||||
[[constraint]]
|
||||
branch = "v2"
|
||||
name = "gopkg.in/yaml.v2"
|
1495
HISTORY.md
1495
HISTORY.md
File diff suppressed because it is too large
Load Diff
71
LICENSE
71
LICENSE
|
@ -1,21 +1,58 @@
|
|||
The MIT License (MIT)
|
||||
Copyright (c) 2017 Gerasimos Maropoulos, ΓΜ. All rights reserved.
|
||||
|
||||
Copyright (c) 2016-2017 Gerasimos Maropoulos
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following disclaimer
|
||||
in the documentation and/or other materials provided with the
|
||||
distribution.
|
||||
* Neither the name of Gerasimos Maropoulos nor the name of his
|
||||
username, kataras, may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
The Go Programming Language is redistributed with the following disclaimer:
|
||||
|
||||
Copyright (c) 2009 The Go Authors. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following disclaimer
|
||||
in the documentation and/or other materials provided with the
|
||||
distribution.
|
||||
* Neither the name of Google Inc. nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
549
README.md
549
README.md
|
@ -1,55 +1,173 @@
|
|||
# Iris
|
||||
# ![Logo created by @santoshanand](logo_white_35_24.png) Iris
|
||||
|
||||
A fast, cross-platform and efficient web framework with robust set of well-designed features, written entirely in Go.
|
||||
|
||||
[![Build status](https://api.travis-ci.org/kataras/iris.svg?branch=master&style=flat-square)](https://travis-ci.org/kataras/iris)
|
||||
[![Report card](https://img.shields.io/badge/report%20card%20-a%2B-F44336.svg?style=flat-square)](http://goreportcard.com/report/kataras/iris)
|
||||
[![Support forum](https://img.shields.io/badge/support-page-ec2eb4.svg?style=flat-square)](http://support.iris-go.com)
|
||||
[![Examples](https://img.shields.io/badge/howto-examples-3362c2.svg?style=flat-square)](https://github.com/kataras/iris/tree/master/_examples#table-of-contents)
|
||||
[![Godocs](https://img.shields.io/badge/docs-%20reference-5272B4.svg?style=flat-square)](https://godoc.org/github.com/kataras/iris)
|
||||
[![Chat](https://img.shields.io/badge/community-%20chat-00BCD4.svg?style=flat-square)](https://kataras.rocket.chat/channel/iris)
|
||||
[![Buy me a cup of coffee](https://img.shields.io/badge/support-%20open--source-F4A460.svg?logo=data:image%2Fsvg%2Bxml%3Bbase64%2CPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMDAwIDEwMDAiPjxwYXRoIGZpbGw9InJnYigyMjAsMjIwLDIyMCkiIGQ9Ik04ODYuNiwzMDUuM2MtNDUuNywyMDMuMS0xODcsMzEwLjMtNDA5LjYsMzEwLjNoLTc0LjFsLTUxLjUsMzI2LjloLTYybC0zLjIsMjEuMWMtMi4xLDE0LDguNiwyNi40LDIyLjYsMjYuNGgxNTguNWMxOC44LDAsMzQuNy0xMy42LDM3LjctMzIuMmwxLjUtOGwyOS45LTE4OS4zbDEuOS0xMC4zYzIuOS0xOC42LDE4LjktMzIuMiwzNy43LTMyLjJoMjMuNWMxNTMuNSwwLDI3My43LTYyLjQsMzA4LjktMjQyLjdDOTIxLjYsNDA2LjgsOTE2LjcsMzQ4LjYsODg2LjYsMzA1LjN6Ii8%2BPHBhdGggZmlsbD0icmdiKDIyMCwyMjAsMjIwKSIgZD0iTTc5MS45LDgzLjlDNzQ2LjUsMzIuMiw2NjQuNCwxMCw1NTkuNSwxMEgyNTVjLTIxLjQsMC0zOS44LDE1LjUtNDMuMSwzNi44TDg1LDg1MWMtMi41LDE1LjksOS44LDMwLjIsMjUuOCwzMC4ySDI5OWw0Ny4zLTI5OS42bC0xLjUsOS40YzMuMi0yMS4zLDIxLjQtMzYuOCw0Mi45LTM2LjhINDc3YzE3NS41LDAsMzEzLTcxLjIsMzUzLjItMjc3LjVjMS4yLTYuMSwyLjMtMTIuMSwzLjEtMTcuOEM4NDUuMSwxODIuOCw4MzMuMiwxMzAuOCw3OTEuOSw4My45TDc5MS45LDgzLjl6Ii8%2BPC9zdmc%2B)](https://github.com/kataras/iris#buy-me-a-cup-of-coffee)
|
||||
|
||||
<p>
|
||||
Iris is an <b>efficient</b> and well-designed, <b>cross-platform, web framework</b> with robust set of <b>features</b>.<br/>Build your own <b>high-performance</b> web applications and <b>APIs</b> powered by unlimited <b>potentials and portability</b>.<br/>
|
||||
<a href="https://travis-ci.org/kataras/iris"><img src="https://api.travis-ci.org/kataras/iris.svg?branch=v6&style=flat-square" alt="Build Status"></a>
|
||||
<a href="http://goreportcard.com/report/kataras/iris"><img src="https://img.shields.io/badge/report%20card%20-a%2B-F44336.svg?style=flat-square" alt="http://goreportcard.com/report/kataras/iris"></a>
|
||||
<a href="http://support.iris-go.com"><img src="https://img.shields.io/badge/support-page-ec2eb4.svg?style=flat-square" alt="Iris support forum"></a> <!-- <a href="https://github.com/kataras/iris/blob/v6/HISTORY.md"><img src="https://img.shields.io/badge/codename-√Νεxτ%20-blue.svg?style=flat-square" alt="CHANGELOG/HISTORY"></a> --><a href="https://github.com/kataras/iris/tree/v6/_examples#table-of-contents"><img src="https://img.shields.io/badge/examples-%20repository-3362c2.svg?style=flat-square" alt="Examples for new Gophers"></a>
|
||||
<a href="https://godoc.org/gopkg.in/kataras/iris.v6"><img src="https://img.shields.io/badge/docs-%20reference-5272B4.svg?style=flat-square" alt="Docs"></a>
|
||||
<a href="https://kataras.rocket.chat/channel/iris"><img src="https://img.shields.io/badge/community-%20chat-00BCD4.svg?style=flat-square" alt="Chat"></a>
|
||||
<a href="https://github.com/kataras/iris#buy-me-a-cup-of-coffee"><img src="https://img.shields.io/badge/support-%20open--source-F4A460.svg?logo=data:image%2Fsvg%2Bxml%3Bbase64%2CPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMDAwIDEwMDAiPjxwYXRoIGZpbGw9InJnYigyMjAsMjIwLDIyMCkiIGQ9Ik04ODYuNiwzMDUuM2MtNDUuNywyMDMuMS0xODcsMzEwLjMtNDA5LjYsMzEwLjNoLTc0LjFsLTUxLjUsMzI2LjloLTYybC0zLjIsMjEuMWMtMi4xLDE0LDguNiwyNi40LDIyLjYsMjYuNGgxNTguNWMxOC44LDAsMzQuNy0xMy42LDM3LjctMzIuMmwxLjUtOGwyOS45LTE4OS4zbDEuOS0xMC4zYzIuOS0xOC42LDE4LjktMzIuMiwzNy43LTMyLjJoMjMuNWMxNTMuNSwwLDI3My43LTYyLjQsMzA4LjktMjQyLjdDOTIxLjYsNDA2LjgsOTE2LjcsMzQ4LjYsODg2LjYsMzA1LjN6Ii8%2BPHBhdGggZmlsbD0icmdiKDIyMCwyMjAsMjIwKSIgZD0iTTc5MS45LDgzLjlDNzQ2LjUsMzIuMiw2NjQuNCwxMCw1NTkuNSwxMEgyNTVjLTIxLjQsMC0zOS44LDE1LjUtNDMuMSwzNi44TDg1LDg1MWMtMi41LDE1LjksOS44LDMwLjIsMjUuOCwzMC4ySDI5OWw0Ny4zLTI5OS42bC0xLjUsOS40YzMuMi0yMS4zLDIxLjQtMzYuOCw0Mi45LTM2LjhINDc3YzE3NS41LDAsMzEzLTcxLjIsMzUzLjItMjc3LjVjMS4yLTYuMSwyLjMtMTIuMSwzLjEtMTcuOEM4NDUuMSwxODIuOCw4MzMuMiwxMzAuOCw3OTEuOSw4My45TDc5MS45LDgzLjl6Ii8%2BPC9zdmc%2B" alt="Buy me a cup of coffee"></a>
|
||||
<img src="https://raw.githubusercontent.com/smallnest/go-web-framework-benchmark/4db507a22c964c9bc9774c5b31afdc199a0fe8b7/benchmark.png" alt="This benchmark measures results from 'real-world' instead of 'hello-world' application source code. | Last Update At: July 21, 2016. | Shows: Processing Time Horizontal Graph. | Who did: Third-party source. Transparent achievement." />
|
||||
</p>
|
||||
|
||||
What you say about Iris ✌
|
||||
Build your own web applications and portable APIs with the highest performance and countless potentials.
|
||||
|
||||
If you're coming from [Node.js](https://nodejs.org) world, this is the [expressjs](https://github.com/expressjs/express)++ equivalent for the [Go Programming Language](https://golang.org).
|
||||
|
||||
Installation
|
||||
-----------
|
||||
<p>
|
||||
<a href="https://medium.com/@kataras/a-url-shortener-service-using-go-iris-and-bolt-4182f0b00ae7">
|
||||
<img width="300" src="http://iris-go.com/comment28.png" />
|
||||
</a>
|
||||
|
||||
<a href="https://twitter.com/gelnior/status/769100480706379776">
|
||||
<img width="300" src="http://iris-go.com/comment27.png" />
|
||||
</a>
|
||||
The only requirement is the [Go Programming Language](https://golang.org/dl/), at least version 1.8
|
||||
|
||||
<br/>
|
||||
```sh
|
||||
$ go get -u github.com/kataras/iris
|
||||
```
|
||||
|
||||
<a href="https://twitter.com/_mgale/status/818591490305761280">
|
||||
<img width="300" width="630" src="http://iris-go.com/comment25.png" />
|
||||
</a>
|
||||
> 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.
|
||||
For further installation support, please navigate [here](http://support.iris-go.com/d/16-how-to-install-iris-web-framework).
|
||||
|
||||
<a href="https://twitter.com/MeAlex07/status/822799954188075008">
|
||||
<img width="300" width="627" src="http://iris-go.com/comment26.png" />
|
||||
</a>
|
||||
```go
|
||||
package main
|
||||
|
||||
<br/>
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/view"
|
||||
)
|
||||
|
||||
// User is just a bindable object structure.
|
||||
type User struct {
|
||||
Username string `json:"username"`
|
||||
Firstname string `json:"firstname"`
|
||||
Lastname string `json:"lastname"`
|
||||
City string `json:"city"`
|
||||
Age int `json:"age"`
|
||||
}
|
||||
|
||||
<a href="https://www.youtube.com/watch?v=jGx0LkuUs4A">
|
||||
<img width="300"
|
||||
src="https://github.com/iris-contrib/website/raw/gh-pages/assets/gif_link_to_yt.gif" alt="What people say" />
|
||||
</a>
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
<a href="https://www.youtube.com/watch?v=jGx0LkuUs4A">
|
||||
<img width ="300" src="https://github.com/iris-contrib/website/raw/gh-pages/assets/gif_link_to_yt2.gif" alt="What people say" />
|
||||
</a>
|
||||
<br/>
|
||||
// Define templates using the std html/template engine.
|
||||
// Parse and load all files inside "./views" folder with ".html" file extension.
|
||||
// Reload the templates on each request (development mode).
|
||||
app.AttachView(view.HTML("./views", ".html").Reload(true))
|
||||
|
||||
If you're coming from <a href="https://nodejs.org/en/">Node.js</a> world, this is the <a href="https://github.com/expressjs/express">expressjs</a> equivalent for the <a href="https://golang.org">Go Programming Language.</a><br/>
|
||||
// Regster custom handler for specific http errors.
|
||||
app.OnErrorCode(iris.StatusInternalServerError, func(ctx context.Context) {
|
||||
// .Values are used to communicate between handlers, middleware.
|
||||
errMessage := ctx.Values().GetString("error")
|
||||
if errMessage != "" {
|
||||
ctx.Writef("Internal server error: %s", errMessage)
|
||||
return
|
||||
}
|
||||
|
||||
</p>
|
||||
ctx.Writef("(Unexpected) internal server error")
|
||||
})
|
||||
|
||||
Legends [♡](https://github.com/kataras/iris#support)
|
||||
-----------
|
||||
app.Use(func(ctx context.Context) {
|
||||
ctx.Application().Log("Begin request for path: %s", ctx.Path())
|
||||
ctx.Next()
|
||||
})
|
||||
|
||||
// app.Done(func(ctx context.Context) {})
|
||||
|
||||
// Method POST: http://localhost:8080/decode
|
||||
app.Post("/decode", func(ctx context.Context) {
|
||||
var user User
|
||||
ctx.ReadJSON(&user)
|
||||
ctx.Writef("%s %s is %d years old and comes from %s", user.Firstname, user.Lastname, user.Age, user.City)
|
||||
})
|
||||
|
||||
// Method GET: http://localhost:8080/encode
|
||||
app.Get("/encode", func(ctx context.Context) {
|
||||
doe := User{
|
||||
Username: "Johndoe",
|
||||
Firstname: "John",
|
||||
Lastname: "Doe",
|
||||
City: "Neither FBI knows!!!",
|
||||
Age: 25,
|
||||
}
|
||||
|
||||
ctx.JSON(doe)
|
||||
})
|
||||
|
||||
// Method GET: http://localhost:8080/profile/anytypeofstring
|
||||
app.Get("/profile/{username:string}", profileByUsername)
|
||||
|
||||
usersRoutes := app.Party("/users", logThisMiddleware)
|
||||
{
|
||||
// Method GET: http://localhost:8080/users/42
|
||||
usersRoutes.Get("/{id:int min(1)}", getUserByID)
|
||||
// Method POST: http://localhost:8080/users/create
|
||||
usersRoutes.Post("/create", createUser)
|
||||
}
|
||||
|
||||
// Listen for incoming HTTP/1.x & HTTP/2 clients on localhost port 8080.
|
||||
app.Run(iris.Addr(":8080"), iris.WithCharset("UTF-8"))
|
||||
}
|
||||
|
||||
func logThisMiddleware(ctx context.Context) {
|
||||
ctx.Application().Log("Path: %s | IP: %s", ctx.Path(), ctx.RemoteAddr())
|
||||
|
||||
// .Next is required to move forward to the chain of handlers,
|
||||
// if missing then it stops the execution at this handler.
|
||||
ctx.Next()
|
||||
}
|
||||
|
||||
func profileByUsername(ctx context.Context) {
|
||||
// .Params are used to get dynamic path parameters.
|
||||
username := ctx.Params().Get("username")
|
||||
ctx.ViewData("Username", username)
|
||||
// renders "./views/users/profile.html"
|
||||
// with {{ .Username }} equals to the username dynamic path parameter.
|
||||
ctx.View("users/profile.html")
|
||||
}
|
||||
|
||||
func getUserByID(ctx context.Context) {
|
||||
userID := ctx.Params().Get("id") // Or convert directly using: .Values().GetInt/GetInt64 etc...
|
||||
// your own db fetch here instead of user :=...
|
||||
user := User{Username: "username" + userID}
|
||||
|
||||
ctx.XML(user)
|
||||
}
|
||||
|
||||
func createUser(ctx context.Context) {
|
||||
var user User
|
||||
err := ctx.ReadForm(&user)
|
||||
if err != nil {
|
||||
ctx.Values().Set("error", "creating user, read and parse form failed. "+err.Error())
|
||||
ctx.StatusCode(iris.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
// renders "./views/users/create_verification.html"
|
||||
// with {{ . }} equals to the User object, i.e {{ .Username }} , {{ .Firstname}} etc...
|
||||
ctx.ViewData("", user)
|
||||
ctx.View("users/create_verification.html")
|
||||
}
|
||||
```
|
||||
|
||||
### Reload on source code changes
|
||||
|
||||
```sh
|
||||
$ go get -u github.com/kataras/rizla
|
||||
$ cd $GOPATH/src/mywebapp
|
||||
$ rizla main.go
|
||||
```
|
||||
|
||||
> Psst: Wanna go to [_examples](https://github.com/kataras/iris/tree/master/_examples) to see more code-snippets?
|
||||
|
||||
<details>
|
||||
<summary>Legends</summary>
|
||||
|
||||
I'm sorry for taking this personally but I really need to thanks each one of them because they stood up [♡](https://github.com/kataras/iris#support) for me when others trying to "bullying" my personality in order to deflame Iris.
|
||||
|
||||
All of us should read and repsect the official [golang](https://golang.org/conduct) and [iris](CODE-OF-CONDUCT.md) community **Code of Conduct**. This type of commitment and communication is the way of making Go great.
|
||||
|
||||
<!-- on each chance, i.e when iris posts were trending on sites like dzone and medium they spamming an awful full of lies and deflamation blog post. We all should read and repsect the official golang's and iris' Code of Conduct. -->
|
||||
|
||||
[Juan Sebastián Suárez Valencia](https://github.com/Juanses) donated 20 EUR at September 11 of 2016
|
||||
|
||||
|
@ -73,18 +191,47 @@ Legends [♡](https://github.com/kataras/iris#support)
|
|||
|
||||
[Conrad Steenberg](https://github.com/hengestone) donated 25 EUR at March 23 of 2017
|
||||
|
||||
<!-- ANONYMOUS[*](https://github.com/kataras/iris#support) donated 356 EUR, last anonymous donation at 22 March of 2017
|
||||
// No o need to show anonymous donations here, the full list is still shown at DONATIONS.md.
|
||||
-->
|
||||
<p>
|
||||
|
||||
<a href="https://medium.com/@kataras/a-url-shortener-service-using-go-iris-and-bolt-4182f0b00ae7">
|
||||
<img width="300" src="http://iris-go.com/comment28.png" />
|
||||
</a>
|
||||
|
||||
<a href="https://twitter.com/gelnior/status/769100480706379776">
|
||||
<img width="300" src="http://iris-go.com/comment27.png" />
|
||||
</a>
|
||||
|
||||
<br/>
|
||||
|
||||
<a href="https://www.youtube.com/watch?v=jGx0LkuUs4A">
|
||||
<img width="300" src="https://github.com/iris-contrib/website/raw/gh-pages/assets/gif_link_to_yt.gif" alt="What people say" />
|
||||
</a>
|
||||
|
||||
<a href="https://www.youtube.com/watch?v=jGx0LkuUs4A">
|
||||
<img width ="300" src="https://github.com/iris-contrib/website/raw/gh-pages/assets/gif_link_to_yt2.gif" alt="What people say" />
|
||||
</a>
|
||||
|
||||
<br/>
|
||||
|
||||
<a href="https://twitter.com/_mgale/status/818591490305761280">
|
||||
<img width="300" width="630" src="http://iris-go.com/comment25.png" />
|
||||
</a>
|
||||
|
||||
<a href="https://twitter.com/MeAlex07/status/822799954188075008">
|
||||
<img width="300" width="627" src="http://iris-go.com/comment26.png" />
|
||||
</a>
|
||||
|
||||
</p>
|
||||
|
||||
</details>
|
||||
|
||||
Feature Overview
|
||||
-----------
|
||||
|
||||
- Focus on high performance
|
||||
- Build RESTful APIs with our expressionist path syntax, i.e `{userid:int min(1)}`, `{asset:path}`, `{lowercase: regexp([a-z]+)}`
|
||||
- Automatically install and serve certificates from https://letsencrypt.org
|
||||
- Robust routing and middleware ecosystem
|
||||
- Build RESTful APIs
|
||||
- Choose your favorite routes' path syntax between [httprouter](https://github.com/kataras/iris/blob/v6/_examples/beginner/routes-using-httprouter/main.go) and [gorillamux](https://github.com/kataras/iris/blob/v6/_examples/beginner/routes-using-gorillamux/main.go)
|
||||
- Request-Scoped Transactions
|
||||
- Group API's and subdomains with wildcard support
|
||||
- Body binding for JSON, XML, Forms, can be extended to use your own custom binders
|
||||
|
@ -94,7 +241,7 @@ Feature Overview
|
|||
- Graceful shutdown
|
||||
- Limit request body
|
||||
- Localization i18N
|
||||
- Serve static files
|
||||
- Serve static and embedded files
|
||||
- Cache
|
||||
- Log requests
|
||||
- Customizable format and output for the logger
|
||||
|
@ -122,239 +269,30 @@ Feature Overview
|
|||
- And many others...
|
||||
|
||||
|
||||
Table of Contents
|
||||
Documentation
|
||||
-----------
|
||||
|
||||
<a href="https://github.com/kataras/iris/tree/v6/_examples#table-of-contents"><img align="right" width="265" src="https://raw.githubusercontent.com/iris-contrib/website/gh-pages/assets/book/cover_4.jpg"></a>
|
||||
<a href="https://github.com/kataras/iris/tree/master/_examples#table-of-contents"><img width="155" src="https://raw.githubusercontent.com/iris-contrib/website/gh-pages/assets/book/cover_4.jpg"></a>
|
||||
|
||||
Small but practical [examples](https://github.com/kataras/iris/tree/master/_examples#table-of-contents) --they cover each feature.
|
||||
|
||||
* [Level: Beginner](_examples/beginner)
|
||||
* [Hello World](_examples/beginner/hello-world/main.go)
|
||||
* [Routes (using httprouter)](_examples/beginner/routes-using-httprouter/main.go)
|
||||
* [Routes (using gorillamux)](_examples/beginner/routes-using-gorillamux/main.go)
|
||||
* [Internal Application File Logger](_examples/beginner/file-logger/main.go)
|
||||
* [Write JSON](_examples/beginner/write-json/main.go)
|
||||
* [Read JSON](_examples/beginner/read-json/main.go)
|
||||
* [Read Form](_examples/beginner/read-form/main.go)
|
||||
* [Favicon](_examples/beginner/favicon/main.go)
|
||||
* [File Server](_examples/beginner/file-server/main.go)
|
||||
* [Send Files](_examples/beginner/send-files/main.go)
|
||||
* [Stream Writer](_examples/beginner/stream-writer/main.go)
|
||||
* [Listen UNIX Socket](_examples/beginner/listen-unix/main.go)
|
||||
* [Listen TLS](_examples/beginner/listen-tls/main.go)
|
||||
* [Listen Letsencrypt (Automatic Certifications)](_examples/beginner/listen-letsencrypt/main.go)
|
||||
* [Level: Intermediate](_examples/intermediate)
|
||||
* [Send An E-mail](_examples/intermediate/e-mail/main.go)
|
||||
* [Upload/Read Files](_examples/intermediate/upload-files/main.go)
|
||||
* [Request Logger](_examples/intermediate/request-logger/main.go)
|
||||
* [Profiling (pprof)](_examples/intermediate/pprof/main.go)
|
||||
* [Basic Authentication](_examples/intermediate/basicauth/main.go)
|
||||
* [HTTP Access Control](_examples/intermediate/cors/main.go)
|
||||
* [Cache Markdown](_examples/intermediate/cache-markdown/main.go)
|
||||
* [Localization and Internationalization](_examples/intermediate/i18n/main.go)
|
||||
* [Recovery](_examples/intermediate/recover/main.go)
|
||||
* [Graceful Shutdown](_examples/intermediate/graceful-shutdown/main.go)
|
||||
* [Custom TCP Listener](_examples/intermediate/custom-listener/main.go)
|
||||
* [Custom HTTP Server](_examples/intermediate/custom-httpserver/main.go)
|
||||
* [View Engine](_examples/intermediate/view)
|
||||
* [Overview](_examples/intermediate/view/overview/main.go)
|
||||
* [Template HTML: Part Zero](_examples/intermediate/view/template_html_0/main.go)
|
||||
* [Template HTML: Part One](_examples/intermediate/view/template_html_1/main.go)
|
||||
* [Template HTML: Part Two](_examples/intermediate/view/template_html_2/main.go)
|
||||
* [Template HTML: Part Three](_examples/intermediate/view/template_html_3/main.go)
|
||||
* [Template HTML: Part Four](_examples/intermediate/view/template_html_4/main.go)
|
||||
* [Inject Data Between Handlers](_examples/intermediate/view/context-view-data/main.go)
|
||||
* [Embedding Templates Into Executable](_examples/intermediate/view/embedding-templates-into-app)
|
||||
* [Custom Renderer](_examples/intermediate/view/custom-renderer/main.go)
|
||||
* [Password Hashing](_examples/intermediate/password-hashing/main.go)
|
||||
* [Sessions](_examples/intermediate/sessions)
|
||||
* [Overview](_examples/intermediate/sessions/overview/main.go)
|
||||
* [Encoding & Decoding the Session ID: Secure Cookie](_examples/intermediate/sessions/securecookie/main.go)
|
||||
* [Standalone](_examples/intermediate/sessions/standalone/main.go)
|
||||
* [With A Back-End Database](_examples/intermediate/sessions/database/main.go)
|
||||
* [Flash Messages](_examples/intermediate/flash-messages/main.go)
|
||||
* [Websockets](_examples/intermediate/websockets)
|
||||
* [Ridiculous Simple](_examples/intermediate/websockets/ridiculous-simple/main.go)
|
||||
* [Overview](_examples/intermediate/websockets/overview/main.go)
|
||||
* [Connection List](_examples/intermediate/websockets/connectionlist/main.go)
|
||||
* [Native Messages](_examples/intermediate/websockets/naive-messages/main.go)
|
||||
* [Secure](_examples/intermediate/websockets/secure/main.go)
|
||||
* [Custom Go Client](_examples/intermediate/websockets/custom-go-client/main.go)
|
||||
* [Level: Advanced](_examples/advanced)
|
||||
* [Transactions](_examples/advanced/transactions/main.go)
|
||||
* [HTTP Testing](_examples/advanced/httptest/main_test.go)
|
||||
* [Watch & Compile Typescript source files](_examples/advanced/typescript/main.go)
|
||||
* [Cloud Editor](_examples/advanced/cloud-editor/main.go)
|
||||
* [Online Visitors](_examples/advanced/online-visitors/main.go)
|
||||
* [URL Shortener using BoltDB](_examples/advanced/url-shortener/main.go)
|
||||
* [Subdomains](_examples/advanced/subdomains)
|
||||
* [Single](_examples/advanced/subdomains/single/main.go)
|
||||
* [Multi](_examples/advanced/subdomains/multi/main.go)
|
||||
* [Wildcard](_examples/advanced/subdomains/wildcard/main.go)
|
||||
|
||||
Installation
|
||||
-----------
|
||||
|
||||
The only requirement is the [Go Programming Language](https://golang.org/dl/), at least 1.8
|
||||
|
||||
```sh
|
||||
$ go get gopkg.in/kataras/iris.v6
|
||||
```
|
||||
|
||||
Overview
|
||||
-----------
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/cors"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/view"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// Receives optional iris.Configuration{}, see ./configuration.go
|
||||
// for more.
|
||||
app := iris.New()
|
||||
|
||||
// Order doesn't matter,
|
||||
// You can split it to different .Adapt calls.
|
||||
// See ./adaptors folder for more.
|
||||
app.Adapt(
|
||||
// adapt a logger which prints all errors to the os.Stdout
|
||||
iris.DevLogger(),
|
||||
// adapt the adaptors/httprouter or adaptors/gorillamux
|
||||
httprouter.New(),
|
||||
// 5 template engines are supported out-of-the-box:
|
||||
//
|
||||
// - standard html/template
|
||||
// - amber
|
||||
// - django
|
||||
// - handlebars
|
||||
// - pug(jade)
|
||||
//
|
||||
// Use the html standard engine for all files inside "./views" folder with extension ".html"
|
||||
view.HTML("./views", ".html"),
|
||||
// Cors wrapper to the entire application, allow all origins.
|
||||
cors.New(cors.Options{AllowedOrigins: []string{"*"}}))
|
||||
|
||||
// http://localhost:6300
|
||||
// Method: "GET"
|
||||
// Render ./views/index.html
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
ctx.Render("index.html", iris.Map{"Title": "Page Title"}, iris.RenderOptions{"gzip": true})
|
||||
})
|
||||
|
||||
// Group routes, optionally: share middleware, template layout and custom http errors.
|
||||
userAPI := app.Party("/users", userAPIMiddleware).
|
||||
Layout("layouts/userLayout.html")
|
||||
{
|
||||
// Fire userNotFoundHandler when Not Found
|
||||
// inside http://localhost:6300/users/*anything
|
||||
userAPI.OnError(404, userNotFoundHandler)
|
||||
|
||||
// http://localhost:6300/users
|
||||
// Method: "GET"
|
||||
userAPI.Get("/", getAllHandler)
|
||||
|
||||
// http://localhost:6300/users/42
|
||||
// Method: "GET"
|
||||
userAPI.Get("/:id", getByIDHandler)
|
||||
|
||||
// http://localhost:6300/users
|
||||
// Method: "POST"
|
||||
userAPI.Post("/", saveUserHandler)
|
||||
}
|
||||
|
||||
// Start the server at 127.0.0.1:6300
|
||||
app.Listen(":6300")
|
||||
}
|
||||
|
||||
func userAPIMiddleware(ctx *iris.Context) {
|
||||
// your code here...
|
||||
println("Request: " + ctx.Path())
|
||||
ctx.Next() // go to the next handler(s)
|
||||
}
|
||||
|
||||
func userNotFoundHandler(ctx *iris.Context) {
|
||||
// your code here...
|
||||
ctx.HTML(iris.StatusNotFound, "<h1> User page not found </h1>")
|
||||
}
|
||||
|
||||
func getAllHandler(ctx *iris.Context) {
|
||||
// your code here...
|
||||
}
|
||||
|
||||
func getByIDHandler(ctx *iris.Context) {
|
||||
// take the :id from the path, parse to integer
|
||||
// and set it to the new userID local variable.
|
||||
userID, _ := ctx.ParamInt("id")
|
||||
|
||||
// userRepo, imaginary database service <- your only job.
|
||||
user := userRepo.GetByID(userID)
|
||||
|
||||
// send back a response to the client,
|
||||
// .JSON: content type as application/json; charset="utf-8"
|
||||
// iris.StatusOK: with 200 http status code.
|
||||
//
|
||||
// send user as it is or make use of any json valid golang type,
|
||||
// like the iris.Map{"username" : user.Username}.
|
||||
ctx.JSON(iris.StatusOK, user)
|
||||
}
|
||||
|
||||
func saveUserHandler(ctx *iris.Context) {
|
||||
// your code here...
|
||||
}
|
||||
```
|
||||
|
||||
### Reload on source code changes
|
||||
|
||||
```sh
|
||||
$ go get -u github.com/kataras/rizla
|
||||
$ cd $GOPATH/src/mywebapp
|
||||
$ rizla main.go
|
||||
```
|
||||
|
||||
### Reload templates on each incoming request
|
||||
|
||||
```go
|
||||
app.Adapt(view.HTML("./views", ".html").Reload(true))
|
||||
```
|
||||
|
||||
|
||||
FAQ & Documentation
|
||||
-----------
|
||||
|
||||
<a href="https://github.com/kataras/iris/tree/v6/_examples#table-of-contents"><img align="right" width="125" src="https://raw.githubusercontent.com/iris-contrib/website/gh-pages/assets/book/cover_4.jpg"></a>
|
||||
|
||||
1. [Getting Started with Go+Iris](http://gopherbook.iris-go.com)
|
||||
|
||||
2. Official small but practical [examples](https://github.com/kataras/iris/tree/v6/_examples#table-of-contents)
|
||||
|
||||
3. Navigate through [community examples](https://github.com/iris-contrib/examples) too
|
||||
|
||||
4. [Creating A URL Shortener Service Using Go, Iris, and Bolt](https://medium.com/@kataras/a-url-shortener-service-using-go-iris-and-bolt-4182f0b00ae7)
|
||||
|
||||
5. [Godocs](https://godoc.org/gopkg.in/kataras/iris.v6) for deep documentation
|
||||
|
||||
6. [HISTORY.md](https://github.com//kataras/iris/tree/v6/HISTORY.md) is your best friend, version migrations are released there
|
||||
|
||||
|
||||
I'll be glad to talk with you about **your awesome feature requests**,
|
||||
open a new [discussion](http://support.iris-go.com), you will be heard!
|
||||
Wanna create your own fast URL Shortener Service Using Iris? --click [here](https://medium.com/@kataras/a-url-shortener-service-using-go-iris-and-bolt-4182f0b00ae7) to learn how.
|
||||
|
||||
[Godocs](https://godoc.org/github.com/kataras/iris) --for deep understanding.
|
||||
|
||||
|
||||
Support
|
||||
------------
|
||||
|
||||
- :star: [the project](https://github.com/kataras/iris/stargazers), will help you to follow the upcoming features
|
||||
- [Donate](https://github.com/kataras/iris#buy-me-a-cup-of-coffee), will help me to continue
|
||||
- [Post](http://support.iris-go.com) a feature request or report a bug, will help all of us to build a better web, together
|
||||
- :earth_americas: post [an article](https://dzone.com/articles/a-url-shortener-service-using-go-iris-and-bolt-ger) or [tweet](https://twitter.com/gelnior/status/769100480706379776) and share it with your neighbor
|
||||
- [Post](http://support.iris-go.com) a feature request or report a bug, will help to make the framework even better.
|
||||
- :star: and watch [the project](https://github.com/kataras/iris/stargazers), will notify you about updates.
|
||||
- :earth_americas: publish [an article](https://medium.com/) or share a [tweet](https://twitter.com/) about Iris.
|
||||
- Donations, will help me to continue.
|
||||
|
||||
I'll be glad to talk with you about **your awesome feature requests**,
|
||||
open a new [discussion](http://support.iris-go.com), you will be heard!
|
||||
|
||||
Thanks in advance!
|
||||
|
||||
Buy me a cup of coffee?
|
||||
------------
|
||||
|
@ -364,21 +302,40 @@ Iris is free and open source but developing it has taken thousands of hours of m
|
|||
|
||||
I spend all my time in the construction of Iris, therefore I have no income value.
|
||||
|
||||
Feel free to send **any** amount through paypal
|
||||
Feel free to send **any** amount through paypal:
|
||||
|
||||
[![](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=kataras2006%40hotmail%2ecom&lc=GR&item_name=Iris%20web%20framework&item_number=iriswebframeworkdonationid2016¤cy_code=EUR&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted)
|
||||
|
||||
> Please check your e-mail after your donation.
|
||||
|
||||
|
||||
Thanks for your gratitude and finance help ♡
|
||||
<!--
|
||||
|
||||
Some of the benefits are listed here:
|
||||
|
||||
- Your github username, after your approval, is visible at the top of the README page.
|
||||
- Access to the 'donors' [private chat room](https://kataras.rocket.chat/group/donors) gives you real-time assistance by Iris' Author.
|
||||
|
||||
-->
|
||||
|
||||
<!--
|
||||
|
||||
### Become An Iris Sponsor
|
||||
|
||||
Want to add your company's logo to our [website](http://iris-go.com)?
|
||||
|
||||
Please contact me via email: kataras2006@hotmail.com
|
||||
|
||||
Thank you!
|
||||
|
||||
-->
|
||||
|
||||
Third Party Middleware
|
||||
------------
|
||||
|
||||
Iris has its own middleware form of `func(ctx *iris.Context)` but it's also compatible with all `net/http` middleware forms using [iris.ToHandler](https://github.com/iris-contrib/middleware/blob/master/cors/cors.go#L33), i.e Negroni's middleware form of `func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)`.
|
||||
Iris has its own middleware form of `func(ctx context.Context)` but it's also compatible with all `net/http` middleware forms. See [here](https://github.com/kataras/iris/blob/master/_examples/beginner/convert-handlers/negroni-like/main.go).
|
||||
|
||||
Here is a small list of Iris compatible middleware, I'm sure you can find more:
|
||||
I'm sure that each of you have, already, found his own favorite list but here's a small list of third-party handlers:
|
||||
|
||||
| Middleware | Author | Description |
|
||||
| -----------|--------|-------------|
|
||||
|
@ -406,32 +363,16 @@ Feel free to put up a [PR](https://github.com/iris-contrib/middleware) your midd
|
|||
Testing
|
||||
------------
|
||||
|
||||
The `httptest` package is a simple Iris helper for the httpexpect, a new library for End-to-end HTTP and REST API testing for Go.
|
||||
The `httptest` package is your way for end-to-end HTTP testing, it uses the httpexpect library created by our friend, [gavv](https://github.com/gavv).
|
||||
|
||||
You can find tests by navigating to the source code,
|
||||
i.e:
|
||||
|
||||
- [context_test.go](https://github.com/kataras/iris/blob/v6/context_test.go)
|
||||
- [handler_test.go](https://github.com/kataras/iris/blob/v6/handler_test.go)
|
||||
- [policy_gorillamux_test.go](https://github.com/kataras/iris/blob/v6/policy_gorillamux_test.go)
|
||||
- [policy_httprouter_test.go](https://github.com/kataras/iris/blob/v6/policy_httprouter_test.go)
|
||||
- [policy_nativerouter_test.go](https://github.com/kataras/iris/blob/v6/policy_nativerouter_test.go)
|
||||
- [policy_routerwrapper_test.go](https://github.com/kataras/iris/blob/v6/policy_routerwrapper_test.go)
|
||||
- [policy_sessions_test.go](https://github.com/kataras/iris/blob/v6/policy_sessions_test.go)
|
||||
- [response_writer_test.go](https://github.com/kataras/iris/blob/v6/response_writer_test.go)
|
||||
- [route_test.go](https://github.com/kataras/iris/blob/v6/route_test.go)
|
||||
- [status_test.go](https://github.com/kataras/iris/blob/v6/status_test.go)
|
||||
- [transaction_test.go](https://github.com/kataras/iris/blob/v6/transaction_test.go)
|
||||
- [serializer_test.go](https://github.com/kataras/iris/blob/v6/serializer_test.go)
|
||||
|
||||
A simple test is located to [./_examples/advanced/httptest/main_test.go](https://github.com/kataras/iris/blob/v6/_examples/advanced/httptest/main_test.go)
|
||||
A simple test is located to [./_examples/intermediate/httptest/main_test.go](https://github.com/kataras/iris/blob/master/_examples/intermediate/httptest/main_test.go)
|
||||
|
||||
Philosophy
|
||||
------------
|
||||
|
||||
The Iris philosophy is to provide robust tooling for HTTP, making it a great solution for single page applications, web sites, hybrids, or public HTTP APIs. Keep note that, today, iris is faster than nginx itself.
|
||||
The Iris philosophy is to provide robust tooling for HTTP, making it a great solution for single page applications, web sites, hybrids, or public HTTP APIs. Keep note that, today, iris is faster than apache+nginx itself.
|
||||
|
||||
Iris does not force you to use any specific ORM or template engine. Iris is routerless which means you can adapt any router you like, [httprouter](https://github.com/kataras/iris/blob/v6/_examples/beginner/routes-using-httprouter/main.go) is the fastest, [gorillamux](https://github.com/kataras/iris/blob/v6/_examples/beginner/routes-using-gorillamux/main.go) has more features. With support for the most used template engines (5), you can quickly craft the perfect application.
|
||||
Iris does not force you to use any specific ORM or template engine. With support for the most popular template engines, you can quickly craft your perfect application.
|
||||
|
||||
|
||||
People
|
||||
|
@ -441,7 +382,6 @@ The author of Iris is [@kataras](https://github.com/kataras).
|
|||
|
||||
However the real Success of Iris belongs to you with your bug reports and feature requests that made this Framework so Unique.
|
||||
|
||||
|
||||
Contact
|
||||
------------
|
||||
|
||||
|
@ -451,18 +391,39 @@ Besides the fact that we have a [community chat][Chat] for questions or reports
|
|||
- [Facebook](https://facebook.com/kataras.gopher)
|
||||
- [Linkedin](https://www.linkedin.com/in/gerasimos-maropoulos)
|
||||
|
||||
|
||||
Codename: ["√Νεxτ"](https://github.com/kataras/iris/blob/v6/HISTORY.md)
|
||||
Version
|
||||
------------
|
||||
|
||||
Current: v7
|
||||
|
||||
Each new release is pushed to the master. It stays there until the next version. When a next version is released then the previous version goes to its own branch with `gopkg.in` as its import path (and its own vendor folder), in order to keep it working "for-ever".
|
||||
|
||||
Community members can request additional features or report a bug fix for a specific iris version.
|
||||
|
||||
|
||||
### Should I upgrade my Iris?
|
||||
|
||||
Developers are not forced to use the latest Iris version, they can use any version in production, they can update at any time they want.
|
||||
|
||||
Testers should upgrade immediately, if you're willing to use Iris in production you can wait a little more longer, transaction should be as safe as possible.
|
||||
|
||||
### Where can I find older versions?
|
||||
|
||||
Each Iris version is independent. Only bug fixes, Router's API and experience are kept.
|
||||
|
||||
Previous versions can be found at [releases page](https://github.com/kataras/iris/releases).
|
||||
|
||||
License
|
||||
------------
|
||||
|
||||
Unless otherwise noted, the source files are distributed
|
||||
under the MIT License found in the [LICENSE file](LICENSE).
|
||||
under the BSD-3-Clause License found in the [LICENSE file](LICENSE).
|
||||
|
||||
Note that some optional components that you may use with Iris requires
|
||||
Note that some third-party packages that you use with Iris may requires
|
||||
different license agreements.
|
||||
|
||||
|
||||
[Chat]: https://kataras.rocket.chat/channel/iris
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
|
@ -1,18 +1,34 @@
|
|||
# Examples
|
||||
|
||||
This folder provides easy to understand code snippets on how to get started with web development with the Go programming language using the [Iris](https://github.com/kataras/iris) web framework.
|
||||
This folder provides easy to understand code snippets on how to get started with web development with the Go programming language using the [Iris](https://github.com/kataras/iris) web framework.
|
||||
|
||||
It doesn't contains "best ways" neither explains all its features. It's just a simple, practical cookbook for young Go developers!
|
||||
It doesn't contains "best ways" neither explains all its features. It's just a simple, practical cookbook for young Gophers!
|
||||
|
||||
## Table of Contents
|
||||
<!-- when the new book will be ready I should add the link here -->
|
||||
<img align="right" src="http://iris-go.com/assets/book/cover_4.jpg" width="300" />
|
||||
## Table of contents
|
||||
|
||||
* [Level: Beginner](beginner)
|
||||
* [Hello World](beginner/hello-world/main.go)
|
||||
* [Routes (using httprouter)](beginner/routes-using-httprouter/main.go)
|
||||
* [Routes (using gorillamux)](beginner/routes-using-gorillamux/main.go)
|
||||
* [Overview](beginner/overview/main.go)
|
||||
* [Listening](beginner/listening)
|
||||
* [Common, with address](beginner/listening/listen-addr/main.go)
|
||||
* [UNIX socket file](beginner/listening/listen-unix/main.go)
|
||||
* [TLS](beginner/listening/listen-tls)
|
||||
* [Letsencrypt (Automatic Certifications)](beginner/listening/listen-letsencrypt/main.go)
|
||||
* [Custom TCP Listener](beginner/listening/custom-listener/main.go)
|
||||
* [Configuration](beginner/configuration)
|
||||
* [Basic way](beginner/configuration/basic/main.go)
|
||||
* [Functional way](beginner/configuration/functional/main.go)
|
||||
* [Import from YAML file](beginner/configuration/from-yaml-file/main.go)
|
||||
* [Import from TOML file](beginner/configuration/from-toml-file/main.go)
|
||||
* [Routing](beginner/routing)
|
||||
* [Overview](beginner/routing/main.go)
|
||||
* [Basic](beginner/routing/basic/main.go)
|
||||
* [Dynamic Path](beginner/routing/dynamic-path/main.go)
|
||||
* [Reverse routing](beginner/routing/reverse/main.go)
|
||||
* [Transform any third-party handler to iris-compatible handler](beginner/convert-handlers)
|
||||
* [From func(http.ResponseWriter, *http.Request, http.HandlerFunc)](beginner/convert-handlers/negroni-like/main.go)
|
||||
* [From http.Handler or http.HandlerFunc](beginner/convert-handlers/nethttp/main.go)
|
||||
* [Internal Application File Logger](beginner/file-logger/main.go)
|
||||
* [Custom HTTP Errors](beginner/http-errors/main.go)
|
||||
* [Write JSON](beginner/write-json/main.go)
|
||||
* [Read JSON](beginner/read-json/main.go)
|
||||
* [Read Form](beginner/read-form/main.go)
|
||||
|
@ -20,38 +36,46 @@ It doesn't contains "best ways" neither explains all its features. It's just a s
|
|||
* [File Server](beginner/file-server/main.go)
|
||||
* [Send Files](beginner/send-files/main.go)
|
||||
* [Stream Writer](beginner/stream-writer/main.go)
|
||||
* [Listen UNIX Socket](beginner/listen-unix/main.go)
|
||||
* [Listen TLS](beginner/listen-tls/main.go)
|
||||
* [Listen Letsencrypt (Automatic Certifications)](beginner/listen-letsencrypt/main.go)
|
||||
* [Send An E-mail](beginner/e-mail/main.go)
|
||||
* [Upload/Read Files](beginner/upload-files/main.go)
|
||||
* [Recovery](beginner/recover/main.go)
|
||||
* [Profiling (pprof)](beginner/pprof/main.go)
|
||||
* [Request Logger](beginner/request-logger/main.go)
|
||||
* [Basic Authentication](beginner/basicauth/main.go)
|
||||
* [Level: Intermediate](intermediate)
|
||||
* [Send An E-mail](intermediate/e-mail/main.go)
|
||||
* [Upload/Read Files](intermediate/upload-files/main.go)
|
||||
* [Request Logger](intermediate/request-logger/main.go)
|
||||
* [Profiling (pprof)](intermediate/pprof/main.go)
|
||||
* [Basic Authentication](intermediate/basicauth/main.go)
|
||||
* [Transactions](intermediate/transactions/main.go)
|
||||
* [HTTP Testing](intermediate/httptest/main_test.go)
|
||||
* [Watch & Compile Typescript source files](intermediate/typescript/main.go)
|
||||
* [Cloud Editor](intermediate/cloud-editor/main.go)
|
||||
* [Serve Embedded Files](intermediate/serve-embedded-files/main.go)
|
||||
* [HTTP Access Control](intermediate/cors/main.go)
|
||||
* [Cache Markdown](intermediate/cache-markdown/main.go)
|
||||
* [Localization and Internationalization](intermediate/i18n/main.go)
|
||||
* [Recovery](intermediate/recover/main.go)
|
||||
* [Graceful Shutdown](intermediate/graceful-shutdown/main.go)
|
||||
* [Custom TCP Listener](intermediate/custom-listener/main.go)
|
||||
* [Custom HTTP Server](intermediate/custom-httpserver/main.go)
|
||||
* [Graceful Shutdown](intermediate/graceful-shutdown)
|
||||
* [Basic and simple](intermediate/graceful-shutdown/basic/main.go)
|
||||
* [Custom Host](intermediate/graceful-shutdown/custom-host/main.go)
|
||||
* [Custom HTTP Server](intermediate/custom-httpserver)
|
||||
* [Iris way](intermediate/custom-httpserver/iris-way/main.go)
|
||||
* [Standar way](intermediate/custom-httpserver/std-way/main.go)
|
||||
* [More than one server](intermediate/custom-httpserver/multi/main.go)
|
||||
* [Custom Context](intermediate/custom-context)
|
||||
* [Method Overriding](intermediate/custom-context/method-overriding/main.go)
|
||||
* [Route State](intermediate/route-state/main.go)
|
||||
* [View Engine](intermediate/view)
|
||||
* [Overview](intermediate/view/overview/main.go)
|
||||
* [Template HTML: Part Zero](intermediate/view/template_html_0/main.go)
|
||||
* [Template HTML: Part One](intermediate/view/template_html_1/main.go)
|
||||
* [Template HTML: Part Two](intermediate/view/template_html_2/main.go)
|
||||
* [Template HTML: Part Three](intermediate/view/template_html_3/main.go)
|
||||
* [Template HTML: Part Four](intermediate/view/template_html_4/main.go)
|
||||
* [Hi](intermediate/view/template_html_0/main.go)
|
||||
* [Showcase one simple Layout](intermediate/view/template_html_1/main.go)
|
||||
* [Layouts `yield` and `render` tmpl funcs](intermediate/view/template_html_2/main.go)
|
||||
* [Showcase of the `urlpath` tmpl func](intermediate/view/template_html_3/main.go)
|
||||
* [Showcase of the `url` tmpl func](intermediate/view/template_html_4/main.go)
|
||||
* [Inject Data Between Handlers](intermediate/view/context-view-data/main.go)
|
||||
* [Embedding Templates Into Executable](intermediate/view/embedding-templates-into-app)
|
||||
* [Custom Renderer](intermediate/view/custom-renderer/main.go)
|
||||
* [Password Hashing](intermediate/password-hashing/main.go)
|
||||
* [Embedding Templates Into App Executable File](intermediate/view/embedding-templates-into-app)
|
||||
* [Sessions](intermediate/sessions)
|
||||
* [Overview](intermediate/sessions/overview/main.go)
|
||||
* [Encoding & Decoding the Session ID: Secure Cookie](intermediate/sessions/securecookie/main.go)
|
||||
* [Standalone](intermediate/sessions/standalone/main.go)
|
||||
* [With A Back-End Database](intermediate/sessions/database/main.go)
|
||||
* [Password Hashing](intermediate/sessions/password-hashing/main.go)
|
||||
* [Flash Messages](intermediate/flash-messages/main.go)
|
||||
* [Websockets](intermediate/websockets)
|
||||
* [Ridiculous Simple](intermediate/websockets/ridiculous-simple/main.go)
|
||||
|
@ -60,20 +84,14 @@ It doesn't contains "best ways" neither explains all its features. It's just a s
|
|||
* [Native Messages](intermediate/websockets/naive-messages/main.go)
|
||||
* [Secure](intermediate/websockets/secure/main.go)
|
||||
* [Custom Go Client](intermediate/websockets/custom-go-client/main.go)
|
||||
* [Subdomains](intermediate/subdomains)
|
||||
* [Single](intermediate/subdomains/single/main.go)
|
||||
* [Multi](intermediate/subdomains/multi/main.go)
|
||||
* [Wildcard](intermediate/subdomains/wildcard/main.go)
|
||||
* [Level: Advanced](advanced)
|
||||
* [Transactions](advanced/transactions/main.go)
|
||||
* [HTTP Testing](advanced/httptest/main_test.go)
|
||||
* [Watch & Compile Typescript source files](advanced/typescript/main.go)
|
||||
* [Cloud Editor](advanced/cloud-editor/main.go)
|
||||
* [Online Visitors](advanced/online-visitors/main.go)
|
||||
* [URL Shortener using BoltDB](advanced/url-shortener/main.go)
|
||||
* [Subdomains](advanced/subdomains)
|
||||
* [Single](advanced/subdomains/single/main.go)
|
||||
* [Multi](advanced/subdomains/multi/main.go)
|
||||
* [Wildcard](advanced/subdomains/wildcard/main.go)
|
||||
|
||||
> Do not forget to [star or watch the project](https://github.com/kataras/iris/stargazers) in order to stay updated with the latest tech trends, it takes some seconds for the sake of go!
|
||||
|
||||
|
||||
> Don't forget to take a quick look or add your own [examples in the community's repository](https://github.com/iris-contrib/examples)!
|
||||
|
||||
> Developers should read the official [documentation](https://godoc.org/gopkg.in/kataras/iris.v6), in depth, for better understanding.
|
||||
> Developers should read the official [documentation](https://godoc.org/github.com/kataras/iris) in depth, for deep understanding.
|
||||
|
|
|
@ -1,41 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/sessions"
|
||||
)
|
||||
|
||||
func newApp() *iris.Framework {
|
||||
app := iris.New()
|
||||
app.Adapt(httprouter.New())
|
||||
app.Adapt(sessions.New(sessions.Config{Cookie: "mysessionid"}))
|
||||
|
||||
app.Get("/hello", func(ctx *iris.Context) {
|
||||
sess := ctx.Session()
|
||||
if !sess.HasFlash() /* or sess.GetFlash("name") == "", same thing here */ {
|
||||
ctx.HTML(iris.StatusUnauthorized, "<h1> Unauthorized Page! </h1>")
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(iris.StatusOK, iris.Map{
|
||||
"Message": "Hello",
|
||||
"From": sess.GetFlash("name"),
|
||||
})
|
||||
})
|
||||
|
||||
app.Post("/login", func(ctx *iris.Context) {
|
||||
sess := ctx.Session()
|
||||
if !sess.HasFlash() {
|
||||
sess.SetFlash("name", ctx.FormValue("name"))
|
||||
}
|
||||
// let's no redirect, just set the flash message, nothing more.
|
||||
})
|
||||
|
||||
return app
|
||||
}
|
||||
|
||||
func main() {
|
||||
app := newApp()
|
||||
app.Listen(":8080")
|
||||
}
|
|
@ -3,30 +3,27 @@ package main
|
|||
import (
|
||||
"sync/atomic"
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/view"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/websocket"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
|
||||
"github.com/kataras/iris/view"
|
||||
"github.com/kataras/iris/websocket"
|
||||
)
|
||||
|
||||
var (
|
||||
app *iris.Framework
|
||||
app *iris.Application
|
||||
ws websocket.Server
|
||||
)
|
||||
|
||||
func init() {
|
||||
// init the server instance
|
||||
app = iris.New()
|
||||
// adapt a logger in dev mode
|
||||
app.Adapt(iris.DevLogger())
|
||||
// adapt router
|
||||
app.Adapt(httprouter.New())
|
||||
// adapt templaes
|
||||
app.Adapt(view.HTML("./templates", ".html").Reload(true))
|
||||
// adapt websocket
|
||||
// load templaes
|
||||
app.AttachView(view.HTML("./templates", ".html").Reload(true))
|
||||
// attach websocket server
|
||||
ws = websocket.New(websocket.Config{Endpoint: "/my_endpoint"})
|
||||
ws.OnConnection(HandleWebsocketConnection)
|
||||
app.Adapt(ws)
|
||||
ws.Attach(app)
|
||||
}
|
||||
|
||||
type page struct {
|
||||
|
@ -36,21 +33,23 @@ type page struct {
|
|||
func main() {
|
||||
app.StaticWeb("/js", "./static/assets/js")
|
||||
|
||||
h := func(ctx *iris.Context) {
|
||||
ctx.Render("index.html", page{PageID: "index page"})
|
||||
h := func(ctx context.Context) {
|
||||
ctx.ViewData("", page{PageID: "index page"})
|
||||
ctx.View("index.html")
|
||||
}
|
||||
|
||||
h2 := func(ctx *iris.Context) {
|
||||
ctx.Render("other.html", page{PageID: "other page"})
|
||||
h2 := func(ctx context.Context) {
|
||||
ctx.ViewData("", page{PageID: "other page"})
|
||||
ctx.View("other.html")
|
||||
}
|
||||
|
||||
// Open some browser tabs/or windows
|
||||
// and navigate to
|
||||
// http://localhost:8080/ and http://localhost:8080/other
|
||||
// http://localhost:8080/ and http://localhost:8080/other multiple times.
|
||||
// Each page has its own online-visitors counter.
|
||||
app.Get("/", h)
|
||||
app.Get("/other", h2)
|
||||
app.Listen(":8080")
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
type pageView struct {
|
||||
|
|
|
@ -1,39 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(iris.DevLogger())
|
||||
// subdomains works with all available routers, like other features too.
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
/*
|
||||
* Setup static files
|
||||
*/
|
||||
|
||||
app.StaticWeb("/assets", "./public/assets")
|
||||
app.StaticWeb("/upload_resources", "./public/upload_resources")
|
||||
|
||||
dashboard := app.Party("dashboard.")
|
||||
{
|
||||
dashboard.Get("/", func(ctx *iris.Context) {
|
||||
ctx.Writef("HEY FROM dashboard")
|
||||
})
|
||||
}
|
||||
system := app.Party("system.")
|
||||
{
|
||||
system.Get("/", func(ctx *iris.Context) {
|
||||
ctx.Writef("HEY FROM system")
|
||||
})
|
||||
}
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
ctx.Writef("HEY FROM frontend /")
|
||||
})
|
||||
/* test this on firefox, because the domain is not real (because of .local), on firefox this will fail, but you can test it with other domain */
|
||||
app.Listen("domain.local:80") // for beginners: look ../hosts file
|
||||
}
|
|
@ -13,21 +13,11 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/boltdb/bolt"
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/view"
|
||||
)
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
|
||||
// a custom Iris event policy, which will run when server interruped (i.e control+C)
|
||||
// receives a func() error, most of packages are compatible with that on their Close/Shutdown/Cancel funcs.
|
||||
func releaser(r func() error) iris.EventPolicy {
|
||||
return iris.EventPolicy{
|
||||
Interrupted: func(app *iris.Framework) {
|
||||
if err := r(); err != nil {
|
||||
app.Log(iris.ProdMode, "error while releasing resources: "+err.Error())
|
||||
}
|
||||
}}
|
||||
}
|
||||
"github.com/kataras/iris/view"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
@ -36,83 +26,77 @@ func main() {
|
|||
db := NewDB("shortener.db")
|
||||
factory := NewFactory(DefaultGenerator, db)
|
||||
|
||||
app.Adapt(
|
||||
// print all kind of errors and logs at os.Stdout
|
||||
iris.DevLogger(),
|
||||
// use the httprouter, you can use adpaotrs/gorillamux if you want
|
||||
httprouter.New(),
|
||||
// serve the "./templates" directory's "*.html" files with the HTML std view engine.
|
||||
view.HTML("./templates", ".html").Reload(true),
|
||||
// `db.Close` is a `func() error` so it can be a `releaser` too.
|
||||
// Wrap the db.Close with the releaser in order to be released when app exits or control+C
|
||||
// You probably never saw that before, clever pattern which I am able to use only with Iris :)
|
||||
releaser(db.Close),
|
||||
)
|
||||
|
||||
// serve the "./templates" directory's "*.html" files with the HTML std view engine.
|
||||
tmpl := view.HTML("./templates", ".html").Reload(true)
|
||||
// template funcs
|
||||
//
|
||||
// look ./templates/index.html#L16
|
||||
app.Adapt(iris.TemplateFuncsPolicy{"isPositive": func(n int) bool {
|
||||
tmpl.AddFunc("isPositive", func(n int) bool {
|
||||
if n > 0 {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}})
|
||||
})
|
||||
|
||||
app.AttachView(tmpl)
|
||||
|
||||
// Serve static files (css)
|
||||
app.StaticWeb("/static", "./resources")
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
ctx.MustRender("index.html", iris.Map{"url_count": db.Len()})
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.ViewData("url_count", db.Len())
|
||||
ctx.View("index.html")
|
||||
})
|
||||
|
||||
// find and execute a short url by its key
|
||||
// used on http://localhost:8080/u/dsaoj41u321dsa
|
||||
execShortURL := func(ctx *iris.Context, key string) {
|
||||
execShortURL := func(ctx context.Context, key string) {
|
||||
if key == "" {
|
||||
ctx.EmitError(iris.StatusBadRequest)
|
||||
ctx.StatusCode(iris.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
value := db.Get(key)
|
||||
if value == "" {
|
||||
ctx.SetStatusCode(iris.StatusNotFound)
|
||||
ctx.StatusCode(iris.StatusNotFound)
|
||||
ctx.Writef("Short URL for key: '%s' not found", key)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Redirect(value, iris.StatusTemporaryRedirect)
|
||||
}
|
||||
app.Get("/u/:shortkey", func(ctx *iris.Context) {
|
||||
execShortURL(ctx, ctx.Param("shortkey"))
|
||||
app.Get("/u/:shortkey", func(ctx context.Context) {
|
||||
execShortURL(ctx, ctx.Params().Get("shortkey"))
|
||||
})
|
||||
|
||||
app.Post("/shorten", func(ctx *iris.Context) {
|
||||
data := make(map[string]interface{}, 0)
|
||||
app.Post("/shorten", func(ctx context.Context) {
|
||||
formValue := ctx.FormValue("url")
|
||||
if formValue == "" {
|
||||
data["form_result"] = "You need to a enter a URL."
|
||||
ctx.ViewData("form_result", "You need to a enter a URL")
|
||||
} else {
|
||||
key, err := factory.Gen(formValue)
|
||||
if err != nil {
|
||||
data["form_result"] = "Invalid URL."
|
||||
ctx.ViewData("form_result", "Invalid URL")
|
||||
} else {
|
||||
if err = db.Set(key, formValue); err != nil {
|
||||
data["form_result"] = "Internal error while saving the url"
|
||||
app.Log(iris.DevMode, "while saving url: "+err.Error())
|
||||
ctx.ViewData("form_result", "Internal error while saving the URL")
|
||||
app.Log("while saving URL: " + err.Error())
|
||||
} else {
|
||||
ctx.SetStatusCode(iris.StatusOK)
|
||||
shortenURL := "http://" + app.Config.VHost + "/u/" + key
|
||||
data["form_result"] = template.HTML("<pre><a target='_new' href='" + shortenURL + "'>" + shortenURL + " </a></pre>")
|
||||
ctx.StatusCode(iris.StatusOK)
|
||||
shortenURL := "http://" + app.ConfigurationReadOnly().GetVHost() + "/u/" + key
|
||||
ctx.ViewData("form_result",
|
||||
template.HTML("<pre><a target='_new' href='"+shortenURL+"'>"+shortenURL+" </a></pre>"))
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
data["url_count"] = db.Len()
|
||||
ctx.Render("index.html", data)
|
||||
ctx.ViewData("url_count", db.Len())
|
||||
ctx.View("index.html")
|
||||
})
|
||||
|
||||
app.Listen("localhost:8080")
|
||||
app.Run(iris.Addr(":8080"))
|
||||
|
||||
db.Close()
|
||||
}
|
||||
|
||||
// +------------------------------------------------------------+
|
||||
|
|
|
@ -3,55 +3,56 @@ package main
|
|||
import (
|
||||
"time"
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/middleware/basicauth"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/middleware/basicauth"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(iris.DevLogger()) // adapt a simple internal logger to print any errors
|
||||
app.Adapt(httprouter.New()) // adapt a router, you can use gorillamux too
|
||||
|
||||
authConfig := basicauth.Config{
|
||||
Users: map[string]string{"myusername": "mypassword", "mySecondusername": "mySecondpassword"},
|
||||
Realm: "Authorization Required", // defaults to "Authorization Required"
|
||||
ContextKey: "mycustomkey", // defaults to "user"
|
||||
ContextKey: "user", // defaults to "user"
|
||||
Expires: time.Duration(30) * time.Minute,
|
||||
}
|
||||
|
||||
authentication := basicauth.New(authConfig)
|
||||
app.Get("/", func(ctx *iris.Context) { ctx.Redirect("/admin") })
|
||||
// to global app.Use(authentication) (or app.UseGlobal before the .Listen)
|
||||
|
||||
// to global app.Use(authentication) (or app.UseGlobal before the .Run)
|
||||
// to routes
|
||||
/*
|
||||
app.Get("/mysecret", authentication, func(ctx *iris.Context) {
|
||||
username := ctx.GetString("mycustomkey") // the Contextkey from the authConfig
|
||||
app.Get("/mysecret", authentication, func(ctx context.Context) {
|
||||
username := ctx.Values().GetString("user") // the Contextkey from the authConfig
|
||||
ctx.Writef("Hello authenticated user: %s ", username)
|
||||
})
|
||||
*/
|
||||
|
||||
app.Get("/", func(ctx context.Context) { ctx.Redirect("/admin") })
|
||||
|
||||
// to party
|
||||
|
||||
needAuth := app.Party("/admin", authentication)
|
||||
{
|
||||
//http://localhost:8080/admin
|
||||
needAuth.Get("/", func(ctx *iris.Context) {
|
||||
username := ctx.GetString("mycustomkey") // the Contextkey from the authConfig
|
||||
needAuth.Get("/", func(ctx context.Context) {
|
||||
username := ctx.Values().GetString("mycustomkey") // the Contextkey from the authConfig
|
||||
ctx.Writef("Hello authenticated user: %s from: %s ", username, ctx.Path())
|
||||
})
|
||||
// http://localhost:8080/admin/profile
|
||||
needAuth.Get("/profile", func(ctx *iris.Context) {
|
||||
username := ctx.GetString("mycustomkey") // the Contextkey from the authConfig
|
||||
needAuth.Get("/profile", func(ctx context.Context) {
|
||||
username := ctx.Values().GetString("mycustomkey") // the Contextkey from the authConfig
|
||||
ctx.Writef("Hello authenticated user: %s from: %s ", username, ctx.Path())
|
||||
})
|
||||
|
||||
// http://localhost:8080/admin/settings
|
||||
needAuth.Get("/settings", func(ctx *iris.Context) {
|
||||
username := authConfig.User(ctx) // shortcut for ctx.GetString("mycustomkey")
|
||||
needAuth.Get("/settings", func(ctx context.Context) {
|
||||
username := authConfig.User(ctx) // shortcut for ctx.Values().GetString("mycustomkey")
|
||||
ctx.Writef("Hello authenticated user: %s from: %s ", username, ctx.Path())
|
||||
})
|
||||
}
|
||||
|
||||
// open http://localhost:8080/admin
|
||||
app.Listen(":8080")
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
29
_examples/beginner/configuration/basic/main.go
Normal file
29
_examples/beginner/configuration/basic/main.go
Normal file
|
@ -0,0 +1,29 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
// [...]
|
||||
|
||||
// Good when you want to modify the whole configuration.
|
||||
app.Run(iris.Addr(":8080"), iris.WithConfiguration(iris.Configuration{ // default configuration:
|
||||
DisableBanner: false,
|
||||
DisableTray: false,
|
||||
DisableInterruptHandler: false,
|
||||
DisablePathCorrection: false,
|
||||
EnablePathEscape: false,
|
||||
FireMethodNotAllowed: false,
|
||||
DisableBodyConsumptionOnUnmarshal: false,
|
||||
DisableAutoFireStatusCode: false,
|
||||
TimeFormat: "Mon, 02 Jan 2006 15:04:05 GMT",
|
||||
Charset: "UTF-8",
|
||||
}))
|
||||
|
||||
// or before run:
|
||||
// app.Configure(iris.WithConfiguration(...))
|
||||
// app.Run(iris.Addr(":8080"))
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
DisableTray: true
|
||||
DisablePathCorrection = false
|
||||
EnablePathEscape = false
|
||||
FireMethodNotAllowed = true
|
||||
DisableBodyConsumptionOnUnmarshal = false
|
||||
TimeFormat = "Mon, 01 Jan 2006 15:04:05 GMT"
|
||||
Charset = "UTF-8"
|
||||
|
||||
[Other]
|
||||
MyServerName = "Iris"
|
18
_examples/beginner/configuration/from-toml-file/main.go
Normal file
18
_examples/beginner/configuration/from-toml-file/main.go
Normal file
|
@ -0,0 +1,18 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
// [...]
|
||||
|
||||
// Good when you have two configurations, one for development and a different one for production use.
|
||||
app.Run(iris.Addr(":8080"), iris.WithConfiguration(iris.TOML("./configs/iris.tml")))
|
||||
|
||||
// or before run:
|
||||
// app.Configure(iris.WithConfiguration(iris.TOML("./configs/iris.tml")))
|
||||
// app.Run(iris.Addr(":8080"))
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
DisableTray: true
|
||||
DisablePathCorrection: false
|
||||
EnablePathEscape: false
|
||||
FireMethodNotAllowed: true
|
||||
DisableBodyConsumptionOnUnmarshal: true
|
||||
TimeFormat: Mon, 01 Jan 2006 15:04:05 GMT
|
||||
Charset: UTF-8
|
18
_examples/beginner/configuration/from-yaml-file/main.go
Normal file
18
_examples/beginner/configuration/from-yaml-file/main.go
Normal file
|
@ -0,0 +1,18 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
// [...]
|
||||
|
||||
// Good when you have two configurations, one for development and a different one for production use.
|
||||
app.Run(iris.Addr(":8080"), iris.WithConfiguration(iris.YAML("./configs/iris.yml")))
|
||||
|
||||
// or before run:
|
||||
// app.Configure(iris.WithConfiguration(iris.YAML("./configs/iris.yml")))
|
||||
// app.Run(iris.Addr(":8080"))
|
||||
}
|
19
_examples/beginner/configuration/functional/main.go
Normal file
19
_examples/beginner/configuration/functional/main.go
Normal file
|
@ -0,0 +1,19 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
// [...]
|
||||
|
||||
// Good when you want to change some of the configuration's field.
|
||||
// I use that method :)
|
||||
app.Run(iris.Addr(":8080"), iris.WithoutBanner, iris.WithTray, iris.WithCharset("UTF-8"))
|
||||
|
||||
// or before run:
|
||||
// app.Configure(iris.WithoutBanner, iris.WithTray, iris.WithCharset("UTF-8"))
|
||||
// app.Run(iris.Addr(":8080"))
|
||||
}
|
43
_examples/beginner/convert-handlers/negroni-like/main.go
Normal file
43
_examples/beginner/convert-handlers/negroni-like/main.go
Normal file
|
@ -0,0 +1,43 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/core/handlerconv"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
irisMiddleware := handlerconv.FromStdWithNext(negronilikeTestMiddleware)
|
||||
app.Use(irisMiddleware)
|
||||
|
||||
// Method GET: http://localhost:8080/
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.HTML("<h1> Home </h1>")
|
||||
// this will print an error,
|
||||
// this route's handler will never be executed because the middleware's criteria not passed.
|
||||
})
|
||||
|
||||
// Method GET: http://localhost:8080/ok
|
||||
app.Get("/ok", func(ctx context.Context) {
|
||||
ctx.Writef("Hello world!")
|
||||
// this will print "OK. Hello world!".
|
||||
})
|
||||
|
||||
// http://localhost:8080
|
||||
// http://localhost:8080/ok
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
func negronilikeTestMiddleware(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
|
||||
if r.URL.Path == "/ok" && r.Method == "GET" {
|
||||
w.Write([]byte("OK. "))
|
||||
next(w, r) // go to the next route's handler
|
||||
return
|
||||
}
|
||||
// else print an error and do not forward to the route's handler.
|
||||
w.WriteHeader(iris.StatusBadRequest)
|
||||
w.Write([]byte("Bad request"))
|
||||
}
|
33
_examples/beginner/convert-handlers/nethttp/main.go
Normal file
33
_examples/beginner/convert-handlers/nethttp/main.go
Normal file
|
@ -0,0 +1,33 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/core/handlerconv"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
irisMiddleware := handlerconv.FromStd(nativeTestMiddleware)
|
||||
app.Use(irisMiddleware)
|
||||
|
||||
// Method GET: http://localhost:8080/
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.HTML("Home")
|
||||
})
|
||||
|
||||
// Method GET: http://localhost:8080/ok
|
||||
app.Get("/ok", func(ctx context.Context) {
|
||||
ctx.HTML("<b>Hello world!</b>")
|
||||
})
|
||||
|
||||
// http://localhost:8080
|
||||
// http://localhost:8080/ok
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
func nativeTestMiddleware(w http.ResponseWriter, r *http.Request) {
|
||||
println("Request path: " + r.URL.Path)
|
||||
}
|
|
@ -4,20 +4,16 @@ import (
|
|||
"bytes"
|
||||
|
||||
"github.com/kataras/go-mailer"
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/view"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/view"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
app := iris.New()
|
||||
// output startup banner and error logs on os.Stdout
|
||||
app.Adapt(iris.DevLogger())
|
||||
// set the router, you can choose gorillamux too
|
||||
app.Adapt(httprouter.New())
|
||||
// set a root for our templates
|
||||
app.Adapt(view.HTML("./templates", ".html"))
|
||||
app.AttachView(view.HTML("./templates", ".html"))
|
||||
|
||||
// change these to your own settings
|
||||
cfg := mailer.Config{
|
||||
|
@ -38,31 +34,40 @@ func main() {
|
|||
//mailService.Send("iris e-mail test subject", "</h1>outside of context before server's listen!</h1>", to...)
|
||||
|
||||
//inside handler
|
||||
app.Get("/send", func(ctx *iris.Context) {
|
||||
app.Get("/send", func(ctx context.Context) {
|
||||
content := `<h1>Hello From Iris web framework</h1> <br/><br/> <span style="color:blue"> This is the rich message body </span>`
|
||||
|
||||
err := mailService.Send("iris e-mail just t3st subject", content, to...)
|
||||
|
||||
if err != nil {
|
||||
ctx.HTML(200, "<b> Problem while sending the e-mail: "+err.Error())
|
||||
ctx.HTML("<b> Problem while sending the e-mail: " + err.Error())
|
||||
} else {
|
||||
ctx.HTML(200, "<h1> SUCCESS </h1>")
|
||||
ctx.HTML("<h1> SUCCESS </h1>")
|
||||
}
|
||||
})
|
||||
|
||||
// send a body by template
|
||||
app.Get("/send/template", func(ctx *iris.Context) {
|
||||
// we will not use ctx.Render
|
||||
app.Get("/send/template", func(ctx context.Context) {
|
||||
// we will not use ctx.View
|
||||
// because we don't want to render to the client
|
||||
// we need the templates' parsed result as raw bytes
|
||||
// so we make use of the bytes.Buffer which is an io.Writer
|
||||
// which being expected on app.Render parameter first.
|
||||
// which being expected on app.View parameter first.
|
||||
//
|
||||
// the rest of the parameters are the same and the behavior is the same as ctx.Render,
|
||||
// the rest of the parameters are the same and the behavior is the same as ctx.View,
|
||||
// except the 'where to render'
|
||||
buff := &bytes.Buffer{}
|
||||
|
||||
app.Render(buff, "body.html", iris.Map{
|
||||
// View executes and writes the result of a template file to the writer.
|
||||
//
|
||||
// First parameter is the writer to write the parsed template.
|
||||
// Second parameter is the relative, to templates directory, template filename, including extension.
|
||||
// Third parameter is the layout, can be empty string.
|
||||
// Forth parameter is the bindable data to the template, can be nil.
|
||||
//
|
||||
// Use context.View to render templates to the client instead.
|
||||
// Returns an error on failure, otherwise nil.
|
||||
app.View(buff, "body.html", "", context.Map{
|
||||
"Message": " his is the rich message body sent by a template!!",
|
||||
"Footer": "The footer of this e-mail!",
|
||||
})
|
||||
|
@ -71,10 +76,12 @@ func main() {
|
|||
err := mailService.Send("iris e-mail just t3st subject", content, to...)
|
||||
|
||||
if err != nil {
|
||||
ctx.HTML(iris.StatusOK, "<b> Problem while sending the e-mail: "+err.Error())
|
||||
ctx.StatusCode(iris.StatusBadRequest)
|
||||
ctx.HTML("<b> Sent failed with error: " + err.Error())
|
||||
} else {
|
||||
ctx.HTML(iris.StatusOK, "<h1> SUCCESS </h1>")
|
||||
ctx.HTML("<h1> SUCCESS </h1>")
|
||||
}
|
||||
})
|
||||
app.Listen(":8080")
|
||||
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
|
@ -1,23 +1,25 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(httprouter.New())
|
||||
// This will serve the ./static/favicons/iris_favicon_32_32.ico to: localhost:8080/favicon.ico
|
||||
app.Favicon("./static/favicons/iris_favicon_32_32.ico")
|
||||
|
||||
// app.Favicon("./static/favicons/iris_favicon_32_32.ico", "/favicon_32_32.ico")
|
||||
// This will serve the ./static/favicons/iris_favicon_32_32.ico to: localhost:8080/favicon_32_32.ico
|
||||
// This will serve the ./static/favicons/iris_favicon_48_48.ico to: localhost:8080/favicon.ico
|
||||
app.Favicon("./static/favicons/iris_favicon_48_48.ico")
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
ctx.HTML(iris.StatusOK, `You should see the favicon now at the side of your browser,
|
||||
if not, please refresh or clear the browser's cache.`)
|
||||
})
|
||||
// app.Favicon("./static/favicons/iris_favicon_48_48.ico", "/favicon_48_48.ico")
|
||||
// This will serve the ./static/favicons/iris_favicon_48_48.ico to: localhost:8080/favicon_48_48.ico
|
||||
|
||||
app.Listen(":8080")
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.HTML(`<a href="/favicon.ico"> press here to see the favicon.ico</a>.
|
||||
At some browsers like chrome, it should be visible at the top-left side of the browser's window,
|
||||
because some browsers make requests to the /favicon.ico automatically,
|
||||
so Iris serves your favicon in that path too (you can change it).`)
|
||||
}) // if favicon doesn't show to you, try to clear your browser's cache.
|
||||
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
|
Binary file not shown.
Before Width: | Height: | Size: 4.2 KiB |
Binary file not shown.
After Width: | Height: | Size: 15 KiB |
|
@ -1,63 +1,49 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
var myLogFile *os.File
|
||||
// get a filename based on the date, file logs works that way the most times
|
||||
// but these are just a sugar, you can directly attach a new file logger with .AttachLogger(io.Writer)
|
||||
func todayFilename() string {
|
||||
today := time.Now().Format("Jan 02 2006")
|
||||
return today + ".txt"
|
||||
}
|
||||
|
||||
func init() {
|
||||
// open an output file
|
||||
f, err := os.Create("logs.txt")
|
||||
func newLogFile() *os.File {
|
||||
filename := todayFilename()
|
||||
// open an output file, this will append to the today's file if server restarted.
|
||||
f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
myLogFile = f
|
||||
}
|
||||
|
||||
func myFileLogger() iris.LoggerPolicy {
|
||||
|
||||
// you can use a *File or an io.Writer,
|
||||
// we want to log with timestamps so we use the log.New.
|
||||
myLogger := log.New(myLogFile, "", log.LstdFlags)
|
||||
|
||||
// the logger is just a func,
|
||||
// will be used in runtime
|
||||
return func(mode iris.LogMode, message string) {
|
||||
// optionally, check for production or development log message mode
|
||||
// two modes: iris.ProdMode and iris.DevMode
|
||||
if mode == iris.ProdMode {
|
||||
// log only production-mode log messages
|
||||
myLogger.Println(message)
|
||||
}
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
func main() {
|
||||
// close the log file on exit application
|
||||
// when panic or iris exited by interupt event or manually by Shutdown.
|
||||
defer func() {
|
||||
if err := myLogFile.Close(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}()
|
||||
f := newLogFile()
|
||||
defer f.Close()
|
||||
|
||||
app := iris.New()
|
||||
app.Adapt(myFileLogger())
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
// for the sake of simplicity, in order see the logs at the ./logs.txt:
|
||||
app.Log(iris.ProdMode, "You have requested: http://localhost/8080"+ctx.Path())
|
||||
// attach the file as logger, remember, iris' app logger is just an io.Writer.
|
||||
app.AttachLogger(f)
|
||||
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
// for the sake of simplicity, in order see the logs at the ./_today_.txt
|
||||
ctx.Application().Log("Request: %s\r\n", ctx.Path())
|
||||
ctx.Writef("hello")
|
||||
})
|
||||
|
||||
// open http://localhost:8080
|
||||
// and watch the ./logs.txt file
|
||||
app.Listen(":8080")
|
||||
// navigate to http://localhost:8080
|
||||
// and open the ./logs.txt file
|
||||
if err := app.Run(iris.Addr(":8080"), iris.WithoutBanner); err != nil {
|
||||
app.Log("Shutdown with error: %v", err)
|
||||
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,16 +1,16 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"github.com/kataras/iris"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
// first parameter is the request path
|
||||
// second is the operating system directory
|
||||
app.StaticWeb("/static", "./assets")
|
||||
|
||||
app.Listen(":8080")
|
||||
// http://localhost:8080/static/css/main.css
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
|
|
@ -1,20 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
// Adapt the "httprouter", faster,
|
||||
// but it has limits on named path parameters' validation,
|
||||
// you can adapt "gorillamux" if you need regexp path validation!
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
app.HandleFunc("GET", "/", func(ctx *iris.Context) {
|
||||
ctx.Writef("hello world\n")
|
||||
})
|
||||
|
||||
app.Listen(":8080")
|
||||
}
|
29
_examples/beginner/http-errors/main.go
Normal file
29
_examples/beginner/http-errors/main.go
Normal file
|
@ -0,0 +1,29 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
app.OnErrorCode(iris.StatusInternalServerError, func(ctx context.Context) {
|
||||
ctx.HTML("Message: <b>" + ctx.Values().GetString("message") + "</b>")
|
||||
})
|
||||
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.HTML(`Click <a href="/my500">here</a> to fire the 500 status code`)
|
||||
})
|
||||
|
||||
app.Get("/my500", func(ctx context.Context) {
|
||||
ctx.Values().Set("message", "this is the error message")
|
||||
ctx.StatusCode(500)
|
||||
})
|
||||
|
||||
app.Get("/u/{firstname:alphabetical}", func(ctx context.Context) {
|
||||
ctx.Writef("Hello %s", ctx.Values().GetString("firstname"))
|
||||
})
|
||||
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
|
@ -1,35 +0,0 @@
|
|||
// Package main provide one-line integration with letsencrypt.org
|
||||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
// output startup banner and error logs on os.Stdout
|
||||
app.Adapt(iris.DevLogger())
|
||||
// set the router, you can choose gorillamux too
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
ctx.Writef("Hello from SECURE SERVER!")
|
||||
})
|
||||
|
||||
app.Get("/test2", func(ctx *iris.Context) {
|
||||
ctx.Writef("Welcome to secure server from /test2!")
|
||||
})
|
||||
|
||||
app.Get("/redirect", func(ctx *iris.Context) {
|
||||
ctx.Redirect("/test2")
|
||||
})
|
||||
|
||||
// This will provide you automatic certification & key from letsencrypt.org's servers
|
||||
// it also starts a second 'http://' server which will redirect all 'http://$PATH' requests to 'https://$PATH'
|
||||
|
||||
// NOTE: may not work on local addresses like this,
|
||||
// use it on a real domain, because
|
||||
// it uses the "golang.org/x/crypto/acme/autocert" package.
|
||||
app.ListenLETSENCRYPT("localhost:443")
|
||||
}
|
|
@ -1,37 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
)
|
||||
|
||||
const host = "127.0.0.1:443"
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
// output startup banner and error logs on os.Stdout
|
||||
app.Adapt(iris.DevLogger())
|
||||
// set the router, you can choose gorillamux too
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
ctx.Writef("Hello from the SECURE server")
|
||||
})
|
||||
|
||||
app.Get("/mypath", func(ctx *iris.Context) {
|
||||
ctx.Writef("Hello from the SECURE server on path /mypath")
|
||||
})
|
||||
|
||||
// start a secondary server (HTTP) on port 80, this is a non-blocking func
|
||||
// redirects all http to the main server which is tls/ssl on port :443
|
||||
|
||||
iris.Proxy(":80", "https://"+host)
|
||||
// start the MAIN server (HTTPS) on port 443, this is a blocking func
|
||||
app.ListenTLS(host, "mycert.cert", "mykey.key")
|
||||
|
||||
// now if you navigate to http://127.0.0.1/mypath it will
|
||||
// send you back to https://127.0.0.1:443/mypath (https://127.0.0.1/mypath)
|
||||
//
|
||||
// go to the listen-letsencrypt example to view how you can integrate your server
|
||||
// to get automatic certification and key from the letsencrypt.org 's servers.
|
||||
}
|
|
@ -1,22 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
)
|
||||
|
||||
const host = "127.0.0.1:443"
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
// output startup banner and error logs on os.Stdout
|
||||
app.Adapt(iris.DevLogger())
|
||||
// set the router, you can choose gorillamux too
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
ctx.Writef("Hello from the server")
|
||||
})
|
||||
|
||||
app.ListenUNIX("/tmp/srv.sock", 0666)
|
||||
}
|
29
_examples/beginner/listening/custom-listener/main.go
Normal file
29
_examples/beginner/listening/custom-listener/main.go
Normal file
|
@ -0,0 +1,29 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"net"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.Writef("Hello from the server")
|
||||
})
|
||||
|
||||
app.Get("/mypath", func(ctx context.Context) {
|
||||
ctx.Writef("Hello from %s", ctx.Path())
|
||||
})
|
||||
|
||||
// create any custom tcp listener, unix sock file or tls tcp listener.
|
||||
l, err := net.Listen("tcp4", ":8080")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// use of the custom listener
|
||||
app.Run(iris.Listener(l))
|
||||
}
|
19
_examples/beginner/listening/listen-addr/main.go
Normal file
19
_examples/beginner/listening/listen-addr/main.go
Normal file
|
@ -0,0 +1,19 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.HTML("<h1>Index /</h1>")
|
||||
})
|
||||
|
||||
if err := app.Run(iris.Addr(":8080")); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
}
|
31
_examples/beginner/listening/listen-letsencrypt/main.go
Normal file
31
_examples/beginner/listening/listen-letsencrypt/main.go
Normal file
|
@ -0,0 +1,31 @@
|
|||
// Package main provide one-line integration with letsencrypt.org
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.Writef("Hello from SECURE SERVER!")
|
||||
})
|
||||
|
||||
app.Get("/test2", func(ctx context.Context) {
|
||||
ctx.Writef("Welcome to secure server from /test2!")
|
||||
})
|
||||
|
||||
app.Get("/redirect", func(ctx context.Context) {
|
||||
ctx.Redirect("/test2")
|
||||
})
|
||||
|
||||
// If http to https auto-redirect is one of your needs
|
||||
// please look the code inside iris_deprecateed.go.ListenLETSENCRYPT to do it manually.
|
||||
|
||||
// NOTE: This may not work on local addresses like this,
|
||||
// use it on a real domain, because
|
||||
// it uses the "golang.org/x/crypto/acme/autocert" package.
|
||||
app.Run(iris.AutoTLS("localhost:443"))
|
||||
}
|
21
_examples/beginner/listening/listen-tls/main.go
Normal file
21
_examples/beginner/listening/listen-tls/main.go
Normal file
|
@ -0,0 +1,21 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.Writef("Hello from the SECURE server")
|
||||
})
|
||||
|
||||
app.Get("/mypath", func(ctx context.Context) {
|
||||
ctx.Writef("Hello from the SECURE server on path /mypath")
|
||||
})
|
||||
|
||||
// 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"))
|
||||
}
|
17
_examples/beginner/listening/listen-unix/main.go
Normal file
17
_examples/beginner/listening/listen-unix/main.go
Normal file
|
@ -0,0 +1,17 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/core/nettools"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
l, err := nettools.UNIX("/tmpl/srv.sock", 0666) // see its code to see how you can manually create a new file listener, it's easy.
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
app.Run(iris.Listener(l))
|
||||
}
|
117
_examples/beginner/overview/main.go
Normal file
117
_examples/beginner/overview/main.go
Normal file
|
@ -0,0 +1,117 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/view"
|
||||
)
|
||||
|
||||
// User is just a bindable object structure.
|
||||
type User struct {
|
||||
Username string `json:"username"`
|
||||
Firstname string `json:"firstname"`
|
||||
Lastname string `json:"lastname"`
|
||||
City string `json:"city"`
|
||||
Age int `json:"age"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
// Define templates using the std html/template engine.
|
||||
// Parse and load all files inside "./views" folder with ".html" file extension.
|
||||
// Reload the templates on each request (development mode).
|
||||
app.AttachView(view.HTML("./views", ".html").Reload(true))
|
||||
|
||||
// Regster custom handler for specific http errors.
|
||||
app.OnErrorCode(iris.StatusInternalServerError, func(ctx context.Context) {
|
||||
// .Values are used to communicate between handlers, middleware.
|
||||
errMessage := ctx.Values().GetString("error")
|
||||
if errMessage != "" {
|
||||
ctx.Writef("Internal server error: %s", errMessage)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Writef("(Unexpected) internal server error")
|
||||
})
|
||||
|
||||
app.Use(func(ctx context.Context) {
|
||||
ctx.Application().Log("Begin request for path: %s", ctx.Path())
|
||||
ctx.Next()
|
||||
})
|
||||
|
||||
// app.Done(func(ctx context.Context) {]})
|
||||
|
||||
// Method POST: http://localhost:8080/decode
|
||||
app.Post("/decode", func(ctx context.Context) {
|
||||
var user User
|
||||
ctx.ReadJSON(&user)
|
||||
ctx.Writef("%s %s is %d years old and comes from %s", user.Firstname, user.Lastname, user.Age, user.City)
|
||||
})
|
||||
|
||||
// Method GET: http://localhost:8080/encode
|
||||
app.Get("/encode", func(ctx context.Context) {
|
||||
doe := User{
|
||||
Username: "Johndoe",
|
||||
Firstname: "John",
|
||||
Lastname: "Doe",
|
||||
City: "Neither FBI knows!!!",
|
||||
Age: 25,
|
||||
}
|
||||
|
||||
ctx.JSON(doe)
|
||||
})
|
||||
|
||||
// Method GET: http://localhost:8080/profile/anytypeofstring
|
||||
app.Get("/profile/{username:string}", profileByUsername)
|
||||
|
||||
usersRoutes := app.Party("/users", logThisMiddleware)
|
||||
{
|
||||
// Method GET: http://localhost:8080/users/42
|
||||
usersRoutes.Get("/{id:int min(1)}", getUserByID)
|
||||
// Method POST: http://localhost:8080/users/create
|
||||
usersRoutes.Post("/create", createUser)
|
||||
}
|
||||
|
||||
// Listen for incoming HTTP/1.x & HTTP/2 clients on localhost port 8080.
|
||||
app.Run(iris.Addr(":8080"), iris.WithCharset("UTF-8"))
|
||||
}
|
||||
|
||||
func logThisMiddleware(ctx context.Context) {
|
||||
ctx.Application().Log("Path: %s | IP: %s", ctx.Path(), ctx.RemoteAddr())
|
||||
|
||||
// .Next is required to move forward to the chain of handlers,
|
||||
// if missing then it stops the execution at this handler.
|
||||
ctx.Next()
|
||||
}
|
||||
|
||||
func profileByUsername(ctx context.Context) {
|
||||
// .Params are used to get dynamic path parameters.
|
||||
username := ctx.Params().Get("username")
|
||||
ctx.ViewData("Username", username)
|
||||
// renders "./views/users/profile.html"
|
||||
// with {{ .Username }} equals to the username dynamic path parameter.
|
||||
ctx.View("users/profile.html")
|
||||
}
|
||||
|
||||
func getUserByID(ctx context.Context) {
|
||||
userID := ctx.Params().Get("id") // Or convert directly using: .Values().GetInt/GetInt64 etc...
|
||||
// your own db fetch here instead of user :=...
|
||||
user := User{Username: "username" + userID}
|
||||
|
||||
ctx.XML(user)
|
||||
}
|
||||
|
||||
func createUser(ctx context.Context) {
|
||||
var user User
|
||||
err := ctx.ReadForm(&user)
|
||||
if err != nil {
|
||||
ctx.Values().Set("error", "creating user, read and parse form failed. "+err.Error())
|
||||
ctx.StatusCode(iris.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
// renders "./views/users/create_verification.html"
|
||||
// with {{ . }} equals to the User object, i.e {{ .Username }} , {{ .Firstname}} etc...
|
||||
ctx.ViewData("", user)
|
||||
ctx.View("users/create_verification.html")
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
<html>
|
||||
<head><title>Create verification</title></head>
|
||||
<body>
|
||||
<h1> Create Verification </h1>
|
||||
<table style="width:550px">
|
||||
<tr>
|
||||
<th>Username</th>
|
||||
<th>Firstname</th>
|
||||
<th>Lastname</th>
|
||||
<th>City</th>
|
||||
<th>Age</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>{{ .Username }}</td>
|
||||
<td>{{ .Firstname }}</td>
|
||||
<td>{{ .Lastname }}</td>
|
||||
<td>{{ .City }}</td>
|
||||
<td>{{ .Age }}</td>
|
||||
</tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
7
_examples/beginner/overview/views/users/profile.html
Normal file
7
_examples/beginner/overview/views/users/profile.html
Normal file
|
@ -0,0 +1,7 @@
|
|||
<html>
|
||||
<head><title>Profile page</title></head>
|
||||
<body>
|
||||
<h1> Profile </h1>
|
||||
<b> {{ .Username }} </b>
|
||||
</body>
|
||||
</html>
|
20
_examples/beginner/pprof/main.go
Normal file
20
_examples/beginner/pprof/main.go
Normal file
|
@ -0,0 +1,20 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
|
||||
"github.com/kataras/iris/middleware/pprof"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.HTML("<h1> Please click <a href='/debug/pprof'>here</a>")
|
||||
})
|
||||
|
||||
app.Any("/debug/pprof/{action:path}", pprof.New())
|
||||
// ___________
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
|
@ -2,9 +2,9 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/view"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/view"
|
||||
)
|
||||
|
||||
type Visitor struct {
|
||||
|
@ -15,28 +15,27 @@ type Visitor struct {
|
|||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
// output startup banner and error logs on os.Stdout
|
||||
app.Adapt(iris.DevLogger())
|
||||
// set the router, you can choose gorillamux too
|
||||
app.Adapt(httprouter.New())
|
||||
// set the view html template engine
|
||||
app.Adapt(view.HTML("./templates", ".html"))
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
if err := ctx.Render("form.html", nil); err != nil {
|
||||
ctx.Log(iris.DevMode, err.Error())
|
||||
// set the view html template engine
|
||||
app.AttachView(view.HTML("./templates", ".html").Reload(true))
|
||||
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
if err := ctx.View("form.html"); err != nil {
|
||||
ctx.StatusCode(iris.StatusInternalServerError)
|
||||
ctx.WriteString(err.Error())
|
||||
}
|
||||
})
|
||||
|
||||
app.Post("/form_action", func(ctx *iris.Context) {
|
||||
app.Post("/form_action", func(ctx context.Context) {
|
||||
visitor := Visitor{}
|
||||
err := ctx.ReadForm(&visitor)
|
||||
if err != nil {
|
||||
ctx.Log(iris.DevMode, "Error when reading form: "+err.Error())
|
||||
ctx.StatusCode(iris.StatusInternalServerError)
|
||||
ctx.WriteString(err.Error())
|
||||
}
|
||||
|
||||
ctx.Writef("Visitor: %#v", visitor)
|
||||
})
|
||||
|
||||
app.Listen(":8080")
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
|
|
@ -4,13 +4,16 @@
|
|||
</head>
|
||||
<body>
|
||||
<form action="/form_action" method="post">
|
||||
<input type="text" name="Username" /> <br /> <input type="text"
|
||||
name="Mail" /><br /> <select multiple="multiple" name="mydata">
|
||||
Username: <input type="text" name="Username" /> <br />
|
||||
Mail: <input type="text" name="Mail" /> <br />
|
||||
Select one or more: <br/>
|
||||
<select multiple="multiple" name="mydata">
|
||||
<option value='one'>One</option>
|
||||
<option value='two'>Two</option>
|
||||
<option value='three'>Three</option>
|
||||
<option value='four'>Four</option>
|
||||
</select>
|
||||
|
||||
<hr />
|
||||
<input type="submit" value="Send data" />
|
||||
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
type Company struct {
|
||||
|
@ -11,26 +11,34 @@ type Company struct {
|
|||
Other string
|
||||
}
|
||||
|
||||
func MyHandler(ctx *iris.Context) {
|
||||
func MyHandler(ctx context.Context) {
|
||||
c := &Company{}
|
||||
if err := ctx.ReadJSON(c); err != nil {
|
||||
ctx.Log(iris.DevMode, err.Error())
|
||||
ctx.StatusCode(iris.StatusBadRequest)
|
||||
ctx.WriteString(err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Writef("Company: %#v\n", c)
|
||||
ctx.Writef("Received: %#v\n", c)
|
||||
}
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
// output startup banner and error logs on os.Stdout
|
||||
app.Adapt(iris.DevLogger())
|
||||
// set the router, you can choose gorillamux too
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
// use postman or whatever to do a POST request
|
||||
// to the http://localhost:8080 with BODY: JSON PAYLOAD
|
||||
// and Content-Type to application/json
|
||||
app.Post("/", MyHandler)
|
||||
app.Listen(":8080")
|
||||
|
||||
// use Postman or whatever to do a POST request
|
||||
// to the http://localhost:8080 with RAW BODY:
|
||||
/*
|
||||
{
|
||||
"Name": "Iris-Go",
|
||||
"City": "New York",
|
||||
"Other": "Something here"
|
||||
}
|
||||
*/
|
||||
// and Content-Type to application/json
|
||||
//
|
||||
// The response should be:
|
||||
// Received: &main.Company{Name:"Iris-Go", City:"New York", Other:"Something here"}
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
|
30
_examples/beginner/recover/main.go
Normal file
30
_examples/beginner/recover/main.go
Normal file
|
@ -0,0 +1,30 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
|
||||
"github.com/kataras/iris/middleware/recover"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
// use this recover(y) middleware
|
||||
app.Use(recover.New())
|
||||
|
||||
i := 0
|
||||
// let's simmilate a panic every next request
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
i++
|
||||
if i%2 == 0 {
|
||||
panic("a panic here")
|
||||
}
|
||||
ctx.Writef("Hello, refresh one time more to get panic!")
|
||||
})
|
||||
|
||||
// http://localhost:8080, refresh it 5-6 times.
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
// Note:
|
||||
// app := iris.Default() instead of iris.New() makes use of the recovery middleware automatically.
|
|
@ -1,17 +1,14 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/middleware/logger"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/middleware/logger"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
app.Adapt(iris.DevLogger()) // it just enables the print of the iris.DevMode logs. Enable it to view the middleware's messages.
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
customLogger := logger.New(logger.Config{
|
||||
// Status displays status code
|
||||
Status: true,
|
||||
|
@ -25,29 +22,31 @@ func main() {
|
|||
|
||||
app.Use(customLogger)
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.Writef("hello")
|
||||
})
|
||||
|
||||
app.Get("/1", func(ctx *iris.Context) {
|
||||
app.Get("/1", func(ctx context.Context) {
|
||||
ctx.Writef("hello")
|
||||
})
|
||||
|
||||
app.Get("/2", func(ctx *iris.Context) {
|
||||
app.Get("/2", func(ctx context.Context) {
|
||||
ctx.Writef("hello")
|
||||
})
|
||||
|
||||
// log http errors
|
||||
// log http errors should be done manually
|
||||
errorLogger := logger.New()
|
||||
|
||||
app.OnError(iris.StatusNotFound, func(ctx *iris.Context) {
|
||||
errorLogger.Serve(ctx)
|
||||
app.OnErrorCode(iris.StatusNotFound, func(ctx context.Context) {
|
||||
errorLogger(ctx)
|
||||
ctx.Writef("My Custom 404 error page ")
|
||||
})
|
||||
|
||||
// http://localhost:8080
|
||||
// http://localhost:8080/1
|
||||
// http://localhost:8080/2
|
||||
app.Listen(":8080")
|
||||
// http://lcoalhost:8080/notfoundhere
|
||||
// see the output on the console.
|
||||
app.Run(iris.Addr(":8080"))
|
||||
|
||||
}
|
|
@ -1,69 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/gorillamux" // import the gorillamux adaptor
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(iris.DevLogger()) // writes both prod and dev logs to the os.Stdout
|
||||
app.Adapt(gorillamux.New()) // uses the gorillamux for routing and reverse routing
|
||||
|
||||
// set a custom 404 handler
|
||||
app.OnError(iris.StatusNotFound, func(ctx *iris.Context) {
|
||||
ctx.HTML(iris.StatusNotFound, "<h1> custom http error page </h1>")
|
||||
})
|
||||
|
||||
app.Get("/healthcheck", h)
|
||||
|
||||
gamesMiddleware := func(ctx *iris.Context) {
|
||||
println(ctx.Method() + ": " + ctx.Path())
|
||||
ctx.Next()
|
||||
}
|
||||
|
||||
games := app.Party("/games", gamesMiddleware)
|
||||
{ // braces are optional of course, it's just a style of code
|
||||
games.Get("/{gameID:[0-9]+}/clans", h)
|
||||
games.Get("/{gameID:[0-9]+}/clans/clan/{publicID:[0-9]+}", h)
|
||||
games.Get("/{gameID:[0-9]+}/clans/search", h)
|
||||
|
||||
games.Put("/{gameID:[0-9]+}/players/{publicID:[0-9]+}", h)
|
||||
games.Put("/{gameID:[0-9]+}/clans/clan/{publicID:[0-9]+}", h)
|
||||
|
||||
games.Post("/{gameID:[0-9]+}/clans", h)
|
||||
games.Post("/{gameID:[0-9]+}/players", h)
|
||||
games.Post("/{gameID:[0-9]+}/clans/{publicID:[0-9]+}/leave", h)
|
||||
games.Post("/{gameID:[0-9]+}/clans/{clanPublicID:[0-9]+}/memberships/application", h)
|
||||
games.Post("/{gameID:[0-9]+}/clans/{clanPublicID:[0-9]+}/memberships/application/:action", h)
|
||||
games.Post("/{gameID:[0-9]+}/clans/{clanPublicID:[0-9]+}/memberships/invitation", h)
|
||||
games.Post("/{gameID:[0-9]+}/clans/{clanPublicID:[0-9]+}/memberships/invitation/:action", h)
|
||||
games.Post("/{gameID:[0-9]+}/clans/{clanPublicID:[0-9]+}/memberships/delete", h)
|
||||
games.Post("/{gameID:[0-9]+}/clans/{clanPublicID:[0-9]+}/memberships/promote", h)
|
||||
games.Post("/{gameID:[0-9]+}/clans/{clanPublicID:[0-9]+}/memberships/demote", h)
|
||||
}
|
||||
|
||||
myroute := app.Get("/anything/{anythingparameter:.*}", func(ctx *iris.Context) {
|
||||
s := ctx.Param("anythingparameter")
|
||||
ctx.Writef("The path after /anything is: %s", s)
|
||||
}) // .ChangeName("myroute")
|
||||
|
||||
app.Get("/reverse_myroute", func(ctx *iris.Context) {
|
||||
// reverse routing snippet using templates:
|
||||
// https://github.com/kataras/iris/tree/v6/adaptors/view/_examples/template_html_3 (gorillamux)
|
||||
// https://github.com/kataras/iris/tree/v6/adaptors/view/_examples/template_html_4 (httprouter)
|
||||
|
||||
myrouteRequestPath := app.Path(myroute.Name(), "anythingparameter", "something/here")
|
||||
ctx.Writef("Should be '/anything/something/here': %s", myrouteRequestPath)
|
||||
})
|
||||
|
||||
p := app.Party("mysubdomain.")
|
||||
// http://mysubdomain.myhost.com/
|
||||
p.Get("/", h)
|
||||
|
||||
app.Listen(":8080")
|
||||
}
|
||||
|
||||
func h(ctx *iris.Context) {
|
||||
ctx.HTML(iris.StatusOK, "<h1>Path<h1/>"+ctx.Path())
|
||||
}
|
|
@ -1,39 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
)
|
||||
|
||||
func hello(ctx *iris.Context) {
|
||||
ctx.Writef("Hello from %s", ctx.Path())
|
||||
}
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(iris.DevLogger())
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
app.OnError(iris.StatusNotFound, func(ctx *iris.Context) {
|
||||
ctx.HTML(iris.StatusNotFound, "<h1>Custom not found handler </h1>")
|
||||
})
|
||||
|
||||
app.Get("/", hello)
|
||||
app.Get("/users/:userid", func(ctx *iris.Context) {
|
||||
ctx.Writef("Hello user with id: %s", ctx.Param("userid"))
|
||||
})
|
||||
|
||||
app.Get("/myfiles/*file", func(ctx *iris.Context) {
|
||||
ctx.HTML(iris.StatusOK, "Hello, the dynamic path after /myfiles is:<br/> <b>"+ctx.Param("file")+"</b>")
|
||||
})
|
||||
|
||||
app.Get("/users/:userid/messages/:messageid", func(ctx *iris.Context) {
|
||||
ctx.HTML(iris.StatusOK, `Message from user with id:<br/> <b>`+ctx.Param("userid")+`</b>,
|
||||
message id: <b>`+ctx.Param("messageid")+`</b>`)
|
||||
})
|
||||
|
||||
// http://127.0.0.1:8080/users/42
|
||||
// http://127.0.0.1:8080/myfiles/mydirectory/myfile.zip
|
||||
// http://127.0.0.1:8080/users/42/messages/1
|
||||
app.Listen(":8080")
|
||||
}
|
170
_examples/beginner/routing/basic/main.go
Normal file
170
_examples/beginner/routing/basic/main.go
Normal file
|
@ -0,0 +1,170 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
// registers a custom handler for 404 not found http (error) status code,
|
||||
// fires when route not found or manually by ctx.StatusCode(iris.StatusNotFound).
|
||||
app.OnErrorCode(iris.StatusNotFound, notFoundHandler)
|
||||
|
||||
// GET -> HTTP Method
|
||||
// / -> Path
|
||||
// func(ctx context.Context) -> The route's handler.
|
||||
//
|
||||
// Third receiver should contains the route's handler(s), they are executed by order.
|
||||
app.Handle("GET", "/", func(ctx context.Context) {
|
||||
// navigate to the middle of $GOPATH/src/github.com/kataras/iris/context/context.go
|
||||
// to overview all context's method (there a lot of them, read that and you will learn how iris works too)
|
||||
ctx.HTML("Hello from " + ctx.Path()) // Hello from /
|
||||
})
|
||||
|
||||
app.Get("/home", func(ctx context.Context) {
|
||||
ctx.Writef(`Same as app.Handle("GET", "/", [...])`)
|
||||
})
|
||||
|
||||
app.Get("/donate", donateHandler, donateFinishHandler)
|
||||
|
||||
// Pssst, don't forget dynamic-path example for more "magic"!
|
||||
app.Get("/api/users/{userid:int min(1)}", func(ctx context.Context) {
|
||||
userID, err := ctx.Params().GetInt("userid")
|
||||
|
||||
if err != nil {
|
||||
ctx.Writef("error while trying to parse userid parameter," +
|
||||
"this will never happen if :int is being used because if it's not integer it will fire Not Found automatically.")
|
||||
ctx.StatusCode(iris.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(map[string]interface{}{
|
||||
// you can pass any custom structured go value of course.
|
||||
"user_id": userID,
|
||||
})
|
||||
})
|
||||
// app.Post("/", func(ctx context.Context){}) -> for POST http method.
|
||||
// app.Put("/", func(ctx context.Context){})-> for "PUT" http method.
|
||||
// app.Delete("/", func(ctx context.Context){})-> for "DELETE" http method.
|
||||
// app.Options("/", func(ctx context.Context){})-> for "OPTIONS" http method.
|
||||
// app.Trace("/", func(ctx context.Context){})-> for "TRACE" http method.
|
||||
// app.Head("/", func(ctx context.Context){})-> for "HEAD" http method.
|
||||
// app.Connect("/", func(ctx context.Context){})-> for "CONNECT" http method.
|
||||
// app.Patch("/", func(ctx context.Context){})-> for "PATCH" http method.
|
||||
// app.Any("/", func(ctx context.Context){}) for all http methods.
|
||||
|
||||
// More than one route can contain the same path with a different http mapped method.
|
||||
// You can catch any route creation errors with:
|
||||
// route, err := app.Get(...)
|
||||
// set a name to a route: route.Name = "myroute"
|
||||
|
||||
// You can also group routes by path prefix, sharing middleware(s) and done handlers.
|
||||
|
||||
adminRoutes := app.Party("/admin", adminMiddleware)
|
||||
|
||||
adminRoutes.Done(func(ctx context.Context) { // executes always last if ctx.Next()
|
||||
ctx.Application().Log("response sent to " + ctx.Path())
|
||||
})
|
||||
// adminRoutes.Layout("/views/layouts/admin.html") // set a view layout for these routes, see more at intermediate/view examples.
|
||||
|
||||
// GET: http://localhost:8080/admin
|
||||
adminRoutes.Get("/", func(ctx context.Context) {
|
||||
// [...]
|
||||
ctx.StatusCode(iris.StatusOK) // default is 200 == iris.StatusOK
|
||||
ctx.HTML("<h1>Hello from admin/</h1>")
|
||||
|
||||
ctx.Next() // in order to execute the party's "Done" Handler(s)
|
||||
})
|
||||
|
||||
// GET: http://localhost:8080/admin/login
|
||||
adminRoutes.Get("/login", func(ctx context.Context) {
|
||||
// [...]
|
||||
})
|
||||
// POST: http://localhost:8080/admin/login
|
||||
adminRoutes.Post("/login", func(ctx context.Context) {
|
||||
// [...]
|
||||
})
|
||||
|
||||
// subdomains, easier than ever, should add localhost or 127.0.0.1 into your hosts file,
|
||||
// etc/hosts on unix or C:/windows/system32/drivers/etc/hosts on windows.
|
||||
v1 := app.Party("v1.")
|
||||
{ // braces are optional, it's just type of style, to group the routes visually.
|
||||
|
||||
// http://v1.localhost:8080
|
||||
v1.Get("/", func(ctx context.Context) {
|
||||
ctx.HTML("Version 1 API. go to <a href='" + ctx.Path() + "/api" + "'>/api/users</a>")
|
||||
})
|
||||
|
||||
usersAPI := v1.Party("/api/users")
|
||||
{
|
||||
// http://v1.localhost:8080/api/users
|
||||
usersAPI.Get("/", func(ctx context.Context) {
|
||||
ctx.Writef("All users")
|
||||
})
|
||||
// http://v1.localhost:8080/api/users/42
|
||||
usersAPI.Get("/{userid:int}", func(ctx context.Context) {
|
||||
ctx.Writef("user with id: %s", ctx.Params().Get("userid"))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// wildcard subdomains.
|
||||
wildcardSubdomain := app.Party("*.")
|
||||
{
|
||||
wildcardSubdomain.Get("/", func(ctx context.Context) {
|
||||
ctx.Writef("Subdomain can be anything, now you're here from: %s", ctx.Subdomain())
|
||||
})
|
||||
}
|
||||
|
||||
// http://localhost:8080
|
||||
// http://localhost:8080/home
|
||||
// http://localhost:8080/donate
|
||||
// http://localhost:8080/api/users/42
|
||||
// http://localhost:8080/admin
|
||||
// http://localhost:8080/admin/login
|
||||
//
|
||||
// http://localhost:8080/api/users/0
|
||||
// http://localhost:8080/api/users/blabla
|
||||
// http://localhost:8080/wontfound
|
||||
//
|
||||
// if hosts edited:
|
||||
// http://v1.localhost:8080
|
||||
// http://v1.localhost:8080/api/users
|
||||
// http://v1.localhost:8080/api/users/42
|
||||
// http://anything.localhost:8080
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
func adminMiddleware(ctx context.Context) {
|
||||
// [...]
|
||||
ctx.Next() // to move to the next handler, or don't that if you have any auth logic.
|
||||
}
|
||||
|
||||
func donateHandler(ctx context.Context) {
|
||||
ctx.Writef("Just like an inline handler, but it can be " +
|
||||
"used by other package, anywhere in your project.")
|
||||
|
||||
// let's pass a value to the next handler
|
||||
// Values is the way handlers(or middleware) are communicating between each other.
|
||||
ctx.Values().Set("donate_url", "https://github.com/kataras/iris#buy-me-a-cup-of-coffee")
|
||||
ctx.Next() // in order to execute the next handler in the chain, look donate route.
|
||||
}
|
||||
|
||||
func donateFinishHandler(ctx context.Context) {
|
||||
// values can be any type of object so we could cast the value to a string
|
||||
// but Iris provides an easy to do that, if donate_url is not defined, then it returns an empty string instead.
|
||||
donateURL := ctx.Values().GetString("donate_url")
|
||||
ctx.Application().Log("donate_url value was: " + donateURL)
|
||||
ctx.Writef("\n\nDonate sent(?).")
|
||||
}
|
||||
|
||||
func notFoundHandler(ctx context.Context) {
|
||||
ctx.HTML("Custom route for 404 not found http code, here you can render a view, html, json <b>any valid response</b>.")
|
||||
}
|
||||
|
||||
// Notes:
|
||||
// A path parameter name should contain only alphabetical letters, symbols, containing '_' and numbers are NOT allowed.
|
||||
// If route failed to be registered, the app will panic without any warnings
|
||||
// if you didn't catch the second return value(error) on .Handle/.Get....
|
183
_examples/beginner/routing/dynamic-path/main.go
Normal file
183
_examples/beginner/routing/dynamic-path/main.go
Normal file
|
@ -0,0 +1,183 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
// At the previous example "routing/basic",
|
||||
// we've seen static routes, group of routes, subdomains, wildcard subdomains, a small example of parameterized path
|
||||
// with a single known paramete and custom http errors, now it's time to see wildcard parameters and macros.
|
||||
|
||||
// Iris, like net/http std package registers route's handlers
|
||||
// by a Handler, the Iris' type of handler is just a func(ctx context.Context)
|
||||
// where context comes from github.com/kataras/iris/context.
|
||||
// Until go 1.9 you will have to import that package too, after go 1.9 this will be not be necessary.
|
||||
//
|
||||
// Iris has the easiest and the most powerful routing process you have ever meet.
|
||||
// If you're used to use the "httprouter"
|
||||
// then you don't have to change a thing of a route's path.
|
||||
//
|
||||
// At the same time,
|
||||
// Iris has its own interpeter(yes like a programming language)
|
||||
// for route's path syntax and their dynamic path parameters parsing and evaluation,
|
||||
// I am calling them "macros" for shortcut.
|
||||
// In the following examples we will see only the second option, which has exactly the same speed
|
||||
// compared to "httprouter".
|
||||
// How? It calculates its needs and if not any special regexp needed then it just
|
||||
// registers the route with the underline httprouter's path syntax,
|
||||
// otherwise it pre-compiles the regexp and adds the necessary middleware(s).
|
||||
//
|
||||
// Note: the Iris' router follows the "httprouter"'s rules for routes confliction.
|
||||
//
|
||||
// Standard macro types for parameters:
|
||||
// +------------------------+
|
||||
// | {param:string} |
|
||||
// +------------------------+
|
||||
// string type
|
||||
// anything
|
||||
//
|
||||
// +------------------------+
|
||||
// | {param:int} |
|
||||
// +------------------------+
|
||||
// int type
|
||||
// only numbers (0-9)
|
||||
//
|
||||
// +------------------------+
|
||||
// | {param:alphabetical} |
|
||||
// +------------------------+
|
||||
// alphabetical/letter type
|
||||
// letters only (upper or lowercase)
|
||||
//
|
||||
// +------------------------+
|
||||
// | {param:file} |
|
||||
// +------------------------+
|
||||
// file type
|
||||
// letters (upper or lowercase)
|
||||
// numbers (0-9)
|
||||
// underscore (_)
|
||||
// dash (-)
|
||||
// point (.)
|
||||
// no spaces ! or other character
|
||||
//
|
||||
// +------------------------+
|
||||
// | {param:path} |
|
||||
// +------------------------+
|
||||
// path type
|
||||
// anything, should be the last part, more than one path segment,
|
||||
// i.e: /path1/path2/path3 , ctx.Params().GetString("param") == "/path1/path2/path3"
|
||||
//
|
||||
// if type is missing then parameter's type is defaulted to string, so
|
||||
// {param} == {param:string}.
|
||||
//
|
||||
// If a function not found on that type then the "string"'s types functions are being used.
|
||||
// i.e:
|
||||
// {param:int min(3)}
|
||||
//
|
||||
//
|
||||
// Besides the fact that Iris provides the basic types and some default "macro funcs"
|
||||
// you are able to register your own too!.
|
||||
//
|
||||
// Register a named path parameter function:
|
||||
// app.Macros().Int.RegisterFunc("min", func(argument int) func(paramValue string) bool {
|
||||
// [...]
|
||||
// return true/false -> true means valid.
|
||||
// })
|
||||
//
|
||||
// at the func(argument ...) you can have any standard type, it will be validated before the server starts
|
||||
// so don't care about performance here, the only thing it runs at serve time is the returning func(paramValue string) bool.
|
||||
//
|
||||
// {param:string equal(iris)} , "iris" will be the argument here:
|
||||
// app.Macros().String.RegisterFunc("equal", func(argument string) func(paramValue string) bool {
|
||||
// return func(paramValue string){ return argument == paramValue }
|
||||
// })
|
||||
|
||||
// you can use the "string" type which is valid for a single path parameter that can be anything.
|
||||
app.Get("/username/{name}", func(ctx context.Context) {
|
||||
ctx.Writef("Hello %s", ctx.Params().Get("name"))
|
||||
}) // type is missing = {name:string}
|
||||
|
||||
// Let's register our first macro attached to int macro type.
|
||||
// "min" = the function
|
||||
// "minValue" = the argument of the function
|
||||
// func(string) bool = the macro's path parameter evaluator, this executes in serve time when
|
||||
// a user requests a path which contains the :int macro type with the min(...) macro parameter function.
|
||||
app.Macros().Int.RegisterFunc("min", func(minValue int) func(string) bool {
|
||||
// do anything before serve here [...]
|
||||
// at this case we don't need to do anything
|
||||
return func(paramValue string) bool {
|
||||
n, err := strconv.Atoi(paramValue)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return n >= minValue
|
||||
}
|
||||
})
|
||||
|
||||
// http://localhost:8080/profile/id>=1
|
||||
// this will throw 404 even if it's found as route on : /profile/0, /profile/blabla, /profile/-1
|
||||
// macro parameter functions are optional of course.
|
||||
app.Get("/profile/{id:int min(1)}", func(ctx context.Context) {
|
||||
// second parameter is the error but it will always nil because we use macros,
|
||||
// the validaton already happened.
|
||||
id, _ := ctx.Params().GetInt("id")
|
||||
ctx.Writef("Hello id: %d", id)
|
||||
})
|
||||
|
||||
// to change the error code per route's macro evaluator:
|
||||
app.Get("/profile/{id:int min(1)}/friends/{friendid:int min(1) else 504}", func(ctx context.Context) {
|
||||
id, _ := ctx.Params().GetInt("id")
|
||||
friendid, _ := ctx.Params().GetInt("friendid")
|
||||
ctx.Writef("Hello id: %d looking for friend id: ", id, friendid)
|
||||
}) // this will throw e 504 error code instead of 404 if all route's macros not passed.
|
||||
|
||||
// http://localhost:8080/game/a-zA-Z/level/0-9
|
||||
// remember, alphabetical is lowercase or uppercase letters only.
|
||||
app.Get("/game/{name:alphabetical}/level/{level:int}", func(ctx context.Context) {
|
||||
ctx.Writef("name: %s | level: %s", ctx.Params().Get("name"), ctx.Params().Get("level"))
|
||||
})
|
||||
|
||||
// let's use a trivial custom regexp that validates a single path parameter
|
||||
// which its value is only lowercase letters.
|
||||
|
||||
// http://localhost:8080/lowercase/kataras
|
||||
app.Get("/lowercase/{name:string regexp(^[a-z]+)}", func(ctx context.Context) {
|
||||
ctx.Writef("name should be only lowercase, otherwise this handler will never executed: %s", ctx.Params().Get("name"))
|
||||
})
|
||||
|
||||
// http://localhost:8080/single_file/app.js
|
||||
app.Get("/single_file/{myfile:file}", func(ctx context.Context) {
|
||||
ctx.Writef("file type validates if the parameter value has a form of a file name, got: %s", ctx.Params().Get("myfile"))
|
||||
})
|
||||
|
||||
// http://localhost:8080/myfiles/any/directory/here/
|
||||
// this is the only macro type that accepts any number of path segments.
|
||||
app.Get("/myfiles/{directory:path}", func(ctx context.Context) {
|
||||
ctx.Writef("path type accepts any number of path segments, path after /myfiles/ is: %s", ctx.Params().Get("directory"))
|
||||
}) // for wildcard path (any number of path segments) without validation you can use:
|
||||
// /myfiles/*directory
|
||||
|
||||
// "{param}"'s performance is exactly the same of ":param"'s.
|
||||
|
||||
// alternatives -> ":param" for single path parameter and "*paramPath" for wildcard path parameter
|
||||
// acquire them by ctx.Params().Get as always.
|
||||
|
||||
// WARNING:
|
||||
// A path parameter name should contain only alphabetical letters, symbols, containing '_' and numbers are NOT allowed.
|
||||
// If route failed to be registered, the app will panic without any warnings
|
||||
// if you didn't catch the second return value(error) on .Handle/.Get....
|
||||
|
||||
// Last, do not confuse ctx.Values() with ctx.Params().
|
||||
// Path parameter's values goes to ctx.Params() and context's local storage
|
||||
// that can be used to communicate between handlers and middleware(s) goes to
|
||||
// ctx.Values(), path parameters and the rest of any custom values are separated for your own good.
|
||||
|
||||
if err := app.Run(iris.Addr(":8080")); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
107
_examples/beginner/routing/main.go
Normal file
107
_examples/beginner/routing/main.go
Normal file
|
@ -0,0 +1,107 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
/*
|
||||
Read:
|
||||
"basic"
|
||||
"dynamic-path"
|
||||
and "reverse" examples if you want to release Iris' real power.
|
||||
*/
|
||||
|
||||
const maxBodySize = 1 << 20
|
||||
|
||||
var app *iris.Application
|
||||
|
||||
func init() {
|
||||
app = iris.New()
|
||||
}
|
||||
|
||||
func registerErrors() {
|
||||
// set a custom 404 handler
|
||||
app.OnErrorCode(iris.StatusNotFound, func(ctx context.Context) {
|
||||
ctx.HTML("<h1> custom http error page </h1>")
|
||||
})
|
||||
}
|
||||
|
||||
func registerGamesRoutes() {
|
||||
gamesMiddleware := func(ctx context.Context) {
|
||||
println(ctx.Method() + ": " + ctx.Path())
|
||||
ctx.Next()
|
||||
}
|
||||
|
||||
// party is just a group of routes with the same prefix
|
||||
// and middleware, i.e: "/games" and gamesMiddleware.
|
||||
games := app.Party("/games", gamesMiddleware)
|
||||
{ // braces are optional of course, it's just a style of code
|
||||
|
||||
// "GET" method
|
||||
games.Get("/{gameID:int}/clans", h)
|
||||
games.Get("/{gameID:int}/clans/clan/{clanPublicID:int}", h)
|
||||
games.Get("/{gameID:int}/clans/search", h)
|
||||
|
||||
// "PUT" method
|
||||
games.Put("/{gameID:int}/players/{clanPublicID:int}", h)
|
||||
games.Put("/{gameID:int}/clans/clan/{clanPublicID:int}", h)
|
||||
// remember: "clanPublicID" should not be changed to other routes with the same prefix.
|
||||
// "POST" method
|
||||
games.Post("/{gameID:int}/clans", h)
|
||||
games.Post("/{gameID:int}/players", h)
|
||||
games.Post("/{gameID:int}/clans/{clanPublicID:int}/leave", h)
|
||||
games.Post("/{gameID:int}/clans/{clanPublicID:int}/memberships/application", h)
|
||||
games.Post("/{gameID:int}/clans/{clanPublicID:int}/memberships/application/{action}", h) // {action} == {action:string}
|
||||
games.Post("/{gameID:int}/clans/{clanPublicID:int}/memberships/invitation", h)
|
||||
games.Post("/{gameID:int}/clans/{clanPublicID:int}/memberships/invitation/{action}", h)
|
||||
games.Post("/{gameID:int}/clans/{clanPublicID:int}/memberships/delete", h)
|
||||
games.Post("/{gameID:int}/clans/{clanPublicID:int}/memberships/promote", h)
|
||||
games.Post("/{gameID:int}/clans/{clanPublicID:int}/memberships/demote", h)
|
||||
}
|
||||
}
|
||||
|
||||
func registerSubdomains() {
|
||||
mysubdomain := app.Party("mysubdomain.")
|
||||
// http://mysubdomain.myhost.com
|
||||
mysubdomain.Get("/", func(ctx context.Context) {
|
||||
ctx.Writef("Hello from subdomain: %s , from host: %s, method: %s and path: %s", ctx.Subdomain(), ctx.Host(), ctx.Method(), ctx.Path())
|
||||
})
|
||||
}
|
||||
func main() {
|
||||
registerErrors()
|
||||
registerGamesRoutes()
|
||||
registerSubdomains()
|
||||
|
||||
// more random examples below:
|
||||
|
||||
app.Handle("GET", "/healthcheck", h)
|
||||
|
||||
// "POST" method
|
||||
// this handler reads raw body from the client/request
|
||||
// and sends back the same body
|
||||
// remember, we have limit to that body in order
|
||||
// to protect ourselves from "over heating".
|
||||
app.Post("/", func(ctx context.Context) {
|
||||
ctx.SetMaxRequestBodySize(maxBodySize) // set max request body that client can send.
|
||||
// get request body
|
||||
b, err := ioutil.ReadAll(ctx.Request().Body)
|
||||
// if is larger then send a bad request status
|
||||
if err != nil {
|
||||
ctx.StatusCode(iris.StatusBadRequest)
|
||||
ctx.Writef(err.Error())
|
||||
return
|
||||
}
|
||||
// send back the post body
|
||||
ctx.Write(b)
|
||||
})
|
||||
|
||||
// start the server on 0.0.0.0:8080
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
func h(ctx context.Context) {
|
||||
ctx.HTML("<h1>Path: " + ctx.Path() + "</h1>")
|
||||
}
|
35
_examples/beginner/routing/reverse/main.go
Normal file
35
_examples/beginner/routing/reverse/main.go
Normal file
|
@ -0,0 +1,35 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/core/router"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
// need for manually reverse routing when needed outside of view engine.
|
||||
// you normally don't need it because of the {{ urlpath "routename" "path" "values" "here"}}
|
||||
rv := router.NewRoutePathReverser(app)
|
||||
|
||||
myroute, _ := app.Get("/anything/{anythingparameter:path}", func(ctx context.Context) {
|
||||
paramValue := ctx.Params().Get("anythingparameter")
|
||||
ctx.Writef("The path after /anything is: %s", paramValue)
|
||||
})
|
||||
|
||||
// useful for links, altough iris' view engine has the {{ urlpath "routename" "path values"}} already.
|
||||
app.Get("/reverse_myroute", func(ctx context.Context) {
|
||||
myrouteRequestPath := rv.Path(myroute.Name, "any/path")
|
||||
ctx.HTML("Should be <b>/anything/any/path</b>: " + myrouteRequestPath)
|
||||
})
|
||||
|
||||
// execute a route, similar to redirect but without redirect :)
|
||||
app.Get("/execute_myroute", func(ctx context.Context) {
|
||||
ctx.Exec("GET", "/anything/any/path") // like it was called by the client.
|
||||
})
|
||||
|
||||
// http://localhost:8080/reverse_myroute
|
||||
// http://localhost:8080/execute_myroute
|
||||
// http://localhost:8080/anything/any/path/here
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
|
@ -1,21 +1,17 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
// output startup banner and error logs on os.Stdout
|
||||
app.Adapt(iris.DevLogger())
|
||||
// set the router, you can choose gorillamux too
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
app.Get("/servezip", func(c *iris.Context) {
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
file := "./files/first.zip"
|
||||
c.SendFile(file, "c.zip")
|
||||
ctx.SendFile(file, "c.zip")
|
||||
})
|
||||
|
||||
app.Listen(":8080")
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
|
|
@ -5,20 +5,16 @@ import (
|
|||
"io"
|
||||
"time" // showcase the delay
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
// output startup banner and error logs on os.Stdout
|
||||
app.Adapt(iris.DevLogger())
|
||||
// set the router, you can choose gorillamux too
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
timeWaitForCloseStream := 4 * time.Second
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
i := 0
|
||||
// goroutine in order to no block and just wait,
|
||||
// goroutine is OPTIONAL and not a very good option but it depends on the needs
|
||||
|
@ -39,7 +35,7 @@ func main() {
|
|||
time.Sleep(timeWaitForCloseStream)
|
||||
})
|
||||
|
||||
app.Get("/alternative", func(ctx *iris.Context) {
|
||||
app.Get("/alternative", func(ctx context.Context) {
|
||||
// Send the response in chunks and wait for a second between each chunk.
|
||||
ctx.StreamWriter(func(w io.Writer) bool {
|
||||
for i := 1; i <= 4; i++ {
|
||||
|
@ -52,5 +48,5 @@ func main() {
|
|||
})
|
||||
})
|
||||
|
||||
app.Listen(":8080")
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
|
|
@ -8,32 +8,33 @@ import (
|
|||
"strconv"
|
||||
"time"
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/view"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/view"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(iris.DevLogger())
|
||||
app.Adapt(httprouter.New())
|
||||
app.Adapt(view.HTML("./templates", ".html"))
|
||||
|
||||
app.AttachView(view.HTML("./templates", ".html"))
|
||||
|
||||
// Serve the form.html to the user
|
||||
app.Get("/upload", func(ctx *iris.Context) {
|
||||
app.Get("/upload", func(ctx context.Context) {
|
||||
//create a token (optionally)
|
||||
|
||||
now := time.Now().Unix()
|
||||
h := md5.New()
|
||||
io.WriteString(h, strconv.FormatInt(now, 10))
|
||||
token := fmt.Sprintf("%x", h.Sum(nil))
|
||||
//render the form with the token for any use you like
|
||||
ctx.Render("upload_form.html", token)
|
||||
|
||||
// render the form with the token for any use you like
|
||||
ctx.ViewData("", token)
|
||||
ctx.View("upload_form.html")
|
||||
})
|
||||
|
||||
// Handle the post request from the upload_form.html to the server
|
||||
app.Post("/upload", iris.LimitRequestBodySize(10<<20),
|
||||
func(ctx *iris.Context) {
|
||||
app.Post("/upload", context.LimitRequestBodySize(10<<20),
|
||||
func(ctx context.Context) {
|
||||
// or use ctx.SetMaxRequestBodySize(10 << 20)
|
||||
//to limit the uploaded file(s) size.
|
||||
|
||||
|
@ -41,8 +42,8 @@ func main() {
|
|||
file, info, err := ctx.FormFile("uploadfile")
|
||||
|
||||
if err != nil {
|
||||
ctx.HTML(iris.StatusInternalServerError,
|
||||
"Error while uploading: <b>"+err.Error()+"</b>")
|
||||
ctx.StatusCode(iris.StatusInternalServerError)
|
||||
ctx.HTML("Error while uploading: <b>" + err.Error() + "</b>")
|
||||
return
|
||||
}
|
||||
|
||||
|
@ -55,8 +56,8 @@ func main() {
|
|||
os.O_WRONLY|os.O_CREATE, 0666)
|
||||
|
||||
if err != nil {
|
||||
ctx.HTML(iris.StatusInternalServerError,
|
||||
"Error while uploading: <b>"+err.Error()+"</b>")
|
||||
ctx.StatusCode(iris.StatusInternalServerError)
|
||||
ctx.HTML("Error while uploading: <b>" + err.Error() + "</b>")
|
||||
return
|
||||
}
|
||||
defer out.Close()
|
||||
|
@ -64,6 +65,6 @@ func main() {
|
|||
io.Copy(out, file)
|
||||
})
|
||||
|
||||
// start the server at 127.0.0.1:8080
|
||||
app.Listen(":8080")
|
||||
// start the server at http://localhost:8080
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
|
@ -1,37 +1,39 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
// User bind struct
|
||||
type User struct {
|
||||
Firstname string `json:"firstname"`
|
||||
Lastname string `json:"lastname"`
|
||||
City string `json:"city"`
|
||||
Age int `json:"age"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
app.Post("/decode", func(ctx *iris.Context) {
|
||||
app.Post("/decode", func(ctx context.Context) {
|
||||
var user User
|
||||
ctx.ReadJSON(&user)
|
||||
|
||||
ctx.Writef("%s %s is %d years old!", user.Firstname, user.Lastname, user.Age)
|
||||
ctx.Writef("%s %s is %d years old and comes from %s!", user.Firstname, user.Lastname, user.Age, user.City)
|
||||
})
|
||||
|
||||
app.Get("/encode", func(ctx *iris.Context) {
|
||||
app.Get("/encode", func(ctx context.Context) {
|
||||
peter := User{
|
||||
Firstname: "John",
|
||||
Lastname: "Doe",
|
||||
City: "Neither FBI knows!!!",
|
||||
Age: 25,
|
||||
}
|
||||
|
||||
ctx.JSON(iris.StatusOK, peter)
|
||||
ctx.StatusCode(iris.StatusOK)
|
||||
ctx.JSON(peter)
|
||||
})
|
||||
|
||||
app.Listen(":8080")
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
|
|
@ -3,11 +3,12 @@ package main
|
|||
import (
|
||||
"time"
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/cache"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
var testMarkdownContents = `## Hello Markdown
|
||||
var markdownContents = []byte(`## Hello Markdown
|
||||
|
||||
This is a sample of Markdown contents
|
||||
|
||||
|
@ -39,7 +40,7 @@ All features of Sundown are supported, including:
|
|||
* **Fast processing**. It is fast enough to render on-demand in
|
||||
most web applications without having to cache the output.
|
||||
|
||||
* **Thread safety**. You can run multiple parsers in different
|
||||
* **Routine safety**. You can run multiple parsers in different
|
||||
goroutines without ill effect. There is no dependence on global
|
||||
shared state.
|
||||
|
||||
|
@ -51,32 +52,55 @@ All features of Sundown are supported, including:
|
|||
* **Standards compliant**. Output successfully validates using the
|
||||
W3C validation tool for HTML 4.01 and XHTML 1.0 Transitional.
|
||||
|
||||
[this is a link](https://github.com/kataras/iris) `
|
||||
[this is a link](https://github.com/kataras/iris) `)
|
||||
|
||||
// Cache should not be used on handlers that contain dynamic data.
|
||||
// Cache is a good and a must-feature on static content, i.e "about page" or for a whole blog site.
|
||||
func main() {
|
||||
app := iris.New()
|
||||
// output startup banner and error logs on os.Stdout
|
||||
app.Adapt(iris.DevLogger())
|
||||
// set the router, you can choose gorillamux too
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
app.Get("/hi", app.Cache(func(c *iris.Context) {
|
||||
c.WriteString("Hi this is a big content, do not try cache on small content it will not make any significant difference!")
|
||||
}, time.Duration(10)*time.Second))
|
||||
// first argument is the handler which response's we want to apply the cache.
|
||||
// if second argument, expiration, is <=time.Second then the cache tries to set the expiration from the "cache-control" maxage header's value(in seconds)
|
||||
// and if that header is empty or not exist then it sets a default of 5 minutes.
|
||||
writeMarkdownCached := cache.Cache(writeMarkdown, 10*time.Second) // or CacheHandler to get the handler
|
||||
|
||||
bodyHandler := func(ctx *iris.Context) {
|
||||
ctx.Markdown(iris.StatusOK, testMarkdownContents)
|
||||
}
|
||||
app.Get("/", writeMarkdownCached.ServeHTTP)
|
||||
// saves its content on the first request and serves it instead of re-calculating the content.
|
||||
// After 10 seconds it will be cleared and resetted.
|
||||
|
||||
expiration := time.Duration(5 * time.Second)
|
||||
|
||||
app.Get("/", app.Cache(bodyHandler, expiration))
|
||||
|
||||
// if expiration is <=time.Second then the cache tries to set the expiration from the "cache-control" maxage header's value(in seconds)
|
||||
// // if this header doesn't founds then the default is 5 minutes
|
||||
app.Get("/cache_control", app.Cache(func(ctx *iris.Context) {
|
||||
ctx.HTML(iris.StatusOK, "<h1>Hello!</h1>")
|
||||
}, -1))
|
||||
|
||||
app.Listen(":8080")
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
func writeMarkdown(ctx context.Context) {
|
||||
// tap multiple times the browser's refresh button and you will
|
||||
// see this println only once every 10 seconds.
|
||||
println("Handler executed. Content refreshed.")
|
||||
|
||||
ctx.Markdown(markdownContents)
|
||||
}
|
||||
|
||||
// Notes:
|
||||
// Cached handler is not changing your pre-defined headers,
|
||||
// so it will not send any additional headers to the client.
|
||||
// The cache happening at the server-side's memory.
|
||||
//
|
||||
// see "DefaultRuleSet" in "cache/client/ruleset.go" to see how you can add separated
|
||||
// rules to each of the cached handlers (`.AddRule`) with the help of "/cache/client/rule"'s definitions.
|
||||
//
|
||||
// The default rules are:
|
||||
/*
|
||||
// #1 A shared cache MUST NOT use a cached response to a request with an
|
||||
// Authorization header field
|
||||
rule.HeaderClaim(ruleset.AuthorizationRule),
|
||||
// #2 "must-revalidate" and/or
|
||||
// "s-maxage" response directives are not allowed to be served stale
|
||||
// (Section 4.2.4) by shared caches. In particular, a response with
|
||||
// either "max-age=0, must-revalidate" or "s-maxage=0" cannot be used to
|
||||
// satisfy a subsequent request without revalidating it on the origin
|
||||
// server.
|
||||
rule.HeaderClaim(ruleset.MustRevalidateRule),
|
||||
rule.HeaderClaim(ruleset.ZeroMaxAgeRule),
|
||||
// #3 custom No-Cache header used inside this library
|
||||
// for BOTH request and response (after get-cache action)
|
||||
rule.Header(ruleset.NoCacheRule, ruleset.NoCacheRule)
|
||||
*/
|
||||
|
|
|
@ -1,35 +1,34 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/typescript" // optinally
|
||||
"gopkg.in/kataras/iris.v6/adaptors/typescript/editor"
|
||||
"github.com/kataras/iris"
|
||||
|
||||
"github.com/kataras/iris/typescript" // optionally
|
||||
"github.com/kataras/iris/typescript/editor"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(iris.DevLogger())
|
||||
app.Adapt(httprouter.New()) // adapt a router, order doesn't matters
|
||||
// adapt a router, order doesn't matters
|
||||
|
||||
// optionally but good to have, I didn't put inside editor or the editor in the typescript compiler adaptors
|
||||
// because you may use tools like gulp and you may use the editor without the typescript compiler adaptor.
|
||||
// but if you need auto-compilation on .ts, we have a solution:
|
||||
ts := typescript.New()
|
||||
ts.Config.Dir = "./www/scripts/"
|
||||
app.Adapt(ts) // adapt the typescript compiler adaptor
|
||||
ts.Attach(app) // attach the typescript compiler adaptor
|
||||
|
||||
editorConfig := editor.Config{
|
||||
Hostname: "127.0.0.1",
|
||||
Hostname: "localhost",
|
||||
Port: 4444,
|
||||
WorkingDir: "./www/scripts/", // "/path/to/the/client/side/directory/",
|
||||
Username: "myusername",
|
||||
Password: "mypassword",
|
||||
}
|
||||
e := editor.New(editorConfig)
|
||||
app.Adapt(e) // adapt the editor
|
||||
e.Attach(app) // attach the editor
|
||||
|
||||
app.StaticWeb("/", "./www") // serve the index.html
|
||||
|
||||
app.Listen(":8080")
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
|
@ -1,43 +1,57 @@
|
|||
package main
|
||||
|
||||
// We don't have to reinvert the wheel, so we will use a good cors middleware
|
||||
// as a router wrapper for our entire app.
|
||||
// Follow the steps below:
|
||||
// +------------------------------------------------------------+
|
||||
// | Cors installation |
|
||||
// +------------------------------------------------------------+
|
||||
// go get -u github.com/rs/cors
|
||||
//
|
||||
// +------------------------------------------------------------+
|
||||
// | Cors wrapper usage |
|
||||
// +------------------------------------------------------------+
|
||||
// import "github.com/rs/cors"
|
||||
//
|
||||
// app := iris.New()
|
||||
// corsOptions := cors.Options{/* your options here */}
|
||||
// corsWrapper := cors.New(corsOptions).ServeHTTP
|
||||
// app.Wrap(corsWrapper)
|
||||
//
|
||||
// [your code goes here...]
|
||||
//
|
||||
// app.Run(iris.Addr(":8080"))
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/cors"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"github.com/rs/cors"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
app := iris.New()
|
||||
app.Adapt(iris.DevLogger())
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
crs := cors.New(cors.Options{
|
||||
corsOptions := cors.Options{
|
||||
AllowedOrigins: []string{"*"},
|
||||
AllowCredentials: true,
|
||||
})
|
||||
}
|
||||
|
||||
app.Adapt(crs) // this line should be added
|
||||
// adaptor supports cors allowed methods, middleware does not.
|
||||
corsWrapper := cors.New(corsOptions).ServeHTTP
|
||||
|
||||
// if you want per-route-only cors
|
||||
// then you should check https://github.com/iris-contrib/middleware/tree/master/cors
|
||||
app.WrapRouter(corsWrapper)
|
||||
|
||||
v1 := app.Party("/api/v1")
|
||||
{
|
||||
v1.Post("/home", func(c *iris.Context) {
|
||||
app.Log(iris.DevMode, "lalala")
|
||||
c.WriteString("Hello from /home")
|
||||
})
|
||||
v1.Get("/g", func(c *iris.Context) {
|
||||
app.Log(iris.DevMode, "lalala")
|
||||
c.WriteString("Hello from /home")
|
||||
})
|
||||
v1.Post("/h", func(c *iris.Context) {
|
||||
app.Log(iris.DevMode, "lalala")
|
||||
c.WriteString("Hello from /home")
|
||||
})
|
||||
v1.Get("/", h)
|
||||
v1.Put("/put", h)
|
||||
v1.Post("/post", h)
|
||||
}
|
||||
|
||||
app.Listen(":8080")
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
func h(ctx context.Context) {
|
||||
ctx.Application().Log(ctx.Path())
|
||||
ctx.Writef("Hello from %s", ctx.Path())
|
||||
}
|
||||
|
|
|
@ -0,0 +1,86 @@
|
|||
package main
|
||||
|
||||
// In this package I'll show you how to override the existing Context's functions and methods.
|
||||
// You can easly navigate to the advanced/custom-context to see how you can add new functions
|
||||
// to your own context (need a custom handler).
|
||||
//
|
||||
// This way is far easier to understand and it's faster when you want to override existing methods:
|
||||
import (
|
||||
"reflect"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/sessions"
|
||||
"github.com/kataras/iris/view"
|
||||
)
|
||||
|
||||
// Create your own custom Context, put any fields you wanna need.
|
||||
type MyContext struct {
|
||||
// Optional Part 1: embed (optional but required if you don't want to override all context's methods)
|
||||
context.Context // it's the internal/Context.go but you don't need to know it.
|
||||
}
|
||||
|
||||
var _ context.Context = &MyContext{} // optionally: validate on compile-time if MyContext implements context.Context.
|
||||
|
||||
// Optional Part 2:
|
||||
// The only one important if you will override the Context with an embedded context.Context inside it.
|
||||
func (ctx *MyContext) Next() {
|
||||
context.Next(ctx)
|
||||
}
|
||||
|
||||
// Override any context's method you want...
|
||||
// [...]
|
||||
|
||||
func (ctx *MyContext) HTML(htmlContents string) (int, error) {
|
||||
ctx.Application().Log("Executing .HTML function from MyContext")
|
||||
|
||||
ctx.ContentType("text/html")
|
||||
return ctx.WriteString(htmlContents)
|
||||
}
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
// Register a view engine on .html files inside the ./view/** directory.
|
||||
viewEngine := view.HTML("./view", ".html")
|
||||
app.AttachView(viewEngine)
|
||||
|
||||
// Register the session manager.
|
||||
sessionManager := sessions.New(sessions.Config{
|
||||
Cookie: "myappcookieid",
|
||||
})
|
||||
app.AttachSessionManager(sessionManager)
|
||||
|
||||
// The only one Required:
|
||||
// here is how you define how your own context will be created and acquired from the iris' generic context pool.
|
||||
app.ContextPool.Attach(func() context.Context {
|
||||
return &MyContext{
|
||||
// Optional Part 3:
|
||||
Context: context.NewContext(app),
|
||||
}
|
||||
})
|
||||
|
||||
// register your route, as you normally do
|
||||
app.Handle("GET", "/", recordWhichContetsJustForProofOfConcept, func(ctx context.Context) {
|
||||
// use the context's overridden HTML method.
|
||||
ctx.HTML("<h1> Hello from my custom context's HTML! </h1>")
|
||||
})
|
||||
|
||||
// this will be executed by the MyContext.Context
|
||||
// if MyContext is not directly define the View function by itself.
|
||||
app.Handle("GET", "/hi/{firstname:alphabetical}", recordWhichContetsJustForProofOfConcept, func(ctx context.Context) {
|
||||
firstname := ctx.Values().GetString("firstname")
|
||||
|
||||
ctx.ViewData("firstname", firstname)
|
||||
ctx.Gzip(true)
|
||||
|
||||
ctx.View("hi.html")
|
||||
})
|
||||
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
// should always print "($PATH) Handler is executing from 'MyContext'"
|
||||
func recordWhichContetsJustForProofOfConcept(ctx context.Context) {
|
||||
ctx.Application().Log("(%s) Handler is executing from: '%s'", ctx.Path(), reflect.TypeOf(ctx).Elem().Name())
|
||||
ctx.Next()
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
<h1> Hi {{.firstname}} </h1>
|
31
_examples/intermediate/custom-httpserver/iris-way/main.go
Normal file
31
_examples/intermediate/custom-httpserver/iris-way/main.go
Normal file
|
@ -0,0 +1,31 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.Writef("Hello from the server")
|
||||
})
|
||||
|
||||
app.Get("/mypath", func(ctx context.Context) {
|
||||
ctx.Writef("Hello from %s", ctx.Path())
|
||||
})
|
||||
|
||||
srv := &http.Server{Addr: ":8080" /* Any custom fields here: Handler and ErrorLog are setted to the server automatically */}
|
||||
// http://localhost:8080/
|
||||
// http://localhost:8080/mypath
|
||||
app.Run(iris.Server(srv)) // same as app.Run(iris.Addr(":8080"))
|
||||
|
||||
// More:
|
||||
// see "multi" if you need to use more than one server at the same app.
|
||||
//
|
||||
// for a custom listener use: iris.Listener(net.Listener) or
|
||||
// iris.TLS(cert,key) or iris.AutoTLS(), see "custom-listener" example for those.
|
||||
}
|
|
@ -1,33 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
// output startup banner and error logs on os.Stdout
|
||||
app.Adapt(iris.DevLogger())
|
||||
// set the router, you can choose gorillamux too
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
ctx.Writef("Hello from the server")
|
||||
})
|
||||
|
||||
app.Get("/mypath", func(ctx *iris.Context) {
|
||||
ctx.Writef("Hello from %s", ctx.Path())
|
||||
})
|
||||
|
||||
// call .Boot before use the 'app' as an http.Handler on a custom http.Server
|
||||
app.Boot()
|
||||
|
||||
// create our custom fasthttp server and assign the Handler/Router
|
||||
fsrv := &http.Server{Handler: app, Addr: ":8080"}
|
||||
fsrv.ListenAndServe()
|
||||
|
||||
// navigate to http://127.0.0.1:8080/mypath
|
||||
}
|
48
_examples/intermediate/custom-httpserver/multi/main.go
Normal file
48
_examples/intermediate/custom-httpserver/multi/main.go
Normal file
|
@ -0,0 +1,48 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.Writef("Hello from the server")
|
||||
})
|
||||
|
||||
app.Get("/mypath", func(ctx context.Context) {
|
||||
ctx.Writef("Hello from %s", ctx.Path())
|
||||
})
|
||||
|
||||
// Note: It's not needed if the first action is "go app.Run".
|
||||
if err := app.Build(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// start a secondary server listening on localhost:9090.
|
||||
// use "go" keyword for Listen functions if you need to use more than one server at the same app.
|
||||
//
|
||||
// http://localhost:9090/
|
||||
// http://localhost:9090/mypath
|
||||
srv1 := &http.Server{Addr: ":9090", Handler: app}
|
||||
go srv1.ListenAndServe()
|
||||
println("Start a server listening on http://localhost:9090")
|
||||
|
||||
// start a "second-secondary" server listening on localhost:5050.
|
||||
//
|
||||
// http://localhost:5050/
|
||||
// http://localhost:5050/mypath
|
||||
srv2 := &http.Server{Addr: ":5050", Handler: app}
|
||||
go srv2.ListenAndServe()
|
||||
println("Start a server listening on http://localhost:5050")
|
||||
|
||||
// Note: app.Run is totally optional, we have already built the app with app.Build,
|
||||
// you can just make a new http.Server instead.
|
||||
// http://localhost:8080/
|
||||
// http://localhost:8080/mypath
|
||||
app.Run(iris.Addr(":8080")) // Block here.
|
||||
}
|
43
_examples/intermediate/custom-httpserver/std-way/main.go
Normal file
43
_examples/intermediate/custom-httpserver/std-way/main.go
Normal file
|
@ -0,0 +1,43 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.Writef("Hello from the server")
|
||||
})
|
||||
|
||||
app.Get("/mypath", func(ctx context.Context) {
|
||||
ctx.Writef("Hello from %s", ctx.Path())
|
||||
})
|
||||
|
||||
// call .Build before use the 'app' as an http.Handler on a custom http.Server
|
||||
if err := app.Build(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// create our custom server and assign the Handler/Router
|
||||
srv := &http.Server{Handler: app, Addr: ":8080"} // you have to set Handler:app and Addr, see "iris-way" which does this automatically.
|
||||
// http://localhost:8080/
|
||||
// http://localhost:8080/mypath
|
||||
println("Start a server listening on http://localhost:8080")
|
||||
srv.ListenAndServe() // same as app.Run(iris.Addr(":8080"))
|
||||
|
||||
// Notes:
|
||||
// Banne and Tray are not shown at all. Same for the Interrupt Handler, even if app's configuration allows them.
|
||||
//
|
||||
// `.Run` is the only one function that cares about those three.
|
||||
|
||||
// More:
|
||||
// see "multi" if you need to use more than one server at the same app.
|
||||
//
|
||||
// for a custom listener use: iris.Listener(net.Listener) or
|
||||
// iris.TLS(cert,key) or iris.AutoTLS(), see "custom-listener" example for those.
|
||||
}
|
|
@ -1,33 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"net"
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
// output startup banner and error logs on os.Stdout
|
||||
app.Adapt(iris.DevLogger())
|
||||
// set the router, you can choose gorillamux too
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
ctx.Writef("Hello from the server")
|
||||
})
|
||||
|
||||
app.Get("/mypath", func(ctx *iris.Context) {
|
||||
ctx.Writef("Hello from %s", ctx.Path())
|
||||
})
|
||||
|
||||
// create our custom listener
|
||||
ln, err := net.Listen("tcp4", ":8080")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// use of the custom listener
|
||||
app.Serve(ln)
|
||||
}
|
|
@ -1,26 +1,24 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/sessions"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/sessions"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
// output startup banner and error logs on os.Stdout
|
||||
app.Adapt(iris.DevLogger())
|
||||
// set the router, you can choose gorillamux too
|
||||
app.Adapt(httprouter.New())
|
||||
sess := sessions.New(sessions.Config{Cookie: "myappsessionid"})
|
||||
app.Adapt(sess)
|
||||
|
||||
app.Get("/set", func(ctx *iris.Context) {
|
||||
sess := sessions.New(sessions.Config{Cookie: "myappsessionid"})
|
||||
app.AttachSessionManager(sess)
|
||||
|
||||
app.Get("/set", func(ctx context.Context) {
|
||||
ctx.Session().SetFlash("name", "iris")
|
||||
ctx.Writef("Message setted, is available for the next request")
|
||||
})
|
||||
|
||||
app.Get("/get", func(ctx *iris.Context) {
|
||||
app.Get("/get", func(ctx context.Context) {
|
||||
name := ctx.Session().GetFlashString("name")
|
||||
if name == "" {
|
||||
ctx.Writef("Empty name!!")
|
||||
|
@ -29,7 +27,7 @@ func main() {
|
|||
ctx.Writef("Hello %s", name)
|
||||
})
|
||||
|
||||
app.Get("/test", func(ctx *iris.Context) {
|
||||
app.Get("/test", func(ctx context.Context) {
|
||||
name := ctx.Session().GetFlashString("name")
|
||||
if name == "" {
|
||||
ctx.Writef("Empty name!!")
|
||||
|
@ -41,5 +39,5 @@ func main() {
|
|||
|
||||
})
|
||||
|
||||
app.Listen(":8080")
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
|
48
_examples/intermediate/graceful-shutdown/basic/main.go
Normal file
48
_examples/intermediate/graceful-shutdown/basic/main.go
Normal file
|
@ -0,0 +1,48 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
stdContext "context"
|
||||
"time"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/core/host"
|
||||
)
|
||||
|
||||
// Before continue, please read the below notes:
|
||||
//
|
||||
// Current version of Iris is auto-graceful on control+C/command+C
|
||||
// or whenever host's .Shutdown called.
|
||||
//
|
||||
// In order to add a custom interrupt handler(ctrl+c/cmd+c) or
|
||||
// shutdown manually you have to "schedule a host supervisor's task" or
|
||||
// use the core/host package manually or use a pure http.Server as we already seen at "custom-server" example.
|
||||
//
|
||||
// At this example, we will disable the interrupt handler and set our own interrupt handler.
|
||||
func main() {
|
||||
app := iris.New()
|
||||
// output startup banner and error logs on os.Stdout
|
||||
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.HTML(" <h1>hi, I just exist in order to see if the server is closed</h1>")
|
||||
})
|
||||
|
||||
// tasks are always running in their go-routine by-default.
|
||||
//
|
||||
// register custom interrupt handler, fires when ctrl+C/cmd+C pressed.
|
||||
app.Scheduler.Schedule(host.OnInterrupt(func(proc host.TaskProcess) {
|
||||
println("Shutdown the server gracefully...")
|
||||
|
||||
timeout := 5 * time.Second // give the server 5 seconds to wait for idle connections.
|
||||
ctx, cancel := stdContext.WithTimeout(stdContext.Background(), timeout)
|
||||
defer cancel()
|
||||
proc.Host().Shutdown(ctx) // Shutdown the underline supervisor's server
|
||||
}))
|
||||
|
||||
// Start the server and disable the default interrupt handler in order to use our scheduled interrupt task.
|
||||
app.Run(iris.Addr(":8080"), iris.WithoutInterruptHandler)
|
||||
}
|
||||
|
||||
// Note:
|
||||
// You can just use an http.Handler with your own signal notify channel and do that as you did with the net/http
|
||||
// package. I will not show this way, but you can find many examples on the internet.
|
72
_examples/intermediate/graceful-shutdown/custom-host/main.go
Normal file
72
_examples/intermediate/graceful-shutdown/custom-host/main.go
Normal file
|
@ -0,0 +1,72 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
stdContext "context"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/core/host"
|
||||
)
|
||||
|
||||
// The difference from its parent main.go is that
|
||||
// with a custom host we're able to call the host's shutdown
|
||||
// and be notified about its .Shutdown call.
|
||||
// Almost the same as before.
|
||||
func main() {
|
||||
app := iris.New()
|
||||
// output startup banner and error logs on os.Stdout
|
||||
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.HTML(" <h1>hi, I just exist in order to see if the server is closed</h1>")
|
||||
})
|
||||
|
||||
// build the framework when all routing-relative actions are declared.
|
||||
if err := app.Build(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// create our custom host supervisor by adapting
|
||||
// a custom http server
|
||||
srv := host.New(&http.Server{Addr: ":8080", Handler: app})
|
||||
|
||||
// tasks are always running in their go-routine by-default.
|
||||
//
|
||||
// register custom interrupt handler, fires when ctrl+C/cmd+C pressed, as we did before.
|
||||
srv.Schedule(host.OnInterrupt(func(proc host.TaskProcess) {
|
||||
println("Shutdown the server gracefully...")
|
||||
|
||||
timeout := 5 * time.Second // give the server 5 seconds to wait for idle connections.
|
||||
ctx, cancel := stdContext.WithTimeout(stdContext.Background(), timeout)
|
||||
defer cancel()
|
||||
proc.Host().DeferFlow() // defer the exit, in order to catch the event
|
||||
srv.Shutdown(ctx) // Shutdown the supervisor, only this way the proc.Host().Done will be notified
|
||||
// the proc.Host().Shutdown, closes the underline server but no the supervisor.
|
||||
// This behavior was choosen because is inneed for custom maintanance services
|
||||
// (i.e restart server every week without loosing connections) which you can easly adapt with Iris.
|
||||
}))
|
||||
|
||||
// schedule a task to be notify when the server was closed by our interrutp handler,
|
||||
// optionally ofcourse.
|
||||
srv.ScheduleFunc(func(proc host.TaskProcess) {
|
||||
select {
|
||||
case <-proc.Host().Done(): // when .Host.Shutdown(ctx) called.
|
||||
println("Server was closed.")
|
||||
proc.Host().RestoreFlow() // Restore the flow in order to exit(continue after the srv.ListenAndServe)
|
||||
}
|
||||
})
|
||||
|
||||
// Start our custom host
|
||||
println("Server is running at :8080")
|
||||
srv.ListenAndServe()
|
||||
// Go to the console and press ctrl+c(for windows and linux) or cmd+c for osx.
|
||||
// The output should be:
|
||||
// Server is running at:8080
|
||||
// Shutdown the server gracefully...
|
||||
// Server was closed.
|
||||
}
|
||||
|
||||
// Note:
|
||||
// You can just use an http.Handler with your own signal notify channel and do that as you did with the net/http
|
||||
// package. I will not show this way, but you can find many examples on the internet.
|
|
@ -1,32 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
// output startup banner and error logs on os.Stdout
|
||||
app.Adapt(iris.DevLogger())
|
||||
// set the router, you can choose gorillamux too
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
app.Get("/hi", func(ctx *iris.Context) {
|
||||
ctx.HTML(iris.StatusOK, " <h1>hi, I just exist in order to see if the server is closed</h1>")
|
||||
})
|
||||
|
||||
app.Adapt(iris.EventPolicy{
|
||||
// Interrupt Event means when control+C pressed on terminal.
|
||||
Interrupted: func(*iris.Framework) {
|
||||
// shut down gracefully, but wait 5 seconds the maximum before closed
|
||||
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
app.Shutdown(ctx)
|
||||
},
|
||||
})
|
||||
|
||||
app.Listen(":8080")
|
||||
}
|
35
_examples/intermediate/httptest/main.go
Normal file
35
_examples/intermediate/httptest/main.go
Normal file
|
@ -0,0 +1,35 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/sessions"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
app.AttachSessionManager(sessions.New(sessions.Config{Cookie: "mysessionid"}))
|
||||
|
||||
app.Get("/hello", func(ctx context.Context) {
|
||||
sess := ctx.Session()
|
||||
if !sess.HasFlash() {
|
||||
ctx.HTML("<h1> Unauthorized Page! </h1>")
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(context.Map{
|
||||
"Message": "Hello",
|
||||
"From": sess.GetFlash("name"),
|
||||
})
|
||||
})
|
||||
|
||||
app.Post("/login", func(ctx context.Context) {
|
||||
sess := ctx.Session()
|
||||
if !sess.HasFlash() {
|
||||
sess.SetFlash("name", ctx.FormValue("name"))
|
||||
}
|
||||
|
||||
})
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
|
@ -3,7 +3,7 @@ package main
|
|||
import (
|
||||
"testing"
|
||||
|
||||
"gopkg.in/kataras/iris.v6/httptest"
|
||||
"github.com/kataras/iris/httptest"
|
||||
)
|
||||
|
||||
// $ cd _example
|
||||
|
@ -27,6 +27,3 @@ func TestNewApp(t *testing.T) {
|
|||
// test /hello nauthorized again, it should be return 401 now (flash should be removed)
|
||||
e.GET("/hello").Expect().Status(401).Body().Equal("<h1> Unauthorized Page! </h1>")
|
||||
}
|
||||
|
||||
// for advanced test examples navigate there:
|
||||
// https://github.com/gavv/httpexpect/blob/master/_examples/iris_test.go
|
|
@ -1,15 +1,13 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/middleware/i18n"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/middleware/i18n"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(iris.DevLogger()) // adapt a simple internal logger to print any errors
|
||||
app.Adapt(httprouter.New()) // adapt a router, you can use gorillamux too
|
||||
|
||||
app.Use(i18n.New(i18n.Config{
|
||||
Default: "en-US",
|
||||
|
@ -19,14 +17,14 @@ func main() {
|
|||
"el-GR": "./locales/locale_el-GR.ini",
|
||||
"zh-CN": "./locales/locale_zh-CN.ini"}}))
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
|
||||
// it tries to find the language by:
|
||||
// ctx.Get("language") , that should be setted on other middleware before the i18n middleware*
|
||||
// ctx.Values().GetString("language")
|
||||
// if that was empty then
|
||||
// it tries to find from the URLParameter setted on the configuration
|
||||
// if not found then
|
||||
// it tries to find the language by the "lang" cookie
|
||||
// it tries to find the language by the "language" cookie
|
||||
// if didn't found then it it set to the Default setted on the configuration
|
||||
|
||||
// hi is the key, 'kataras' is the %s on the .ini file
|
||||
|
@ -36,7 +34,7 @@ func main() {
|
|||
// or:
|
||||
hi := i18n.Translate(ctx, "hi", "kataras")
|
||||
|
||||
language := ctx.Get(iris.TranslateLanguageContextKey) // language is the language key, example 'en-US'
|
||||
language := ctx.Values().GetString(ctx.Application().ConfigurationReadOnly().GetTranslateLanguageContextKey()) // return is form of 'en-US'
|
||||
|
||||
// The first succeed language found saved at the cookie with name ("language"),
|
||||
// you can change that by changing the value of the: iris.TranslateLanguageContextKey
|
||||
|
@ -46,6 +44,6 @@ func main() {
|
|||
// go to http://localhost:8080/?lang=el-GR
|
||||
// or http://localhost:8080
|
||||
// or http://localhost:8080/?lang=zh-CN
|
||||
app.Listen(":8080")
|
||||
app.Run(iris.Addr(":8080"))
|
||||
|
||||
}
|
||||
|
|
|
@ -1,24 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/middleware/pprof"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(iris.DevLogger())
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
ctx.HTML(iris.StatusOK, "<h1> Please click <a href='/debug/pprof'>here</a>")
|
||||
})
|
||||
|
||||
app.Get("/debug/pprof/*action", pprof.New())
|
||||
// ___________
|
||||
// Note:
|
||||
// if you prefer gorillamux adaptor, then
|
||||
// the wildcard for gorilla mux (as you already know) is '{action:.*}' instead of '*action'.
|
||||
app.Listen(":8080")
|
||||
}
|
|
@ -1,34 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/middleware/recover"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
// fast way to enable non-fatal messages to be printed to the user
|
||||
// (yes in iris even recover's errors are not fatal because it's restarting,
|
||||
// ProdMode messages are only for things that Iris cannot continue at all,
|
||||
// these are logged by-default but you can change that behavior too by passing a different LoggerPolicy to the .Adapt)
|
||||
app.Adapt(iris.DevLogger())
|
||||
// adapt a router, you can use gorillamux too
|
||||
app.Adapt(httprouter.New())
|
||||
|
||||
// use this recover(y) middleware
|
||||
app.Use(recover.New())
|
||||
|
||||
i := 0
|
||||
// let's simmilate a panic every next request
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
i++
|
||||
if i%2 == 0 {
|
||||
panic("a panic here")
|
||||
}
|
||||
ctx.Writef("Hello, refresh one time more to get panic!")
|
||||
})
|
||||
|
||||
// http://localhost:8080
|
||||
app.Listen(":8080")
|
||||
}
|
39
_examples/intermediate/route-state/main.go
Normal file
39
_examples/intermediate/route-state/main.go
Normal file
|
@ -0,0 +1,39 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
none, _ := app.None("/invisible/{username}", func(ctx context.Context) {
|
||||
ctx.Writef("Hello %s with method: %s", ctx.Values().GetString("username"), ctx.Method())
|
||||
|
||||
if from := ctx.Values().GetString("from"); from != "" {
|
||||
ctx.Writef("\nI see that you're coming from %s", from)
|
||||
}
|
||||
})
|
||||
|
||||
app.Get("/change", func(ctx context.Context) {
|
||||
|
||||
if none.IsOnline() {
|
||||
none.Method = iris.MethodNone
|
||||
} else {
|
||||
none.Method = iris.MethodGet
|
||||
}
|
||||
|
||||
// refresh re-builds the router at serve-time in order to be notified for its new routes.
|
||||
app.RefreshRouter()
|
||||
})
|
||||
|
||||
app.Get("/execute", func(ctx context.Context) {
|
||||
// same as navigating to "http://localhost:8080/invisible/kataras" when /change has being invoked and route state changed
|
||||
// from "offline" to "online"
|
||||
ctx.Values().Set("from", "/execute") // values and session can be shared when calling Exec from a "foreign" context.
|
||||
ctx.Exec("GET", "/invisible/kataras")
|
||||
})
|
||||
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
7225
_examples/intermediate/serve-embedded-files/assets/css/bootstrap.min.css
vendored
Normal file
7225
_examples/intermediate/serve-embedded-files/assets/css/bootstrap.min.css
vendored
Normal file
File diff suppressed because it is too large
Load Diff
BIN
_examples/intermediate/serve-embedded-files/assets/favicon.ico
Normal file
BIN
_examples/intermediate/serve-embedded-files/assets/favicon.ico
Normal file
Binary file not shown.
After Width: | Height: | Size: 264 KiB |
9190
_examples/intermediate/serve-embedded-files/assets/js/jquery-2.1.1.js
vendored
Normal file
9190
_examples/intermediate/serve-embedded-files/assets/js/jquery-2.1.1.js
vendored
Normal file
File diff suppressed because it is too large
Load Diff
287
_examples/intermediate/serve-embedded-files/bindata.go
Normal file
287
_examples/intermediate/serve-embedded-files/bindata.go
Normal file
File diff suppressed because one or more lines are too long
43
_examples/intermediate/serve-embedded-files/main.go
Normal file
43
_examples/intermediate/serve-embedded-files/main.go
Normal file
|
@ -0,0 +1,43 @@
|
|||
// for templates + go-bindata checkout the '_examples\intermediate\view\embedding-templates-into-app' folder.
|
||||
package main
|
||||
|
||||
// First of all, execute: $ go get https://github.com/jteeuwen/go-bindata
|
||||
// Secondly, execute the command: cd $GOPATH/src/github.com/kataras/iris/_examples/intermediate/serve-embedded-files && go-bindata ./assets/...
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.HTML("<b> Hi from index</b>")
|
||||
})
|
||||
|
||||
// executing this go-bindata command creates a source file named 'bindata.go' which
|
||||
// gives you the Asset and AssetNames funcs which we will pass into .StaticAssets
|
||||
// for more viist: https://github.com/jteeuwen/go-bindata
|
||||
// Iris gives you a way to integrade these functions to your web app
|
||||
|
||||
// For the reason that you may use go-bindata to embed more than your assets,
|
||||
// you should pass the 'virtual directory path', for example here is the : "./assets"
|
||||
// and the request path, which these files will be served to,
|
||||
// you can set as "/assets" or "/static" which resulting on http://localhost:8080/static/*anyfile.*extension
|
||||
app.StaticEmbedded("/static", "./assets", Asset, AssetNames)
|
||||
|
||||
// that's all
|
||||
// this will serve the ./assets (embedded) files to the /static request path for example the favicon.ico will be served as :
|
||||
// http://localhost:8080/static/favicon.ico
|
||||
// Methods: GET and HEAD
|
||||
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
||||
// Navigate to:
|
||||
// http://localhost:8080/static/favicon.ico
|
||||
// http://localhost:8080/static/js/jquery-2.1.1.js
|
||||
// http://localhost:8080/static/css/bootstrap.min.css
|
||||
|
||||
// Now, these files are are stored into inside your executable program, no need to keep it in the same location with your assets folder.
|
|
@ -1,11 +1,12 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/sessions"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/sessions/sessiondb/redis"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/sessions/sessiondb/redis/service"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
|
||||
"github.com/kataras/iris/sessions"
|
||||
"github.com/kataras/iris/sessions/sessiondb/redis"
|
||||
"github.com/kataras/iris/sessions/sessiondb/redis/service"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
@ -29,16 +30,16 @@ func main() {
|
|||
|
||||
// the rest of the code stays the same.
|
||||
app := iris.New()
|
||||
app.Adapt(iris.DevLogger()) // enable all (error) logs
|
||||
app.Adapt(httprouter.New()) // select the httprouter as the servemux
|
||||
// enable all (error) logs
|
||||
// select the httprouter as the servemux
|
||||
|
||||
// Adapt the session manager we just created
|
||||
app.Adapt(mySessions)
|
||||
// Attach the session manager we just created
|
||||
app.AttachSessionManager(mySessions)
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.Writef("You should navigate to the /set, /get, /delete, /clear,/destroy instead")
|
||||
})
|
||||
app.Get("/set", func(ctx *iris.Context) {
|
||||
app.Get("/set", func(ctx context.Context) {
|
||||
|
||||
//set session values
|
||||
ctx.Session().Set("name", "iris")
|
||||
|
@ -47,27 +48,27 @@ func main() {
|
|||
ctx.Writef("All ok session setted to: %s", ctx.Session().GetString("name"))
|
||||
})
|
||||
|
||||
app.Get("/get", func(ctx *iris.Context) {
|
||||
app.Get("/get", func(ctx context.Context) {
|
||||
// get a specific key, as string, if no found returns just an empty string
|
||||
name := ctx.Session().GetString("name")
|
||||
|
||||
ctx.Writef("The name on the /set was: %s", name)
|
||||
})
|
||||
|
||||
app.Get("/delete", func(ctx *iris.Context) {
|
||||
app.Get("/delete", func(ctx context.Context) {
|
||||
// delete a specific key
|
||||
ctx.Session().Delete("name")
|
||||
})
|
||||
|
||||
app.Get("/clear", func(ctx *iris.Context) {
|
||||
app.Get("/clear", func(ctx context.Context) {
|
||||
// removes all entries
|
||||
ctx.Session().Clear()
|
||||
})
|
||||
|
||||
app.Get("/destroy", func(ctx *iris.Context) {
|
||||
app.Get("/destroy", func(ctx context.Context) {
|
||||
//destroy, removes the entire session data and cookie
|
||||
ctx.SessionDestroy()
|
||||
})
|
||||
|
||||
app.Listen(":8080")
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
|
|
@ -1,20 +1,21 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/sessions"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
|
||||
"github.com/kataras/iris/sessions"
|
||||
)
|
||||
|
||||
var (
|
||||
key = "my_sessionid"
|
||||
)
|
||||
|
||||
func secret(ctx *iris.Context) {
|
||||
func secret(ctx context.Context) {
|
||||
|
||||
// Check if user is authenticated
|
||||
if auth, _ := ctx.Session().GetBoolean("authenticated"); !auth {
|
||||
ctx.EmitError(iris.StatusForbidden)
|
||||
ctx.StatusCode(iris.StatusForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
|
@ -22,7 +23,7 @@ func secret(ctx *iris.Context) {
|
|||
ctx.WriteString("The cake is a lie!")
|
||||
}
|
||||
|
||||
func login(ctx *iris.Context) {
|
||||
func login(ctx context.Context) {
|
||||
session := ctx.Session()
|
||||
|
||||
// Authentication goes here
|
||||
|
@ -32,7 +33,7 @@ func login(ctx *iris.Context) {
|
|||
session.Set("authenticated", true)
|
||||
}
|
||||
|
||||
func logout(ctx *iris.Context) {
|
||||
func logout(ctx context.Context) {
|
||||
session := ctx.Session()
|
||||
|
||||
// Revoke users authentication
|
||||
|
@ -41,15 +42,15 @@ func logout(ctx *iris.Context) {
|
|||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(httprouter.New())
|
||||
// Look https://github.com/kataras/iris/tree/v6/adaptors/sessions/_examples for more features,
|
||||
|
||||
// Look https://github.com/kataras/iris/tree/master/sessions/_examples for more features,
|
||||
// i.e encode/decode and lifetime.
|
||||
sess := sessions.New(sessions.Config{Cookie: key})
|
||||
app.Adapt(sess)
|
||||
app.AttachSessionManager(sess)
|
||||
|
||||
app.Get("/secret", secret)
|
||||
app.Get("/login", login)
|
||||
app.Get("/logout", logout)
|
||||
|
||||
app.Listen(":8080")
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
|
|
@ -5,15 +5,15 @@ import (
|
|||
// At this example we use the gorilla's securecookie library:
|
||||
"github.com/gorilla/securecookie"
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/sessions"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/sessions"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(iris.DevLogger()) // enable all (error) logs
|
||||
app.Adapt(httprouter.New()) // select the httprouter as the servemux
|
||||
// enable all (error) logs
|
||||
// select the httprouter as the servemux
|
||||
|
||||
cookieName := "mycustomsessionid"
|
||||
// AES only supports key sizes of 16, 24 or 32 bytes.
|
||||
|
@ -28,19 +28,17 @@ func main() {
|
|||
Decode: secureCookie.Decode,
|
||||
})
|
||||
|
||||
app.Adapt(mySessions)
|
||||
|
||||
// OPTIONALLY:
|
||||
// import "gopkg.in/kataras/iris.v6/adaptors/sessions/sessiondb/redis"
|
||||
// import "github.com/kataras/iris/sessions/sessiondb/redis"
|
||||
// or import "github.com/kataras/go-sessions/sessiondb/$any_available_community_database"
|
||||
// mySessions.UseDatabase(redis.New(...))
|
||||
|
||||
app.Adapt(mySessions) // Adapt the session manager we just created.
|
||||
app.AttachSessionManager(mySessions) // Attach the session manager we just created.
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.Writef("You should navigate to the /set, /get, /delete, /clear,/destroy instead")
|
||||
})
|
||||
app.Get("/set", func(ctx *iris.Context) {
|
||||
app.Get("/set", func(ctx context.Context) {
|
||||
|
||||
//set session values
|
||||
ctx.Session().Set("name", "iris")
|
||||
|
@ -49,24 +47,24 @@ func main() {
|
|||
ctx.Writef("All ok session setted to: %s", ctx.Session().GetString("name"))
|
||||
})
|
||||
|
||||
app.Get("/get", func(ctx *iris.Context) {
|
||||
app.Get("/get", func(ctx context.Context) {
|
||||
// get a specific key, as string, if no found returns just an empty string
|
||||
name := ctx.Session().GetString("name")
|
||||
|
||||
ctx.Writef("The name on the /set was: %s", name)
|
||||
})
|
||||
|
||||
app.Get("/delete", func(ctx *iris.Context) {
|
||||
app.Get("/delete", func(ctx context.Context) {
|
||||
// delete a specific key
|
||||
ctx.Session().Delete("name")
|
||||
})
|
||||
|
||||
app.Get("/clear", func(ctx *iris.Context) {
|
||||
app.Get("/clear", func(ctx context.Context) {
|
||||
// removes all entries
|
||||
ctx.Session().Clear()
|
||||
})
|
||||
|
||||
app.Get("/destroy", func(ctx *iris.Context) {
|
||||
app.Get("/destroy", func(ctx context.Context) {
|
||||
//destroy, removes the entire session data and cookie
|
||||
ctx.SessionDestroy()
|
||||
}) // Note about destroy:
|
||||
|
@ -75,5 +73,5 @@ func main() {
|
|||
// mySessions.DestroyByID
|
||||
// mySessions.DestroyAll
|
||||
|
||||
app.Listen(":8080")
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
|
|
@ -3,15 +3,15 @@ package main
|
|||
import (
|
||||
"time"
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/sessions"
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/sessions"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Adapt(iris.DevLogger()) // enable all (error) logs
|
||||
app.Adapt(httprouter.New()) // select the httprouter as the servemux
|
||||
// enable all (error) logs
|
||||
// select the httprouter as the servemux
|
||||
|
||||
mySessions := sessions.New(sessions.Config{
|
||||
// Cookie string, the session's client cookie name, for example: "mysessionid"
|
||||
|
@ -23,8 +23,6 @@ func main() {
|
|||
// -1 means expire when browser closes
|
||||
// or set a value, like 2 hours:
|
||||
Expires: time.Hour * 2,
|
||||
// the length of the sessionid's cookie's value
|
||||
CookieLength: 32,
|
||||
// if you want to invalid cookies on different subdomains
|
||||
// of the same host, then enable it
|
||||
DisableSubdomainPersistence: false,
|
||||
|
@ -32,16 +30,16 @@ func main() {
|
|||
})
|
||||
|
||||
// OPTIONALLY:
|
||||
// import "gopkg.in/kataras/iris.v6/adaptors/sessions/sessiondb/redis"
|
||||
// import "github.com/kataras/iris/sessions/sessiondb/redis"
|
||||
// or import "github.com/kataras/go-sessions/sessiondb/$any_available_community_database"
|
||||
// mySessions.UseDatabase(redis.New(...))
|
||||
|
||||
app.Adapt(mySessions) // Adapt the session manager we just created.
|
||||
app.AttachSessionManager(mySessions) // Attach the session manager we just created.
|
||||
|
||||
app.Get("/", func(ctx *iris.Context) {
|
||||
app.Get("/", func(ctx context.Context) {
|
||||
ctx.Writef("You should navigate to the /set, /get, /delete, /clear,/destroy instead")
|
||||
})
|
||||
app.Get("/set", func(ctx *iris.Context) {
|
||||
app.Get("/set", func(ctx context.Context) {
|
||||
|
||||
//set session values
|
||||
ctx.Session().Set("name", "iris")
|
||||
|
@ -50,24 +48,24 @@ func main() {
|
|||
ctx.Writef("All ok session setted to: %s", ctx.Session().GetString("name"))
|
||||
})
|
||||
|
||||
app.Get("/get", func(ctx *iris.Context) {
|
||||
app.Get("/get", func(ctx context.Context) {
|
||||
// get a specific key, as string, if no found returns just an empty string
|
||||
name := ctx.Session().GetString("name")
|
||||
|
||||
ctx.Writef("The name on the /set was: %s", name)
|
||||
})
|
||||
|
||||
app.Get("/delete", func(ctx *iris.Context) {
|
||||
app.Get("/delete", func(ctx context.Context) {
|
||||
// delete a specific key
|
||||
ctx.Session().Delete("name")
|
||||
})
|
||||
|
||||
app.Get("/clear", func(ctx *iris.Context) {
|
||||
app.Get("/clear", func(ctx context.Context) {
|
||||
// removes all entries
|
||||
ctx.Session().Clear()
|
||||
})
|
||||
|
||||
app.Get("/destroy", func(ctx *iris.Context) {
|
||||
app.Get("/destroy", func(ctx context.Context) {
|
||||
|
||||
//destroy, removes the entire session data and cookie
|
||||
ctx.SessionDestroy()
|
||||
|
@ -78,5 +76,5 @@ func main() {
|
|||
// mySessions.DestroyByID
|
||||
// mySessions.DestroyAll
|
||||
|
||||
app.Listen(":8080")
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user