Golang框架-Iris框架使用(一)——基本使用

1. Iris框架

1.1 Golang框架

  Golang常用框架有:GinIrisBeegoBuffaloEchoRevel,其中Gin、Beego和Iris较为流行。Iris是目前流行Golang框架中唯一提供MVC支持(实际上Iris使用MVC性能会略有下降)的框架,并且支持依赖注入,使用入门简单,能够快速构建Web后端,也是目前几个框架中发展最快的,从2016年截止至目前总共有17.4k stars(Gin 35K stars)。

Iris is a fast, simple yet fully featured and very efficient web framework for Go. It provides a beautifully expressive and easy to use foundation for your next website or API.

star chart

1.2 安装Iris

Iris官网:https://iris-go.com/
Iris Github:https://github.com/kataras/iris

# go get -u -v 获取包
go get github.com/kataras/iris/v12@latest
# 可能提示@latest是错误,如果版本大于11,可以使用下面打开GO111MODULE选项
# 使用完最好关闭,否则编译可能出错
go env -w GO111MODULE=on
# go get失败可以更改代理
go env -w GOPROXY=https://goproxy.cn,direct

2. 使用Iris构建服务端

2.1 简单例子1——直接返回消息

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")
	// 设置recover从panics恢复,设置log记录
	app.Use(recover.New())
	app.Use(logger.New())

	app.Handle("GET", "/", func(ctx iris.Context) {
		ctx.HTML("<h1>Hello Iris!</h1>")
		
	})
	app.Handle("GET", "/getjson", func(ctx iris.Context) {
		ctx.JSON(iris.Map{"message": "your msg"})
	})
	
	app.Run(iris.Addr("localhost:8080"))
}

其他便捷设置方法:

// 默认设置日志和panic处理
app := iris.Default()

我们可以看到iris.Default()的源码:

// 注:默认设置"./view"为html view engine目录
func Default() *Application {
	app := New()
	app.Use(recover.New())
	app.Use(requestLogger.New())
	app.defaultMode = true
	return app
}

2.2 简单例子2——使用HTML模板

package main

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

func main() {
	app := iris.New()
	// 注册模板在work目录的views文件夹
	app.RegisterView(iris.HTML("./views", ".html"))
	
	app.Get("/", func(ctx iris.Context) {
		// 设置模板中"message"的参数值
		ctx.ViewData("message", "Hello world!")
		// 加载模板
		ctx.View("hello.html")
	})
	
	app.Run(iris.Addr("localhost:8080"))
}

上述例子使用的hello.html模板

<html>
<head>
	<title>Hello Page</title>
</head>
<body>
	<h1>{{ .message }}</h1>
</body>
</html>

2.3 路由处理

上述例子中路由处理,可以使用下面简单替换,分别针对HTTP中的各种方法

app.Get("/someGet", getting)
app.Post("/somePost", posting)
app.Put("/somePut", putting)
app.Delete("/someDelete", deleting)
app.Patch("/somePatch", patching)
app.Head("/someHead", head)
app.Options("/someOptions", options)

例如,使用路由“/hello”的Get路径

app.Get("/hello", handlerHello)

func handlerHello(ctx iris.Context) {
	ctx.WriteString("Hello")
}

// 等价于下面
app.Get("/hello", func(ctx iris.Context) {
		ctx.WriteString("Hello")
	})

2.4 使用中间件

app.Use(myMiddleware)

func myMiddleware(ctx iris.Context) {
	ctx.Application().Logger().Infof("Runs before %s", ctx.Path())
	ctx.Next()
}

2.5 使用文件记录日志

  1. 整个Application使用文件记录
// 获取当前时间
now := time.Now().Format("20060102") + ".log"
// 打开文件,如果不存在创建,如果存在追加文件尾,权限为:拥有者可读可写
file, err := os.OpenFile(now, os.O_CREATE | os.O_APPEND, 0600)
defer file.Close()
if err != nil {
	app.Logger().Errorf("Log file not found")
}
// 设置日志输出为文件
app.Logger().SetOutput(file)
  1. 上述记录日志到文件可以和中间件结合,以控制不必要的调试信息记录到文件
func myMiddleware(ctx iris.Context) {
	now := time.Now().Format("20060102") + ".log"
	file, err := os.OpenFile(now, os.O_CREATE | os.O_APPEND, 0600)
	defer file.Close()
	if err != nil {
		ctx.Application().Logger().SetOutput(file).Errorf("Log file not found")
		os.Exit(-1)
	}
	ctx.Application().Logger().SetOutput(file).Infof("Runs before %s", ctx.Path())
	ctx.Next()
}
  1. 上述方法只能打印Statuscode为200的路由请求,如果想要打印其他状态码请求,需要另使用
app.OnErrorCode(iris.StatusNotFound, func(ctx iris.Context) {
	now := time.Now().Format("20060102") + ".log"
	file, err := os.OpenFile(now, os.O_CREATE | os.O_APPEND, 0600)
	defer file.Close()
	if err != nil {
		ctx.Application().Logger().SetOutput(file).Errorf("Log file not found")
		os.Exit(-1)
	}
	ctx.Application().Logger().SetOutput(file).Infof("404")
	ctx.WriteString("404 not found")
})

