iris搭建api框架记录-01搭建环境
本系列文章是使用iris搭建一个类似laravel的框架,对一部分代码进行封装,达到提高开发速度的目的。
参考https://learnku.com/courses/go-api/1.17/ 流程。用于到达学习框架的目的。
环境准备:
github账号,新建一个repository,我起名为airis
创建好后,映射到本地。
在本地新建一个文件夹airis
go mod init airis
go get github.com /kataras/iris/v12 @master
参照官方文档样例,新建main.go
package main import "github.com/kataras/iris/v12" func main() { app := iris.New() booksAPI := app.Party( "/books" ) { booksAPI.Use(iris.Compression) // GET: http://localhost:8080/books booksAPI.Get( "/" , list) // POST: http://localhost:8080/books booksAPI.Post( "/" , create) } app.Listen( ":8080" ) } // Book example. type Book struct { Title string `json: "title" ` } func list(ctx iris.Context) { books := []Book{ { "Mastering Concurrency in Go" }, { "Go Design Patterns" }, { "Black Hat Go" }, } ctx.JSON(books) // TIP: negotiate the response between server's prioritizes // and client's requirements, instead of ctx.JSON: // ctx.Negotiation().JSON().MsgPack().Protobuf() // ctx.Negotiate(books) } func create(ctx iris.Context) { var b Book err := ctx.ReadJSON(&b) // TIP: use ctx.ReadBody(&b) to bind // any type of incoming data instead. if err != nil { ctx.StopWithProblem(iris.StatusBadRequest, iris.NewProblem(). Title( "Book creation failure" ).DetailErr(err)) // TIP: use ctx.StopWithError(code, err) when only // plain text responses are expected on errors. return } println( "Received Book: " + b.Title) ctx.StatusCode(iris.StatusCreated) }
运行main.go
go run main.go
命令行显示如下,说明启动成功:
使用浏览器访问
http://127.0.0.1:8080/books
正常返回。
文字均为博主原创,转载请联系博主,谢谢!