控制器 taro Posted on Apr 4 2021 Golang iris # 配置中间件 # 方式一 ```go import ( "github.com/kataras/iris/mvc" ) mvc.New(app.Party("/hello")).Handle(new(controllers.HelloController)) ``` ```go // file: web/controllers/hello_controller.go package controllers import ( "errors" "github.com/kataras/iris/mvc" ) // 声明控制器名称 // it handles GET: /hello and GET: /hello/{name} type HelloController struct{} // 配置模板和模板渲染参数 var helloView = mvc.View{ Name: "hello/index.html", Data: map[string]interface{}{ "Title": "Hello Page", "MyMessage": "Welcome to my awesome website", }, } // get方法请求 会返回`helloView` func (c *HelloController) Get() mvc.Result { return helloView } //控制错误输出 var errBadName = errors.New("bad name") var badName = mvc.Response{Err: errBadName, Code: 400} // GetBy returns a "Hello {name}" response. // GetBy 方法会将后面的内容当做name传递进来 //`mvc.Response` and `mvc.View` 两种类型都可以 作为`mvc.Result` 输出 // curl -i http://localhost:8080/hello/iris // curl -i http://localhost:8080/hello/anything func (c *HelloController) GetBy(name string) mvc.Result { if name != "iris" { return badName // or // GetBy(name string) (mvc.Result, error) { // return nil, errBadName // } } // return mvc.Response{Text: "Hello " + name} OR: return mvc.View{ Name: "hello/name.html", Data: name, } } ``` # 一般所用属性 ```go type UserController struct { // 上下文属性会自动填充 // 每个请求会新建一个UserController对象 Ctx iris.Context // Our UserService, it's an interface which // is binded from the main application. Service services.UserService // Session, binded using dependency injection from the main.go. Session *sessions.Session } ``` # 获取session ```go userID := c.Session.GetInt64Default(userIDKey, 0) ``` # Get请求 ```go var registerStaticView = mvc.View{ Name: "user/register.html", Data: iris.Map{"Title": "User Registration"}, } // GetRegister handles GET: http://localhost:8080/user/register. func (c *UserController) GetRegister() mvc.Result { if c.isLoggedIn() { c.logout() } return registerStaticView } ``` # Post请求 ```go // PostRegister handles POST: http://localhost:8080/user/register. func (c *UserController) PostRegister() mvc.Result { // 获取字段 var ( firstname = c.Ctx.FormValue("firstname") username = c.Ctx.FormValue("username") password = c.Ctx.FormValue("password") ) // 新建一个用户对象 u, err := c.Service.Create(password, datamodels.User{ Username: username, Firstname: firstname, }) // 设置session c.Session.Set(userIDKey, u.ID) return mvc.Response{ // if not nil then this error will be shown instead. Err: err, // redirect to /user/me. Path: "/user/me", // When redirecting from POST to GET request you -should- use this HTTP status code, // however there're some (complicated) alternatives if you // search online or even the HTTP RFC. // Status "See Other" RFC 7231, however iris can automatically fix that // but it's good to know you can set a custom code; // Code: 303, } } ``` MVC中使用中间件 视图