请先学习如何使用 net/http
这里包含大部分 iris 网络微框架的简单使用示例
这些示例不一定是最优解,但涵盖了 Iris 的大部分重要功能。
- Hello world!
- Hello WebAssemply! NEW
- 基础
- 教程: 在线人数
- 教程: A Todo MVC Application using Iris and Vue.js
- 教程: 结合 BoltDB 生成短网址
- 教程: 用安卓设备搭建服务器 (MUST)
- POC: Convert the medium-sized project "Parrot" from native to Iris
- POC: Isomorphic react/hot reloadable/redux/css-modules starter kit
- 教程: DropzoneJS 上传
- 教程: Caddy 服务器使用
- 教程: Iris + MongoDB
- 教程: API for Apache Kafka NEW
Iris 是个底层框架, 对 MVC 模式有很好的支持,但不限制文件夹结构,你可以随意组织你的代码。
如何组织代码取决于你的需求. 我们无法告诉你如何设计程序,但你可以仔细查看下面的示例,也许有些片段可以直接放到你的程序里。
- 基础用法 * 忽略错误信息
- UNIX socket file
- TLS
- Letsencrypt (自动认证)
- 进程关闭通知
- 自定义 TCP 监听器 * 通用 net.Listener
- 自定义 HTTP 服务 * easy way
- 优雅关闭
* 使用
RegisterOnInterrupt
* 自定义通知
app.Get("{userid:int min(1)}", myHandler)
app.Post("{asset:path}", myHandler)
app.Put("{custom:string regexp([a-z]+)}", myHandler)
提示: 不同于其他路由处理, iris 路由可以处理以下各种情况:
// 匹配静态前缀 "/assets/" 的各种请求
app.Get("/assets/{asset:path}", assetsWildcardHandler)
// 只匹配 GET "/"
app.Get("/", indexHandler)
// 只匹配 GET "/about"
app.Get("/about", aboutHandler)
// 匹配前缀为 "/profile/" 的所有 GET 请求
// 接着是其余部分的匹配
app.Get("/profile/{username:string}", userHandler)
// 只匹配 "/profile/me" GET 请求,
// 这和 /profile/{username:string}
// 或跟通配符 {root:path} 不冲突
app.Get("/profile/me", userHandler)
// 匹配所有前缀为 /users/ 的 GET 请求
// 参数为数字,且 >= 1
app.Get("/user/{userid:int min(1)}", getUserHandler)
// 匹配所有前缀为 /users/ 的 DELETE 请求
// 参数为数字,且 >= 1
app.Delete("/user/{userid:int min(1)}", deleteUserHandler)
// 匹配所有 GET 请求,除了 "/", "/about", 或其他以 "/assets/" 开头
// 因为它不会与其他路线冲突。
app.Get("{root:path}", rootWildcardHandler)
可以浏览以下示例,以便更好理解
- 概览
- 基本使用
- 控制器
- 自定义 HTTP 错误
- 动态路径
- Write your own custom parameter types NEW
- 反向路由
- Custom Router (high-level) NEW
- 自定义包装
- 自定义上下文 * 方法重写 * 新实现方式
- 路由状态
- 中间件定义 * 路由前 * 全局
Iris 对 MVC (Model View Controller) 有一流的支持, 在 Go 社区里是独一无二的。
Iris 支持快速的请求数据,模型,持久性数据和绑定。
特点
All HTTP Methods are supported, for example if want to serve GET
then the controller should have a function named Get()
,
you can define more than one method function to serve in the same Controller.
Serve custom controller's struct's methods as handlers with custom paths(even with regex parametermized path) via the BeforeActivation
custom event callback, per-controller. Example:
import (
"github.com/kataras/iris"
"github.com/kataras/iris/mvc"
)
func main() {
app := iris.New()
mvc.Configure(app.Party("/root"), myMVC)
app.Run(iris.Addr(":8080"))
}
func myMVC(app *mvc.Application) {
// app.Register(...)
// app.Router.Use/UseGlobal/Done(...)
app.Handle(new(MyController))
}
type MyController struct {}
func (m *MyController) BeforeActivation(b mvc.BeforeActivation) {
// b.Dependencies().Add/Remove
// b.Router().Use/UseGlobal/Done // and any standard API call you already know
// 1-> Method
// 2-> Path
// 3-> The controller's function name to be parsed as handler
// 4-> Any handlers that should run before the MyCustomHandler
b.Handle("GET", "/something/{id:long}", "MyCustomHandler", anyMiddleware...)
}
// GET: http://localhost:8080/root
func (m *MyController) Get() string { return "Hey" }
// GET: http://localhost:8080/root/something/{id:long}
func (m *MyController) MyCustomHandler(id int64) string { return "MyCustomHandler says Hey" }
Persistence data inside your Controller struct (share data between requests)
by defining services to the Dependencies or have a Singleton
controller scope.
Share the dependencies between controllers or register them on a parent MVC Application, and ability
to modify dependencies per-controller on the BeforeActivation
optional event callback inside a Controller,
i.e func(c *MyController) BeforeActivation(b mvc.BeforeActivation) { b.Dependencies().Add/Remove(...) }
.
Access to the Context
as a controller's field(no manual binding is neede) i.e Ctx iris.Context
or via a method's input argument, i.e func(ctx iris.Context, otherArguments...)
.
Models inside your Controller struct (set-ed at the Method function and rendered by the View). You can return models from a controller's method or set a field in the request lifecycle and return that field to another method, in the same request lifecycle.
Flow as you used to, mvc application has its own Router
which is a type of iris/router.Party
, the standard iris api.
Controllers
can be registered to any Party
, including Subdomains, the Party's begin and done handlers work as expected.
Optional BeginRequest(ctx)
function to perform any initialization before the method execution,
useful to call middlewares or when many methods use the same collection of data.
Optional EndRequest(ctx)
function to perform any finalization after any method executed.
Inheritance, recursively, see for example our mvc.SessionController
, it has the Session *sessions.Session
and Manager *sessions.Sessions
as embedded fields
which are filled by its BeginRequest
, here.
This is just an example, you could use the sessions.Session
which returned from the manager's Start
as a dynamic dependency to the MVC Application, i.e
mvcApp.Register(sessions.New(sessions.Config{Cookie: "iris_session_id"}).Start)
.
Access to the dynamic path parameters via the controller's methods' input arguments, no binding is needed.
When you use the Iris' default syntax to parse handlers from a controller, you need to suffix the methods
with the By
word, uppercase is a new sub path. Example:
If mvc.New(app.Party("/user")).Handle(new(user.Controller))
func(*Controller) Get()
-GET:/user
.func(*Controller) Post()
-POST:/user
.func(*Controller) GetLogin()
-GET:/user/login
func(*Controller) PostLogin()
-POST:/user/login
func(*Controller) GetProfileFollowers()
-GET:/user/profile/followers
func(*Controller) PostProfileFollowers()
-POST:/user/profile/followers
func(*Controller) GetBy(id int64)
-GET:/user/{param:long}
func(*Controller) PostBy(id int64)
-POST:/user/{param:long}
If mvc.New(app.Party("/profile")).Handle(new(profile.Controller))
func(*Controller) GetBy(username string)
-GET:/profile/{param:string}
If mvc.New(app.Party("/assets")).Handle(new(file.Controller))
-
func(*Controller) GetByWildard(path string)
-GET:/assets/{param:path}
Supported types for method functions receivers: int, int64, bool and string.
Response via output arguments, optionally, i.e
func(c *ExampleController) Get() string |
(string, string) |
(string, int) |
int |
(int, string) |
(string, error) |
error |
(int, error) |
(any, bool) |
(customStruct, error) |
customStruct |
(customStruct, int) |
(customStruct, string) |
mvc.Result or (mvc.Result, error)
where mvc.Result is an interface which contains only that function: Dispatch(ctx iris.Context)
.
By creating components that are independent of one another, developers are able to reuse components quickly and easily in other applications. The same (or similar) view for one application can be refactored for another application with different data because the view is simply handling how the data is being displayed to the user.
If you're new to back-end web development read about the MVC architectural pattern first, a good start is that wikipedia article.
参考下面的示例
- Hello world UPDATED
- Session Controller UPDATED
- Overview - Plus Repository and Service layers UPDATED
- Login showcase - Plus Repository and Service layers UPDATED
- Singleton NEW
- Websocket Controller NEW
- Register Middleware NEW
- Vue.js Todo MVC NEW
- From func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)
- From http.Handler or http.HandlerFunc
- From func(http.HandlerFunc) http.HandlerFunc
模板引擎 | 调用声明 |
---|---|
template/html | iris.HTML(...) |
django | iris.Django(...) |
handlebars | iris.Handlebars(...) |
amber | iris.Amber(...) |
pug(jade) | iris.Pug(...) |
- Overview
- Hi
- A simple Layout
- Layouts:
yield
andrender
tmpl funcs - The
urlpath
tmpl func - The
url
tmpl func - Inject Data Between Handlers
- Embedding Templates Into App Executable File
- Write to a custom
io.Writer
- Greeting with Pug (Jade)`
- Pug (Jade) Actions`
- Pug (Jade) Includes`
- Pug (Jade) Extends`
You can serve quicktemplate and hero templates files too, simply by using the context#ResponseWriter
, take a look at the http_responsewriter/quicktemplate and http_responsewriter/herotemplate examples.
- Favicon
- Basic
- Embedding Files Into App Executable File
- Embedding Gziped Files Into App Executable File NEW
- Send/Force-Download Files
- Single Page Applications
- Read JSON
- Read XML
- Read Form
- Read Custom per type
- Read Custom via Unmarshaler
- Upload/Read File
- Upload multiple files with an easy way
The
context.Request()
returns the same *http.Request you already know, these examples show some places where the Context uses this object. Besides that you can use it as you did before iris.
- Write
valyala/quicktemplate
templates - Write
shiyanhui/hero
templates - Text, Markdown, HTML, JSON, JSONP, XML, Binary
- Write Gzip
- Stream Writer
- Transactions
- SSE NEW
- SSE (third-party package usage for server sent events)
The
context/context#ResponseWriter()
returns an enchament version of a http.ResponseWriter, these examples show some places where the Context uses this object. Besides that you can use it as you did before iris.
- Request Logger
- Localization and Internationalization
- Recovery
- Profiling (pprof)
- Internal Application File Logger
- Google reCAPTCHA
- Casbin wrapper
- Casbin middleware
- Cloudwatch
- CORS
- JWT
- Newrelic
- Prometheus
- Secure
- Tollboothic
- Cross-Site Request Forgery Protection
https://github.com/kataras/iris/tree/master/middleware#third-party-handlers
The httptest
package is your way for end-to-end HTTP testing, it uses the httpexpect library created by our friend, gavv.
Iris 独立缓存包 package.
可以随意使用自定义的缓存包。
Iris session 管理独立包 package.
可以随意使用自定义的 Session 管理包。
iris websocket library lives on its own package.
The package is designed to work with raw websockets although its API is similar to the famous socket.io. I have read an article recently and I felt very contented about my decision to design a fast websocket-only package for Iris and not a backwards socket.io-like package. You can read that article by following this link: https://medium.com/@ivanderbyl/why-you-don-t-need-socket-io-6848f1c871cd.
如果你愿意,你可以自由使用你自己喜欢的websockets包。
Typescript 自动化工具独立库: https://github.com/kataras/iris/tree/master/typescript 包含相关示例
进一步学习可通过 godocs 和 https://docs.iris-go.com
不要忘记点赞 star or watch 这个项目会一直跟进最新趋势。