编程开源技术交流,分享技术与知识

网站首页 > 开源技术 正文

Go Web 框架 Gin 学习1 - 介绍与安装

wxchong 2024-07-25 13:32:55 开源技术 17 ℃ 0 评论

介绍

Gin是一个用Go语言编写的web框架。

安装

1、下载Gin

$ go get github.com/gin-gonic/gin

第一个web应用

2、代码逐行解析

package main

import (
   "github.com/gin-gonic/gin" //导包
   "net/http"
)

func main() {
   app := gin.Default()
   //func Default() *Engine
   //Default返回一个已经附加了Logger和Recovery中间件的Engine实例。
   app.GET("/", index)
   //func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes
   //app.GET("/",index)是app.Handle("GET","/",index)简写。
   //通过路径relativePath("/")访问,处理请求的方法是最后1个handler(index),其中在index前可以有更多的handler,处理最后1个作为处理程序,其他的部分为中间件。
   //对于GET、POST、PUT、PATCH和DELETE请求,可以使用各自的快捷功能(app.GET、app.POST、app.PUT、app.PATCH、app.DELETE)
   _ = app.Run("127.0.0.1:80")
   // func (engine *Engine) Run(addr ...string) (err error)
   // Run attaches the router to a http.Server and starts listening and serving HTTP requests. It is a shortcut for http.ListenAndServe(addr, router) Note: this method will block the calling goroutine indefinitely unless an error happens.
   // 通过Run方法启用http.Server路由,并开始侦听和服务HTTP请求。
   // 它是http的快捷方式。也可以写成 http.ListenAndServe("127.0.0.1:80", app)
   // 注意:使用Run方法后,程序将阻塞调用goroutine。
   //_ = http.ListenAndServe("127.0.0.1:80", app)
}

func index(c *gin.Context) {
   c.String(http.StatusOK, "golang从入门到精通")
   //func (c *Context) String(code int, format string, values ...interface{})
   // 响应内容为字符串,其中http.StatusOK是常量,常量值为200,因此也可以写成c.String(200, "golang从入门到精通")
}

去除逐行解释,截图如下:

运行如下:

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表