Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/iron-buster/gin-learn
学习一下Go的web框架gin。
https://github.com/iron-buster/gin-learn
Last synced: 3 days ago
JSON representation
学习一下Go的web框架gin。
- Host: GitHub
- URL: https://github.com/iron-buster/gin-learn
- Owner: Iron-Buster
- Created: 2024-09-13T07:15:30.000Z (2 months ago)
- Default Branch: main
- Last Pushed: 2024-09-14T01:51:32.000Z (2 months ago)
- Last Synced: 2024-09-14T20:43:39.277Z (2 months ago)
- Language: Go
- Size: 11.7 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Gin-Learn
学习一下Go的web框架gin。## Gin Install
> go get -u -v github.com/gin-gonic/gin**simple code**
```go
package mainimport "github.com/gin-gonic/gin"
func main() {
r := gin.Default()
r.GET("/", func(c *gin.Context) {
c.String(200, "Hello, Gin")
})
r.Run()
}
```## Route
- 解析路径参数
```go
r.GET("/user/:name", func(c *gin.Context) {
name := c.Param("name")
c.String(http.StatusOK, "Hello %s", name)
})
```
- 获取Query参数
```go
r.GET("/users", func(c *gin.Context) {
name := c.Query("name")
role := c.DefaultQuery("role", "teacher") // 获取不到就取默认值
c.String(http.StatusOK, "%s is a %s", name, role)
})
```
- 获取Post参数
```go
r.POST("/form", func(c *gin.Context) {
username := c.PostForm("username")
password := c.DefaultPostForm("password", "888888")c.JSON(http.StatusOK, gin.H{
"username": username,
"password": password,
})
})
```
- Get和Post混合
```go
r.POST("/posts", func(c *gin.Context) {
id := c.Query("id")
page := c.DefaultQuery("page", "0")
username := c.PostForm("username")
password := c.DefaultPostForm("password", "000000")c.JSON(http.StatusOK, gin.H{
"id": id,
"page": page,
"username": username,
"password": password,
})
})
```
- Map参数
```go
r.POST("/post", func(c *gin.Context) {
ids := c.QueryMap("ids")
names := c.PostFormMap("names")c.JSON(http.StatusOK, gin.H{
"ids": ids,
"names": names,
})
})
```
- Redirect 重定向
```go
r.GET("/redirect", func(c *gin.Context) {
c.Redirect(http.StatusMovedPermanently, "/index")
})
r.GET("/goindex", func(c *gin.Context) {
c.Request.URL.Path = "/"
r.HandleContext(c)
})
```
- 分组路由
```go
// 分组路由
// 对于一些公共前缀的路由,可以使用分组路由,类似Java里Controller类上加的一个@RequestMapping("/api/")的东西吧defaultHandler := func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"path": c.FullPath(),
})
}
// group: v1
v1 := r.Group("/v1")
{
v1.GET("/posts", defaultHandler)
v1.GET("/series", defaultHandler)
}
// group: v2
v2 := r.Group("/v2")
{
v2.GET("/posts", defaultHandler)
v2.POST("/series", defaultHandler)
}
```