lris框架基础案例 下载

lris框架基础案例
下载

  

//俩种下载方式选1
# go get -u github.com/kataras/iris
# git clone https://github.com/kataras/iris.git

postman下载
http://y.downya.com/down1/postman_v7.6.0_downyi.com.zip

1. Get、Post、Put等请求

  1 package main
  2 
  3 import (
  4     "github.com/kataras/iris"
  5     "github.com/kataras/iris/context"
  6 )
  7 
  8 //main方法
  9 func main() {
 10 
 11     //GET请求
 12     // http://localhost:8080/hello
 13     //app.Handle("GET", "/hello", func(context context.Context) {
 14     //    context.HTML("<h1> Hello world. </h1>")
 15     //})
 16     //app.Get("/hello", func(context context.Context) {
 17     //    context.HTML("<h1> Hello world. </h1>")
 18     //})
 19     //
 20     //app.Handle("GET", "/string", func(context context.Context) {
 21     //    context.WriteString(" This is get request ")
 22     //})
 23     //
 24     ////POST请求
 25     //app.Handle("POST", "/postHello", func(context context.Context) {
 26     //    context.HTML("<h1> This is post request </h1>")
 27     //})
 28     //app.Post("/postHello", func(context context.Context) {
 29     //    context.HTML("<h1> This is post request </h1>")
 30     //})
 31     //
 32     ////Options
 33     //app.Handle("OPTIONS", "/options", func(context context.Context) {
 34     //    context.HTML("<h1> This is  options request </h1>")
 35     //})
 36     //app.Options("/options", func(context context.Context) {
 37     //
 38     //})
 39 
 40     //http://localhost:8080/user/info
 41     //app.Get("/user/info", func(context context.Context) {
 42     //    //context.WriteString("Hello world")
 43     //    context.HTML("<h1> Hello wrold </h1>")
 44     //})
 45     //app.Handle("GET", "/user/info", func(context context.Context) {
 46     //    context.Text("Hello world")
 47     //})
 48 
 49     //POST请求
 50     //app.Post("/user/info", func(context context.Context) {
 51     //    context.WriteString(" User Info is Post Request ")
 52     //})
 53     //app.Handle("POST", "/user/info", func(context context.Context) {
 54     //    context.WriteString(" User Info is Post Request , Deal is in handle func ")
 55     //})
 56     //
 57 
 58     app := iris.New()
 59 
 60     app.Get("/getRequest", func(context context.Context) {
 61         //处理get请求,请求的url为:/getRequest
 62         path := context.Path()
 63         app.Logger().Info(path)
 64     })
 65 
 66     //1、处理Get请求
 67     app.Get("/userpath", func(context context.Context) {
 68         //获取Path
 69         path := context.Path()
 70         app.Logger().Info(path)
 71         //写入返回数据:string类型
 72         context.WriteString("请求路径:" + path)
 73     })
 74 
 75     //2.处理Get请求 并接受参数
 76     app.Get("/userinfo", func(context context.Context) {
 77         path := context.Path()
 78         app.Logger().Info(path)
 79         //获取get请求所携带的参数
 80         userName := context.URLParam("username") //
 81         app.Logger().Info(userName)
 82 
 83         pwd := context.URLParam("pwd")
 84         app.Logger().Info(pwd)
 85         //返回html数据格式
 86         context.HTML("<h1>" + userName + "," + pwd + "</h1>")
 87     })
 88 
 89     //3.处理Post请求 form表单的字段获取
 90     app.Post("/postLogin", func(context context.Context) {
 91         path := context.Path()
 92         app.Logger().Info(path)
 93         //context.PostValue方法来获取post请求所提交的for表单数据
 94         name := context.PostValue("name")
 95         pwd := context.PostValue("pwd")
 96         app.Logger().Info(name, "  ", pwd)
 97         context.HTML(name)
 98     })
 99 
100     //4、处理Post请求 Json格式数据
101     /**
102      * Postman工具选择[{"key":"Content-Type","value":"application/json","description":""}]
103      * 请求内容:{"name": "davie","age": 28}
104      */
105     app.Post("/postJson", func(context context.Context) {
106 
107         //1.path
108         path := context.Path()
109         app.Logger().Info("请求URL:", path)
110 
111         //2.Json数据解析
112         var person Person
113         //context.ReadJSON()
114         if err := context.ReadJSON(&person); err != nil {
115             panic(err.Error())
116         }
117 
118         //输出:Received: main.Person{Name:"davie", Age:28}
119         context.Writef("Received: %#+v
", person)
120     })
121 
122     //5.处理Post请求 Xml格式数据
123     /**
124      * 请求配置:Content-Type到application/xml(可选但最好设置)
125      * 请求内容:
126      *
127      *  <student>
128      *        <stu_name>davie</stu_name>
129      *        <stu_age>28</stu_age>
130      *    </student>
131      *
132      */
133 
134     app.Post("/postXml", func(context context.Context) {
135 
136         //1.Path
137         path := context.Path()
138         app.Logger().Info("请求URL:", path)
139 
140         //2.XML数据解析
141         var student Student
142         if err := context.ReadXML(&student); err != nil {
143             panic(err.Error())
144         }
145         //输出:
146         context.Writef("Received:%#+v
", student)
147     })
148 
149     //put请求
150     app.Put("/putinfo", func(context context.Context) {
151         path := context.Path()
152         app.Logger().Info("请求url:", path)
153     })
154 
155     //delete请求
156     app.Delete("/deleteuser", func(context context.Context) {
157         path := context.Path()
158         app.Logger().Info("Delete请求url:", path)
159     })
160 
161     app.Run(iris.Addr(":8000"), iris.WithoutServerError(iris.ErrServerClosed))
162 }
163 
164 //自定义的struct
165 type Person struct {
166     Name string `json:"name"`
167     Age  int    `json:"age"`
168 }
169 
170 //自定义的结构体
171 type Student struct {
172     //XMLName xml.Name `xml:"student"`
173     StuName string `xml:"stu_name"`
174     StuAge  int    `xml:"stu_age"`
175 }
176 
177 type config struct {
178     Addr       string `yaml:"addr"`
179     ServerName string `yaml:"serverName"`
180 }

 3. 请求数据格式返回

  1 package main
  2 
  3 import (
  4     "github.com/kataras/iris"
  5     "github.com/kataras/iris/context"
  6 )
  7 
  8 type Teacher struct {
  9     Name  string `json:"Name"`
 10     City  string `json:"City"`
 11     Other string `json:"Other"`
 12 }
 13 
 14 //程序主入口
 15 func main() {
 16 
 17     app := iris.New()
 18 
 19     /**
 20      * 通过Get请求
 21      * 返回 WriteString
 22      */
 23     app.Get("/getHello", func(context context.Context) {
 24         context.WriteString(" Hello world ")
 25     })
 26 
 27     /**
 28      * 通过Get请求
 29      * 返回 HTML数据
 30      */
 31     app.Get("/getHtml", func(context context.Context) {
 32         context.HTML("<h1> Davie, 12 </h1>")
 33     })
 34 
 35     /**
 36      * 通过Get请求
 37      * 返回 Json数据
 38      */
 39     app.Get("/getJson", func(context context.Context) {
 40         context.JSON(iris.Map{"message": "hello word", "requestCode": 200})
 41     })
 42 
 43     //POST
 44     app.Post("/user/postinfo", func(context context.Context) {
 45         //context.WriteString(" Post Request ")
 46         //user := context.Params().GetString("user")
 47 
 48         var tec Teacher
 49         err := context.ReadJSON(&tec)
 50         if err != nil {
 51             panic(err.Error())
 52         } else {
 53             app.Logger().Info(tec)
 54             context.WriteString(tec.Name)
 55         }
 56 
 57         //fmt.Println(user)
 58         //teacher := Teacher{}
 59         //err := context.ReadForm(&teacher)
 60         //if err != nil {
 61         //    panic(err.Error())
 62         //} else {
 63         //    context.WriteString(teacher.Name)
 64         //}
 65     })
 66 
 67     //PUT
 68     app.Put("/getHello", func(context context.Context) {
 69         context.WriteString(" Put Request ")
 70     })
 71 
 72     app.Delete("/DeleteHello", func(context context.Context) {
 73         context.WriteString(" Delete Request ")
 74     })
 75 
 76     //返回json数据
 77     app.Get("/getJson", func(context context.Context) {
 78         context.JSON(iris.Map{"message": "hello word", "requestCode": 200})
 79     })
 80 
 81     app.Get("/getStuJson", func(context context.Context) {
 82         context.JSON(Student{Name: "Davie", Age: 18})
 83     })
 84 
 85     //返回xml数据
 86     app.Get("/getXml", func(context context.Context) {
 87         context.XML(Person{Name: "Davie", Age: 18})
 88     })
 89 
 90     //返回Text
 91     app.Get("/helloText", func(context context.Context) {
 92         context.Text(" text hello world ")
 93     })
 94 
 95     app.Run(iris.Addr(":8000"), iris.WithoutServerError(iris.ErrServerClosed))
 96 
 97 }
 98 
 99 //json结构体
100 type Student struct {
101     Name string `json:"name"`
102     Age  int    `json:"age"`
103 }
104 
105 //xml结构体
106 type Person struct {
107     Name string `xml:"name"`
108     Age  int    `xml:"age"`
109 }

4. 路由功能处理方式

  1 package main
  2 
  3 import (
  4     "github.com/kataras/iris"
  5     "github.com/kataras/iris/context"
  6 )
  7 
  8 func main() {
  9 
 10     app := iris.New()
 11 
 12     /**
 13      * 1.handle方式处理请求
 14      */
 15     //GET: http://localhost:8002/userinfo
 16     app.Handle("GET", "/userinfo", func(context context.Context) {
 17         path := context.Path()
 18         app.Logger().Info(path)
 19         app.Logger().Error(" request path :", path)
 20     })
 21 
 22     //post
 23     app.Handle("POST", "/postcommit", func(context context.Context) {
 24         path := context.Path()
 25         app.Logger().Info(" post reuqest, the url is : ", path)
 26         context.HTML(path)
 27     })
 28 
 29     //      http://localhost:8002?date=20190310&city=beijing
 30     //GET: http://localhost:8002/weather/2019-03-10/beijing
 31     //      http://localhost:8002/weather/2019-03-11/beijing
 32     //      http://localhost:8002/weather/2019-03-11/tianjin
 33 
 34     app.Get("/weather/{date}/{city}", func(context context.Context) {
 35         path := context.Path()
 36         date := context.Params().Get("date")
 37         city := context.Params().Get("city")
 38         context.WriteString(path + "  , " + date + " , " + city)
 39     })
 40     
 41     /**
 42      * 1、Get 正则表达式 路由
 43      * 使用:context.Params().Get("name") 获取正则表达式变量
 44      *
 45      */
 46     // 请求1:/hello/1  /hello/2  /hello/3 /hello/10000
 47     //正则表达式:{name}
 48     app.Get("/hello/{name}", func(context context.Context) {
 49         //获取变量
 50         path := context.Path()
 51 
 52         app.Logger().Info(path)
 53         //获取正则表达式变量内容值
 54         name := context.Params().Get("name")
 55         context.HTML("<h1>" + name + "</h1>")
 56     })
 57 
 58     /**
 59      * 2、自定义正则表达式变量路由请求 {unit64:uint64}进行变量类型限制
 60      */
 61     // 123
 62     // davie
 63     app.Get("/api/users/{userid:uint64}", func(context context.Context) {
 64         userID, err := context.Params().GetUint("userid")
 65 
 66         if err != nil {
 67             //设置请求状态码,状态码可以自定义
 68             context.JSON(map[string]interface{}{
 69                 "requestcode": 201,
 70                 "message":     "bad request",
 71             })
 72             return
 73         }
 74 
 75         context.JSON(map[string]interface{}{
 76             "requestcode": 200,
 77             "user_id":     userID,
 78         })
 79     })
 80 
 81     //自定义正则表达式路由请求 bool
 82     app.Get("/api/users/{isLogin:bool}", func(context context.Context) {
 83         isLogin, err := context.Params().GetBool("isLogin")
 84         if err != nil {
 85             context.StatusCode(iris.StatusNonAuthoritativeInfo)
 86             return
 87         }
 88         if isLogin {
 89             context.WriteString(" 已登录 ")
 90         } else {
 91             context.WriteString(" 未登录 ")
 92         }
 93 
 94         //正则表达式所支持的数据类型
 95         context.Params()
 96     })
 97 
 98     app.Run(iris.Addr(":8002"), iris.WithoutServerError(iris.ErrServerClosed))
 99 
100 }

5. 路由组

 1 package main
 2 
 3 import (
 4     "github.com/kataras/iris"
 5     "github.com/kataras/iris/context"
 6 )
 7 
 8 func main() {
 9 
10     app := iris.New()
11 
12     //用户模块users
13     //  xxx/users/register 注册
14     //  xxx/users/login  登录
15     //  xxx/users/info   获取用户信息
16 
17     /**
18      * 路由组请求
19      */
20     userParty := app.Party("/users", func(context context.Context) {
21         // 处理下一级请求
22         context.Next()
23     })
24 
25     /**
26      * 路由组下面的下一级请求
27      * ../users/register
28      */
29     userParty.Get("/register", func(context context.Context) {
30         app.Logger().Info("用户注册功能")
31         context.HTML("<h1>用户注册功能</h1>")
32     })
33 
34     /**
35      * 路由组下面的下一级请求
36      * ../users/login
37      */
38     userParty.Get("/login", func(context context.Context) {
39         app.Logger().Info("用户登录功能")
40         context.HTML("<h1>用户登录功能</h1>")
41     })
42 
43     usersRouter := app.Party("/admin", userMiddleware)
44 
45     //Done:
46     usersRouter.Done(func(context context.Context) {
47 
48         context.Application().Logger().Infof("response sent to " + context.Path())
49     })
50 
51     usersRouter.Get("/info", func(context context.Context) {
52         context.HTML("<h1> 用户信息 </h1>")
53         context.Next()// 手动显示调用
54     })
55 
56     usersRouter.Get("/query", func(context context.Context) {
57         context.HTML("<h1> 查询信息 </h1>")
58     })
59 
60     app.Run(iris.Addr(":8003"), iris.WithoutServerError(iris.ErrServerClosed))
61 }
62 
63 //用户路由中间件
64 func userMiddleware(context iris.Context) {
65     context.Next()
66 }

6. Iris配置

 1 package main
 2 
 3 import (
 4     "github.com/kataras/iris"
 5     "os"
 6     "encoding/json"
 7     "fmt"
 8 )
 9 
10 /**
11  * Iris配置设置案例
12  */
13 func main() {
14 
15     //1.新建app实例
16     app := iris.New()
17 
18     //一、通过程序代码对应用进行全局配置
19     app.Configure(iris.WithConfiguration(iris.Configuration{
20         //如果设置为true,当人为中断程序执行时,则不会自动正常将服务器关闭。如果设置为true,需要自己自定义处理。
21         DisableInterruptHandler: false,
22         //该配置项表示更正并将请求的路径重定向到已注册的路径
23         //比如:如果请求/home/ 但找不到此Route的处理程序,然后路由器检查/home处理程序是否存在,如果是,(permant)将客户端重定向到正确的路径/home。
24         //默认为false
25         DisablePathCorrection: false,
26         //
27         EnablePathEscape:                  false,
28         FireMethodNotAllowed:              false,
29         DisableBodyConsumptionOnUnmarshal: false,
30         DisableAutoFireStatusCode:         false,
31         TimeFormat:                        "Mon,02 Jan 2006 15:04:05 GMT",
32         Charset:                           "utf-8",
33     }))
34 
35     //二、通过读取tml配置文件读取服务配置
36     //注意:要在run方法运行之前执行
37     app.Configure(iris.WithConfiguration(iris.TOML("/Users/hongweiyu/go/src/irisDemo/5-路由组及Iris配置/configs/iris.tml")))
38 
39     //三、通过读取yaml配置文件读取服务配置
40     //同样要在run方法运行之前执行
41     app.Configure(iris.WithConfiguration(iris.YAML("/Users/hongweiyu/go/src/irisDemo/5-路由组及Iris配置/configs/iris.yml")))
42 
43     //四、通过json配置文件进行应用配置
44     file, _ := os.Open("/Users/hongweiyu/go/src/irisDemo/5-路由组及Iris配置/config.json")
45     defer file.Close()
46     
47     decoder := json.NewDecoder(file)
48     conf := Coniguration{}
49     err := decoder.Decode(&conf)
50     if err != nil {
51         fmt.Println("Error:", err)
52     }
53     fmt.Println(conf.Port)
54 
55     //2.运行服务,端口监听
56     app.Run(iris.Addr(":8009"))
57 }
58 
59 type Coniguration struct {
60     AppName string `json:"appname"`
61     Port    int    `json:"port"`
62 }

config.json

{
  "appname": "IrisDemo",
  "port": 8000
}

iris.tml

DisablePathCorrection = false
EnablePathEscape = false
FireMethodNotAllowed = true
DisableBodyConsumptionOnUnmarshal = false
TimeFormat = "Mon, 01 Jan 2006 15:04:05 GMT"
Charset = "UTF-8"

[Other]
    MyServerName = "iris"

iris.yml

DisablePathCorrection: false
EnablePathEscape: false
FireMethodNotAllowed: true
DisableBodyConsumptionOnUnmarshal: true
TimeFormat: Mon, 01 Jan 2006 15:04:05 GMT
Charset: UTF-8

7. MVC包使用

 1 package main
 2 
 3 import (
 4     "github.com/kataras/iris"
 5     "github.com/kataras/iris/mvc"
 6 )
 7 
 8 func main() {
 9     app := iris.New()
10 
11     //mvc.Configure(app.Party("/user"), )
12     //设置自定义控制器
13     mvc.New(app).Handle(new(UserController))
14 
15     //路由组的mvc处理
16     mvc.Configure(app.Party("/user"), func(context *mvc.Application) {
17         context.Handle(new(UserController))
18     })
19 
20     app.Run(iris.Addr(":8009"))
21 }
22 
23 /**
24  * url:http://localhost:8009
25  * type:get
26  */
27 func (uc *UserController) Get() string {
28     iris.New().Logger().Info(" Get 请求 ")
29     return "hell world"
30 }
31 
32 /**
33  * url:http://localhost:8009
34  * type:post
35  */
36 func (uc *UserController) Post() {
37     iris.New().Logger().Info(" post 请求 ")
38 }
39 
40 func (uc *UserController) Put() {
41     iris.New().Logger().Info(" put 请求 ")
42 }
43 
44 /**
45  * url:http://localhost:8009/info
46  * type:get
47  */
48 func (uc *UserController) GetInfo() mvc.Result {
49     iris.New().Logger().Info(" get 请求, 请求路径为info ")
50     return mvc.Response{
51         Object: map[string]interface{}{
52             "code":     1,
53             "msessage": "请求成功",
54         },
55     }
56 }
57 
58 type UserController struct {
59 }
60 
61 func (uc *UserController) BeforeActivation(a mvc.BeforeActivation) {
62     a.Handle("GET", "/query", "UserInfo")
63 }
64 
65 /**
66  * url: http://localhost:8009/query
67  * type:get
68  */
69 func (uc *UserController) UserInfo() mvc.Result {
70     //todo
71     iris.New().Logger().Info(" user info query ")
72     return mvc.Response{}
73 }

 

8.Seesion的使用和控制

  1 package main
  2 
  3 import (
  4     "github.com/kataras/iris/sessions"
  5     "github.com/kataras/iris"
  6     "github.com/kataras/iris/context"
  7     "github.com/kataras/iris/sessions/sessiondb/boltdb"
  8 )
  9 
 10 var (
 11     USERNAME = "userName"
 12     ISLOGIN  = "isLogin"
 13 )
 14 
 15 /**
 16  * Session的使用和控制
 17  */
 18 func main() {
 19 
 20     app := iris.New()
 21 
 22     sessionID := "mySession"
 23 
 24     //1、创建session并进行使用
 25     sess := sessions.New(sessions.Config{
 26         Cookie: sessionID,
 27     })
 28 
 29     /**
 30      * 用户登录功能
 31      */
 32     app.Post("/login", func(context context.Context) {
 33         path := context.Path()
 34         app.Logger().Info(" 请求Path:", path)
 35         userName := context.PostValue("name")
 36         passwd := context.PostValue("pwd")
 37 
 38         if userName == "davie" && passwd == "pwd123" {
 39             session := sess.Start(context)
 40 
 41             //用户名
 42             session.Set(USERNAME, userName)
 43             //登录状态
 44             session.Set(ISLOGIN, true)
 45 
 46             context.WriteString("账户登录成功 ")
 47 
 48         } else {
 49             session := sess.Start(context)
 50             session.Set(ISLOGIN, false)
 51             context.WriteString("账户登录失败,请重新尝试")
 52         }
 53     })
 54 
 55     /**
 56      * 用户退出登录功能
 57      */
 58     app.Get("/logout", func(context context.Context) {
 59         path := context.Path()
 60         app.Logger().Info(" 退出登录 Path :", path)
 61         session := sess.Start(context)
 62         //删除session
 63         session.Delete(ISLOGIN)
 64         session.Delete(USERNAME)
 65         context.WriteString("退出登录成功")
 66     })
 67 
 68 
 69     app.Get("/query", func(context context.Context) {
 70         path := context.Path()
 71         app.Logger().Info(" 查询信息 path :", path)
 72         session := sess.Start(context)
 73 
 74         isLogin, err := session.GetBoolean(ISLOGIN)
 75         if err != nil {
 76             context.WriteString("账户未登录,请先登录 ")
 77             return
 78         }
 79 
 80         if isLogin {
 81             app.Logger().Info(" 账户已登录 ")
 82             context.WriteString("账户已登录")
 83         } else {
 84             app.Logger().Info(" 账户未登录 ")
 85             context.WriteString("账户未登录")
 86         }
 87 
 88     })
 89 
 90 
 91     //2、session和db绑定使用
 92     db, err := boltdb.New("sessions.db", 0600)
 93     if err != nil {
 94         panic(err.Error())
 95     }
 96 
 97     //程序中断时,将数据库关闭
 98     iris.RegisterOnInterrupt(func() {
 99         defer db.Close()
100     })
101 
102     //session和db绑定
103     sess.UseDatabase(db)
104 
105     app.Run(iris.Addr(":8009"), iris.WithoutServerError(iris.ErrServerClosed))
106 }

end