下面是一个简单的使用Gin框架的demo:
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
router := gin.Default()
router.GET("/", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "Hello Gin!",
})
})
router.GET("/hello/:name", func(c *gin.Context) {
name := c.Param("name")
c.String(http.StatusOK, "Hello %s!", name)
})
router.POST("/login", func(c *gin.Context) {
username := c.PostForm("username")
password := c.PostForm("password")
c.JSON(http.StatusOK, gin.H{
"username": username,
"password": password,
})
})
router.Run(":8080")
}
上面代码中,我们首先引入了gin包,并创建了一个默认的router。在router中,我们定义了三个路由:
/:返回一条简单的json消息;/hello/:name:返回带有参数的字符串;/login:接收POST请求并返回接收到的表单数据。
最后我们通过调用Run()方法启动服务器,监听8080端口。




