zoukankan      html  css  js  c++  java
  • Iris 初试

    官网:https://iris-go.com

    推荐文档: https://www.kancloud.cn/adapa/go-web-iris/1108131

    Iris MVC介绍

    • 什么是MVC
      Model(模型):它是应用程序的主体部分,主要包括业务的逻辑操作和数据模型
      View: 用户与之交互的界面
      Controller: 接受来自界面的请求并交给模型渲染

       MVC 工作流程:

    • Iris MVC目录介绍
      ├── dataModels        # 数据模型目录,主要放结构体,用以表示数据
      ├── go.mod
      ├── repositories        #用以封装所有对数据库的操作,和dataModels中的表一一对应
      ├── service                  #models的业务逻辑放在service
      └── web
          ├── controllers       #控制我们的请求
          └── views                  #存放模板
      └── main.go                 #项目入口
      
    • Iris MVC 人口文件 main.go, 下面我们通过简单的例子来介绍基本用法
      package main
      
      import "github.com/kataras/iris"
      func main() {
      	app := iris.New() // 实例一个iris对象
      	//配置路由
      	app.Get("/", func(ctx iris.Context) {
      		ctx.WriteString("Hello Iris")
      	})
      	app.Post("/", func(ctx iris.Context) {
      		ctx.Write([]byte("Hello Iris"))
      	})
      
      	// 路由分组
      	party := app.Party("/hello")
      	// 此处它的路由地址是: /hello/world
      	party.Get("/world", func(ctx iris.Context) {
      		ctx.WriteString("hello world")
      	})
      
      	// 启动服务器
      	app.Run(iris.Addr(":8085"),iris.WithCharset("UTF-8"))
      	// 监听地址:本服务器上任意id端口8085,设置字符集utf8
      }
      

    注意: 在go.mod 中导入的包, 如果能正常使用,但是goland飘好,可以采用以下方式

    1. 在setting中 Go -> GOPATH -> 勾选Index entire GOPATH
    2. 在环境变量中添加: GO111MODULE=on ; 在~/.bashrc 中添加 export ....
    	相关解释:可以用环境变量 GO111MODULE 开启或关闭模块支持,它有三个可选值:off、on、auto,默认: 1. GO111MODULE=off 无模块支持,go 会从 GOPATH 和 vendor 文件夹寻找包。
    	   2. GO111MODULE=on 模块支持,go 会忽略 GOPATH 和 vendor 文件夹,只根据 go.mod 下载依赖。
    	   3. GO111MODULE=auto 在 GOPATH/src 外面且根目录有 go.mod 文件时,开启模块支持。
    3、如果出现2 processes running 一直无法出来结果,那么多半是代理:https://goproxy.cn

    路由部分

    • 普通路由
      package main
      
      import "github.com/kataras/iris"
      
      func main() {
         app := iris.New()
         //GET 方法
         app.Get("/", handler)
         // POST 方法
         app.Post("/", handler)
         // PUT 方法
         app.Put("/", handler)
         // DELETE 方法
         app.Delete("/", handler)
         //OPTIONS 方法
         app.Options("/", handler)
         //TRACE 方法
         app.Trace("/", handler)
         //CONNECT 方法
         app.Connect("/", handler)
         //HEAD 方法
         app.Head("/", handler)
         // PATCH 方法
         app.Patch("/", handler)
         //任意的http请求方法如option等
         app.Any("/", handler)
      
         app.Run(iris.Addr(":8085"),iris.WithCharset("UTF-8"))
      }
      
      // 处理函数
      func handler(ctx iris.Context) {
         ctx.Writef("methdo:%s path:%s",ctx.Method(),ctx.Path())
      }
      
    • 路由分组
      package main
      
      import "github.com/kataras/iris"
      
      func main()  {
         app := iris.New()
      
         // 分组
         userRouter := app.Party("/user")
         // route: /user/{name}/home  例如:/user/dollarKiller/home
         userRouter.Get("/{name:string}/home", func(ctx iris.Context) {
            name := ctx.Params().Get("name")     // 使用ctx请求对象中那参数
            ctx.Writef("you name: %s",name)
         })
         // route: /user/post
         userRouter.Post("/post", func(ctx iris.Context) {
            ctx.Writef("method:%s,path;%s",ctx.Method(),ctx.Path())
         })
      
         app.Run(iris.Addr(":8085"),iris.WithCharset("UTF-8"))
      }
      
      /*
      	 ctx.Params().Get()  获取参数
      	 ctx.Writef()    返回对象
      	 ctx.Method()  请求方式
      	 ctx.Path()   请求路径
      	 app.Party()   路由分组,路由派对
      */
      
    • 动态路由
      package main
      import "github.com/kataras/iris"
      
      func main() {
         app := iris.New()
      
         // 路由传参
         app.Get("/username/{name}", func(ctx iris.Context) {
            name := ctx.Params().Get("name")
            fmt.Println(name)
         })
      
         // 设置参数
         app.Get("/profile/{id:int min(1)}", func(ctx iris.Context) {
            i, e := ctx.Params().GetInt("id")
            if e != nil {
               ctx.WriteString("error you input")
            }
      
            ctx.WriteString(strconv.Itoa(i))
         })
      
         // 设置错误码
         app.Get("/profile/{id:int min(1)}/friends/{friendid:int max(8) else 504}", func(ctx iris.Context) {
            i, _ := ctx.Params().GetInt("id")
            getInt, _ := ctx.Params().GetInt("friendid")
            ctx.Writef("Hello id:%d looking for friend id: ",i,getInt)
         })// 如果没有传递所有路由的macros,这将抛出504错误代码而不是404.
      
         // 正则表达式
         app.Get("/lowercase/{name:string regexp(^[a-z]+)}", func(ctx iris.Context) {
            ctx.Writef("name should be only lowercase, otherwise this handler will never executed: %s", ctx.Params().Get("name"))
         })
      
         app.Run(iris.Addr(":8085"),iris.WithCharset("UTF-8"))
      }
      

    简单的Web实例

    目录结构:

    ├── dataModels                                               # 数据中心
    │   └── movice.go
    ├── go.mod                                                       # 包管理
    ├── go.sum
    ├── main.go                                                      # 程序入口
    ├── repositories                                              #  数据管理组
    │   └── movice_repositories.go               # 数据管理员
    ├── service                                                         # 服务管理组
    │   └── movie_server.go                              # 服务管理员
    └── web
        ├── controllers                                              #  逻辑中心
        │   └── movice_controller.go                 # 请求的响应中心,通过服务管理员调度数据管理员调度数据   
        └── views                                                         # 模板中心
            └── movie                                                   
                └── index.html
    
    • movie.go 基础的数据, 对应数据库中的表等,使得数据库表结构可以映射到程序
      package dataModels
      // 数据
      type Movice struct {
      	Name string
      }
      
    • movice_repositories.go 数据管理员, 接口数据库+数据中心的表结构映射,整理出各自的功能如.结合数据库的真是数据+基础表的程序代码结构, 使其可以ORM
      package repositories
      import "testIris/dataModels"
      
      // 需要实现的接口
      type MovieRepository interface {
      	GetMovieName() string
      }
      
      // Movie 的封装类  数据管理员
      type MovieManager struct {
      
      }
      
      // 构造函数创建MovieManager, 返回的值的接口 由于MovieManager实现了这个接口
      func NewMovieManager() MovieRepository {
      	return &MovieManager{}
      }
      
      func (m *MovieManager) GetMovieName() string {
      	// 模拟已经从查询到数据
      	movie := &dataModels.Movice{Name:"理查德姑妈"}
      	return movie.Name
      }
      
    • movie_server.go 主要用来整理数据管理员的功能,同时在提供服务给controller
      package service
      
      import (
      	"fmt"
      	"testIris/repositories"
      )
      
      // 服务提供的接口,用来整合repositories, 服务管理员的功能接口
      type MovieServer interface {
      	ShowMoviceName() string
      }
      
      // 服务管理员, 用来管理数据管理员
      type MovieServiceManager struct {
      	repo repositories.MovieRepository
      }
      
      // 初始化服务管理员
      func NewMovieServiceManger(repo repositories.MovieRepository) MovieServer {
      	return &MovieServiceManager{repo:repo}
      }
      
      // 服务管理员的功能实现
      func (m *MovieServiceManager) ShowMoviceName() string {
      	fmt.Println("我们获取到的视频名称: "+m.repo.GetMovieName())
      	return "我们获取到的视频名称: "+m.repo.GetMovieName()
      }
      
    • movie_controller.go 逻辑处理中心,通过请求的不同方式出发不同的函数,返回不同的View渲染结构
      package controllers
      
      import (
      	"github.com/kataras/iris/mvc"
      	"testIris/repositories"
      	"testIris/service"
      )
      
      type MovieController struct {
      }
      
      // 这个controller有Get方法的监听, 最后返回一个视图
      func (c *MovieController) Get() mvc.View {
      	// 创建一个Movie的管理者,他可以实例出movie也可以取movie的属性,相当于movie的管理员
      	movieRepository := repositories.NewMovieManager()  // 用来使得 repositories 管理 dataModelss
      	// 初始化一个服务管理员, 调用他的接口功能 来操作数据管理员
      	movieService := service.NewMovieServiceManger(movieRepository)
      	// 其实本质上是 数据管理员去给服务管理员movie的名字
      	movieResult := movieService.ShowMoviceName()
      	return mvc.View{      // 模板实例
      		Name:"movie/index.html",
      		Data:movieResult,
      	}
      }
      
    • index.html 模板
      <h1>   {{.}}  </h1>
      
    • main.go 程序入口
      package main
      
      import (
      	"github.com/kataras/iris"
      	"github.com/kataras/iris/mvc"
      	"log"
      	"testIris/web/controllers"
      )
      
      func main() {
      	app := iris.New()
      	app.Logger().SetLevel("debug")
      	// 模板注册  将符合路径下的以指定结尾的文件作为模板
      	app.RegisterView(iris.HTML("./web/views", ".html"))
      	// 注册控制器, 请求过来后触发对应的controller
      	mvc.New(app.Party("/hello")).Handle(new(controllers.MovieController))
      
      	err := app.Run(
      		iris.Addr("localhost:8080"),
      	)
      	if nil != nil {
      		log.Fatal(err)
      	}
      }
      
       
  • 相关阅读:
    OAuth客户端调用
    OAuth中client id的处理
    Task作为返回值以及Task<TResult>作为返回值
    Netscaler立身之本—NAT
    Citrix Netscaler负载均衡算法
    Netscaler重置密码的方法
    Netscaler的超高端口复用助力应对公网地址紧张
    Netscaler工作流程
    深入理解Netscaler INat
    Citrix Netscaler版本管理和选择
  • 原文地址:https://www.cnblogs.com/double-W/p/12589685.html
Copyright © 2011-2022 走看看