Skip to content

Latest commit

 

History

History
450 lines (332 loc) · 21.3 KB

README_ZH.md

File metadata and controls

450 lines (332 loc) · 21.3 KB

示例

请先学习如何使用 net/http

这里包含大部分 iris 网络微框架的简单使用示例

这些示例不一定是最优解,但涵盖了 Iris 的大部分重要功能。

概览

目录结构

Iris 是个底层框架, 对 MVC 模式有很好的支持,但不限制文件夹结构,你可以随意组织你的代码。

如何组织代码取决于你的需求. 我们无法告诉你如何设计程序,但你可以仔细查看下面的示例,也许有些片段可以直接放到你的程序里。

HTTP 监听

配置

路由、路由分组、路径动态参数、路由参数处理宏 、 自定义上下文

  • 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)

可以浏览以下示例,以便更好理解

hero (输出的一种高效包装模式)

MVC 模式

Iris 对 MVC (Model View Controller) 有一流的支持, 在 Go 社区里是独一无二的。

Iris 支持快速的请求数据,模型,持久性数据和绑定。

特点

支持所有的HTTP访问方式,例如,如果想要处理GET请求,那么控制器应该有一个叫做Get()的函数 你可以在同一个控制器上面定义不止一个请求处理函数(method function).

通过BeforeActivation对每个控制器自定义事件回调,使自定义控制器的结构方法(struct's methods)处理自定义路径(甚至是包含参数是正则表达式的路径),例如:

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 // 以及任何你已经知道的标准API调用

    // 1-> 方法
    // 2-> 路径
    // 3-> 被解释成handler的控制器函数名称
    // 4-> 在MyCustomHandler之前需要执行的其他handler
    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" }

通过定义依赖项服务或者有一个单一(Singleton)控制器范畴来持久化你控制器结构中的数据(多次请求间共享的数据)

在控制器间共享依赖或者把他们注册到上层MVC应用,以及 在一个控制器内部可以修改每一个控制器在BeforeActivation可选事件回调上的依赖项的能力。 即 func(c *MyController) BeforeActivation(b mvc.BeforeActivation) { b.Dependencies().Add/Remove(...) }.

访问Context作为一个控制器的域(field)(不需要手动绑定)即Ctx iris.Context,或者通过一个方法的输入参数,即func(ctx iris.Context, otherArguments...)

你控制器结构中的模型(在模型函数中设置并且由视图来渲染) 你可以通过一个控制器的方法来返回模型或者设置一个请求生命周期的域

并且在同一个生命周期中把这个域返回给另一个方法。

正如你之前所熟知的流程,mvc应用程序有它自己的以标准iris API iris/router.Party作为类型的路由(router)控制器可以被注册到任意集合(party),包括子域名,这个集合会像所预料那样开始完成处理器工作。

可额外调用BeginRequest(ctx)在任何方法被执行前进行初始化,对于调用中间层(middlewares)或者使用同一组数据的多个方法而言十分有效

同样可调用EndRequest(ctx)在任何方法执行后做完成工作(finalization)

递归继承参考我们mvc.SessionController的例子,它以Session *sessions.SessionManager *sessions.Sessions作为嵌入域,由它的BeginRequest来传递,看这里

这只是一个例子,你可以使用sessions.Session,它作为一个MVC应用的动态依赖从管理者的Start返回,即 mvcApp.Register(sessions.New(sessions.Config{Cookie: "iris_session_id"}).Start).

通过控制器方法的输入参数来访问动态路径参数,不需要绑定。 当你需要使用Iris的默认语法从一个控制器里来解析一个handler,你需要在这个方法前加上By, 大写表示一个新的子路径。例如:

如果是 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}

如果是 mvc.New(app.Party("/profile")).Handle(new(profile.Controller))

  • func(*Controller) GetBy(username string) - GET:/profile/{param:string}

如果是 mvc.New(app.Party("/assets")).Handle(new(file.Controller))

  • func(*Controller) GetByWildard(path string) - GET:/assets/{param:path}

    支持的函数接收者类型是:int, int64, bool and string。

可以通过输出参数来响应,即

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)

其中mvc.Result是一个仅包含Dispatch(ctx iris.Context)的接口

Iris MVC 模式代码复用

通过创建互相独立的组建,开发者可以简单快捷地在别的应用里面复用组建。 一个应用同样的(或相似的)视图使用不同的数据可以被重构给另一个应用,因为视图仅仅处理数据怎么展示给用户。

如果你是一个新的web后端开发者,请先阅读MVC架构模式,一个不错的入门是wikipedia article.

参考下面的示例

子域名

改造 http.Handler/HandlerFunc

视图

模板引擎 调用声明
template/html iris.HTML(...)
django iris.Django(...)
handlebars iris.Handlebars(...)
amber iris.Amber(...)
pug(jade) iris.Pug(...)

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. 只要使用context#ResponseWriter,你可以服务quicktemplatehero templates文件。 看这the http_responsewriter/quicktemplatehttp_responsewriter/herotemplate的例子

认证

文件服务器

如何读取context.Request() *http.Request

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. context.Request()返回你已知的同一http.Request, 这些例子给出了Context使用这个对象的地方。 除此以外你可以在使用iris之前那样子使用它

如何写入context.ResponseWriter() http.ResponseWriter

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.

context.Request()返回了一个http.ResponseWriter的迷醉(魔幻)版本, 这些例子给出了Context使用这个对象的地方。 除此以外你可以在使用iris之前那样子使用它

ORM

其他

试验性质处理器

更多

https://github.com/kataras/iris/tree/master/middleware#third-party-handlers

自动 API 文档

测试

The httptest package is your way for end-to-end HTTP testing, it uses the httpexpect library created by our friend, gavv. httptest包是你用于端对端HTTP测试的,它使用我们朋友gavv创建的httpexpect库

例子

缓存

Iris 独立缓存包 package.

可以随意使用自定义的缓存包。

Cookies

Sessions

Iris session 管理独立包 package.

可以随意使用自定义的 Session 管理包。

Websockets

iris websocket库依赖于它自己的.

设计这个包的目的是处理原始websockets,虽然它的API和著名的socket.io很像。我最近读了一片文章,并且对我 决定给iris设计一个快速的websocket限定包并且不是一个向后传递类socket.io的包。你可以阅读这个链接里的文章https://medium.com/@ivanderbyl/why-you-don-t-need-socket-io-6848f1c871cd。

如果你愿意,你可以自由使用你自己喜欢的websockets包。

Typescript 自动化工具

Typescript 自动化工具独立库: https://github.com/kataras/iris/tree/master/typescript 包含相关示例

大兄弟

进一步学习可通过 godocshttps://docs.iris-go.com

不要忘记点赞 star or watch 这个项目会一直跟进最新趋势。