案例 https://github.com/gin-gonic/gin
https://studygolang.com/articles/21883
启动
新建一个 main.go 文件。
package mainimport ("github.com/gin-gonic/gin")func main() {router := gin.Default()router.Run()}
Gin 只需要两行代码就可以把我们的服务跑起来。
我们只要点击运行,项目便会启动一个 8080 端口,打开浏览器 localhost:8080 我们便可以看到页面上提示出 404 page not found ,这是因为我们的根路由上并没有返回任何结果。同时我们可以在控制台上看到一些打印信息,其中就包括我们刚刚访问根路由的端口。
添加1个路由
package mainimport "github.com/gin-gonic/gin"func main() {r := gin.Default()r.GET("/ping", func(c *gin.Context) {c.JSON(200, gin.H{"message": "pong",})})r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")}
浏览器输入
http://127.0.0.1:8080/ping
输出
{"message":"pong"}
单元测试
建立 test 目录, golang 的单元测试都是以 _test 结尾,建立 index_test.go 文件。
package testimport ("GinHello/initRouter""github.com/stretchr/testify/assert""net/http""net/http/httptest""testing")func TestIndexGetRouter(t *testing.T) {router := initRouter.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())}