2.6 参数设置

  Iris有十分强大的路由处理程序,你能够按照十分灵活的语法设置路由路径,并且如果没有涉及正则表达式,Iris会计算其需求预先编译索引,用十分小的性能消耗来完成路由处理。

注:ctx.Params()和ctx.Values()是不同的,下面是官网给出的解释:

  1. Path parameter’s values can be retrieved from ctx.Params()
  2. Context’s local storage that can be used to communicate between handlers and middleware(s) can be stored to ctx.Values() .

Iris可以使用的参数类型

Param TypeGo TypeValidationRetrieve Helper
:stringstringanything (single path segment)Params().Get
:intint-9223372036854775808 to 9223372036854775807 (x64) or -2147483648 to 2147483647 (x32), depends on the host archParams().GetInt
:int8int8-128 to 127Params().GetInt8
:int16int16-32768 to 32767Params().GetInt16
:int32int32-2147483648 to 2147483647Params().GetInt32
:int64int64-9223372036854775808 to 92233720368?4775807Params().GetInt64
:uintuint0 to 18446744073709551615 (x64) or 0 to 4294967295 (x32), depends on the host archParams().GetUint
:uint8uint80 to 255Params().GetUint8
:uint16uint160 to 65535Params().GetUint16
:uint32uint320 to 4294967295Params().GetUint32
:uint64uint640 to 18446744073709551615Params().GetUint64
:boolbool“1” or “t” or “T” or “TRUE” or “true” or “True” or “0” or “f” or “F” or “FALSE” or “false” or “False”Params().GetBool
:alphabeticalstringlowercase or uppercase lettersParams().Get
:filestringlowercase or uppercase letters, numbers, underscore (_), dash (-), point (.) and no spaces or other special characters that are not valid for filenamesParams().Get
:pathstringanything, can be separated by slashes (path segments) but should be the last part of the route pathParams().Get
  1. 在路径中使用参数
app.Get("/users/{id:uint64}", func(ctx iris.Context){
	id := ctx.Params().GetUint64Default("id", 0)
})
  1. 使用post传递参数
app.Post("/login", func(ctx iris.Context) {
		username := ctx.FormValue("username")
		password := ctx.FormValue("password")
		ctx.JSON(iris.Map{
			"Username": username,
			"Password": password,
		})
	})

  以上就是Iris的基本入门使用,当然还有更多其他操作:中间件使用、正则表达式路由路径的使用、Cache、Cookie、Session、File Server、依赖注入、MVC等的用法,可以参照官方教程使用,后期有时间会写文章总结。

  • 5
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我知道你的问题了。首先,使用beego框架和go-socket.io搭建聊天室需要以下步骤: 1. 安装beego和go-socket.io ```shell go get github.com/astaxie/beego go get github.com/googollee/go-socket.io ``` 2. 创建beego项目 ```shell bee new chatroom cd chatroom ``` 3. 在main.go中引入go-socket.io的包并创建socket.io服务器 ```go package main import ( "github.com/astaxie/beego" "github.com/googollee/go-socket.io" ) func main() { server, err := socketio.NewServer(nil) if err != nil { beego.Error("Socket.IO server creation failed: ", err) return } // TODO: 后续代码 } ``` 4. 添加路由 ```go server.On("connection", func(so socketio.Socket) { beego.Info("New user connected.") // 处理用户连接事件 so.On("chat", func(msg string) { beego.Info("Message received: ", msg) // TODO: 处理消息 }) // 处理用户断开连接事件 so.On("disconnection", func() { beego.Info("User disconnected.") }) }) // 处理根路由 beego.Router("/", &controllers.MainController{}) // 处理socket.io路由 beego.Handler("/socket.io/", server) beego.Handler("/socket.io.js", http.FileServer(http.Dir("./node_modules/socket.io-client/dist/")).ServeHTTP) ``` 5. 在前端页面上添加socket.io客户端代码 ```html <script src="/socket.io.js"></script> <script> var socket = io.connect('http://localhost:8080'); socket.on('connect', function () { console.log('Connected to server.'); }); socket.on('chat', function (message) { console.log('Message received: ' + message); }); socket.on('disconnect', function () { console.log('Disconnected from server.'); }); </script> ``` 6. 处理聊天消息 ```go server.On("connection", func(so socketio.Socket) { beego.Info("New user connected.") // 处理用户连接事件 so.On("chat", func(msg string) { beego.Info("Message received: ", msg) // 广播消息给所有用户 server.BroadcastToAll("chat", msg) }) // 处理用户断开连接事件 so.On("disconnection", func() { beego.Info("User disconnected.") }) }) ``` 这样,你就可以使用beego框架和go-socket.io搭建一个简单的聊天室了。当然,以上代码只是一个简单的示例,你可以根据具体需求进行修改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值