go语言学习005——iris框架学习

1、安装

go get -u github.com/kataras/iris

然后在gopath目录下,新建first_iris文件夹
新建文件main.go

package main

import (
	"github.com/kataras/iris/v12"

	"github.com/kataras/iris/v12/middleware/logger"
	"github.com/kataras/iris/v12/middleware/recover"
)

func main() {
	app := iris.New()
	app.Logger().SetLevel("debug")
	app.Use(recover.New())
	app.Use(logger.New())
	app.Get("/", func(ctx iris.Context) {
		ctx.HTML("Hello")
	})

	app.Run(iris.Addr(":8080"), iris.WithoutServerError(iris.ErrServerClosed))
}

之后go rum main.go
再浏览器localhost:8080访问

2、iris中的http8种请求

2.1、直接处理请求

package main

import (
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/context"
)

func main() {

	app := iris.New()
	//app.Get();  // 可以直接点出来8种获取网络资源的方法,
	//app.Put();

	app.Get("/getRequest", func(context context.Context) {
		// 处理get请求,请求的url为:/getRequest
		path := context.Path()
		app.Logger().Info(path)
	})

	// 1、处理Get请求
	app.Get("/userpath", func(context context.Context) {
		path := context.Path()
		app.Logger().Info(path)

		context.WriteString("请求路径 + " + path)
	})

	// 2、处理Get请求,并接受参数
	app.Get("/userinfo", func(context context.Context) {
		path := context.Path()
		app.Logger().Info(path)

		// 获取get请求携带的参数
		userName := context.URLParam("username")
		app.Logger().Info(userName)

		pwd := context.URLParam("pwd")
		app.Logger().Info(pwd)

		// 返回html格式
		context.HTML("<h1>" + userName + "," + pwd + "</h1>")
	})

	// 2.2、返回json格式的数据
	app.Get("/getJson", func(context context.Context) {
		context.JSON(iris.Map{"message": "hello world", "requestCode": 200})
	})

	// 3、处理Post请求,form表单的字段获取
	app.Post("/postLogin", func(context context.Context) {
		path := context.Path()
		app.Logger().Info(path)

		// 使用context.PostValue来获取post请求所提交的form表单数据
		name := context.PostValue("name")
		pwd := context.PostValue("pwd")
		app.Logger().Info(name, " ", pwd)
		context.HTML(name)
	})

	// 4、处理json格式的post请求
	// postman的请求信息:{"name":"davie","age": 28}
	app.Post("/postJson", func(context context.Context) {
		// 1、Path
		path := context.Path()
		app.Logger().Info("请求URL: ", path)

		// 2. Json解析
		var person Person
		if err := context.ReadJSON(&person); err != nil {
			panic(err.Error())
		}
		context.Writef("Received : %#+v\n", person)
	})

	// 5、处理post请求 xml格式
	// postman的请求信息:{"name":"davie","age": 28}
	app.Post("/postXml", func(context context.Context) {

		//1.Path
		path := context.Path()
		app.Logger().Info("请求URL:", path)

		//2.XML数据解析
		var student Student
		if err := context.ReadXML(&student); err != nil {
			panic(err.Error())
		}
		//输出:
		context.Writef("Received:%#+v\n", student)
	})

	app.Run(iris.Addr(":8000"), iris.WithoutServerError(iris.ErrServerClosed))

}

type Person struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

//自定义的结构体
type Student struct {
	//XMLName xml.Name `xml:"student"`
	StuName string `xml:"stu_name"`
	StuAge  int    `xml:"stu_age"`
}

2.2、使用通用的handle方法自定义

编写自己的请求处理类型以及对应的方法
和正则表达式

package main

import (
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/context"
)

func main() {
	app := iris.New()

	// 第二种统一使用handle处理方式
	app.Handle("GET", "/userinfo", func(context context.Context) {
		path := context.Path()
		app.Logger().Info(path)
		app.Logger().Error("requext is: ", path)

		context.Writef("写回去")
	})

	app.Handle("POST", "/postcommit", func(context context.Context) {
		path := context.Path()
		app.Logger().Info("post request ,the url is :", path)
	})

	// 正则表达式,带参数的
	app.Get("/weather/{date}/{city}", func(context context.Context) {
		path := context.Path()
		date := context.Params().Get("date") // 获取自定义的变量
		city := context.Params().Get("city")
		context.WriteString(path + " , " + date + " , " + city)
	})

	// 正则表达式,带参数,且带参数的数据类型的
	app.Get("/api/users/{isLogin:bool}", func(context context.Context) {
		path := context.Path()
		isLogin, err := context.Params().GetBool("isLogin")
		if err != nil {
			context.StatusCode(iris.StatusNonAuthoritativeInfo)
		}
		if isLogin {
			context.WriteString("已登录")
		} else {
			context.WriteString("未登录")
		}
		context.Writef(path)
		//context.Params().Get  之后提示的信息,就是可以获取的数据类型
	})

	app.Run(iris.Addr(":8800"), iris.WithoutServerError(iris.ErrServerClosed))

}

2.3、用户组

先进入,user,
之后在选择登陆,还是而做其他的,
服务器端代码是前缀匹配,如果遇到了user,就跳转到user的组中,再接着做其他的相关的事情。

	//app := iris.New()
		//userParty
		//userparty := user.Party() 用户组
		//users.Done(func(){})   执行完用户组之后,需要调用一下这个方法

2.4、配置信息

func main() {
	app := iris.New()

	// 1、代码直接配置
	app.Configure(iris.WithConfiguration(iris.Configuration{
		DisableInterruptHandle: false,
		EnablePathEscape: false,
		TimeRormat: "Mon,02 Jan 2006 15:04:05 GMT",
	}))

	// 2、读取tml配置文件读取服务的配置
	app.Configure(iris.WithConfiguration(iris.YAML("/Users/hongweiyu/go/src/irisDemo/004_handle_method/configs/iris.tml")))

	// 3、通过读取yaml配置文件
	app.Configure(iris.WithConfiguration(iris.YAML("("/Users/hongweiyu/go/src/irisDemo/004_handle_method/configs/iris.yml")))

	// 4、通过json配置文件
	file ,_ := os.Open("/User/hongweiyu/go/src/irisDemo/004_handle_method/config.json")
	defer file.Close()

	decoder := json.NewDecoder(file)
	conf := Coniguration{}
	err := decoder.Decode(&conf)
	fi err != nil {
		fmt.Println("error:",err)
	}
	fmt.Println(conf.Port)



type Coniguration struct {
	AppName string 'json:"appname'
	Port int 'json:"port'
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值