本文共 2537 字,大约阅读时间需要 8 分钟。
原文来自
Gin(一):Hello | ISLANDyoungxhui.topGi什么是 Gin
Gin 是一个用 Golang 写的 http web 框架。
这是来自 Gin Github 上的描述。
开发环境
- GoLand 2019.2 EAP
- GoLang 1.11.5
- 采用 Go Modules 进行管理
快速入门
用 GoLand 新建项目的时候,我们选择 Go Modules(vgo) ,选择我们的项目地址和项目名称,我们命名为 GinHello。
点击 create ,此时Goland 为我们生成了项目目录,Go项目的目录永远是那么的简单,比 Java 的 Maven 或者 Gradle 生成的项目目录简单多了。
GinHello||-go.mod
对,就是一个文件。一个 Go module 文件。go mod 是 Go 官方引入的一个依赖管理工具。
添加依赖
通过 go mod 文件进行依赖的。
require github.com/gin-gonic/gin v1.4.0
我们把上面的依赖进行添加到 go module
中, goLand 会自动帮我们进行依赖的下载和管理。
Hello Gin
当完成依赖的添加,就可以开始写代码了。
新建一个 main.go
文件。
package mainimport ( "github.com/gin-gonic/gin")func main() { r := gin.Default() r.Run()}
Gin
只需要两行代码就可以把我们的服务跑起来。
我们只要点击运行,项目便会启动一个 8080
端口,打开浏览器 localhost:8080
我们便可以看到页面上提示出 404 page not found
,这是因为我们的根路由上并没有返回任何结果。同时我们可以在控制台上看到一些打印信息,其中就包括我们刚刚访问根路由的端口。
产生接口
项目已经启动了,那么如何返回一个接口呢?
通过 router
的 Handle
进行配置我们返回的参数。
// 省略代码 // 添加 Get 请求路由 r.GET("/", func(context *gin.Context) { context.String(http.StatusOK, "hello gin") }) // 省略代码
此时我们重启项目,重新访问页面 localhost:808
,此刻的页面上已经显示了 hello gin
。
同样,我们还可以进行 POST
,PUT
,DELETE
等请求方式。
单元测试
单元测试是项目不能缺少的模块,也是保障项目可以正常运行的重要依赖。下面就对 Gin 进行单元测试。
为了方便单元测试,我们首先要对我们的项目进行一下抽取。
新建立一个文件夹叫做 init-router
建立 go 文件 initRouter
package init_routerimport ( "github.com/gin-gonic/gin" "net/http")func SetupRouter() *gin.Engine { router := gin.Default() // 添加 Get 请求路由 router.GET("/", func(context *gin.Context) { context.String(http.StatusOK, "hello gin") }) return router}
main.go
package mainimport ( initRouter "GinHello/init-router")func main() { router := initRouter.SetupRouter() _ = router.Run()}
完成了项目测试的初步建立。
建立test目录,golang 的单元测试都是以_test结尾,建立index_test.go文件。
package index__testimport ( init_router "GinHello/init-router" "github.com/stretchr/testify/assert" "net/http" "net/http/httptest" "testing")func TestIndexGetRouter(t *testing.T) { router := init_router.SetupRouter() w := httptest.NewRecorder() req, _ := http.NewRequest(http.MethodGet, "/", nil) router.ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "hello gin", w.Body.String())}
通过assert进行断言,来判断返回状态码和返回值是否与代码中的值一致。
此时的项目目录为:
GinHello||-init-router| |-initRouter.go||-test| |-index_test.go||-main.go|-go.mod|-go.sum
运行单元测试,控制台打印出单元测试结果。
[GIN-debug] GET / –> GinHello/init-router.SetupRouter.func1 (3 handlers) [GIN] 2019/07/12 - 18:48:37 | 200 | 0s | | GET / — PASS: TestIndexGetRouter (0.02s) PASS
总结
通过简单的搭建一个Gin项目,可以看到Go语言搭建一个Http服务器很简单,也很方便,零配置即可完成项目并运行起来。
项目代码示例
youngxhui/GinHellogithub.com历史文章
Gin(二):路由Router | ISLANDyoungxhui.top转载地址:https://blog.csdn.net/weixin_34245171/article/details/112101011 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!