02.路由
  # 01.基本路由传参
# 1.1 基本路由
- gin 框架中采用的路由库是基于httprouter做的
 - 地址为:https://github.com/julienschmidt/httproute (opens new window)
 
package main
import (
    "net/http"
    "github.com/gin-gonic/gin"
)
func main() {
    r := gin.Default()
    r.GET("/", func(c *gin.Context) {
        c.String(http.StatusOK, "hello word")
    })
    r.POST("/xxxpost",getting)
    r.PUT("/xxxput")
    //监听端口默认为8080
    r.Run(":8000")
}
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 1.2 API参数
- 可以通过Context的Param方法来获取API参数
 - localhost:8000/xxx/zhangsan
 
package main
import (
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
)
func main() {
	r := gin.Default()
	r.GET("/user/:name/*action", func(c *gin.Context) {
		name := c.Param("name")
		action := c.Param("action")
		//截取/
		action = strings.Trim(action, "/")
		c.String(http.StatusOK, name+" blog: "+action)
	})
	//默认为监听8080端口
	r.Run(":8000")
}
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
- http://127.0.0.1:8000/user/tom/v5blog.com
 
# 1.3 URL参数
- URL参数可以通过DefaultQuery()或Query()方法获取
 - DefaultQuery()若参数不村则,返回默认值,Query()若不存在,返回空串
 - http://127.0.0.1:8080/user?name=zhangsan
 
package main
import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)
func main() {
	r := gin.Default()
	r.GET("/user", func(c *gin.Context) {
		//http://127.0.0.1:8080/user?name=zhangsan 才会打印出来默认的值
		name := c.DefaultQuery("name", "xxx")
		c.String(http.StatusOK, fmt.Sprintf("hello %s", name))
	})
	r.Run()
}
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 1.4 routes group
- routes group是为了管理一些相同的URL
 
package main
import (
   "github.com/gin-gonic/gin"
   "fmt"
)
// gin的helloWorld
func main() {
   // 1.创建路由
   // 默认使用了2个中间件Logger(), Recovery()
   r := gin.Default()
   // 路由组1 ,处理GET请求
   v1 := r.Group("/v1")
   // {} 是书写规范
   {
      v1.GET("/login", login)
      v1.GET("submit", submit)
   }
   v2 := r.Group("/v2")
   {
      v2.POST("/login", login)
      v2.POST("/submit", submit)
   }
   r.Run(":8000")
}
func login(c *gin.Context) {
   name := c.DefaultQuery("name", "jack")
   c.String(200, fmt.Sprintf("hello %s\n", name))
}
func submit(c *gin.Context) {
   name := c.DefaultQuery("name", "lily")
   c.String(200, fmt.Sprintf("hello %s\n", name))
}
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# 1.5 重定向
HTTP重定向
r.GET("/test", func(c *gin.Context) {
	c.Redirect(http.StatusMovedPermanently, "http://www.sogo.com/")
})
 1
2
3
2
3
路由重定向
r.GET("/test", func(c *gin.Context) {
    // 指定重定向的URL
    c.Request.URL.Path = "/test2"
    r.HandleContext(c)
})
r.GET("/test2", func(c *gin.Context) {
    c.JSON(http.StatusOK, gin.H{"hello": "world"})
})
 1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 02.路由拆分成单独文件或包
# 2.0 项目结构
- 把路由部分的代码单独拆分成包的话也是可以的,拆分后的目录结构如下
 - routers/routers.go需要注意此时SetupRouter需要改成首字母大写
 
gin_demo
├── main.go
└── routers
    └── routers.go
 1
2
3
4
2
3
4
# 2.1 main.go
package main
import (
	"fmt"
	"gin_test/routers"
)
func main() {
	r := routers.SetupRouter()
	if err := r.Run(); err != nil {
		fmt.Println("startup service failed, err:%v\n", err)
	}
}
 1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 2.2 routers/routers.go
package routers
import (
	"github.com/gin-gonic/gin"
	"net/http"
)
func helloHandler(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"message": "Hello v5blog.com",
	})
}
// SetupRouter 配置路由信息
func SetupRouter() *gin.Engine {
	r := gin.Default()
	r.GET("/", helloHandler)
	return r
}
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 03.路由拆分成多个文件
# 3.0 项目结构
当我们的业务规模继续膨胀,单独的一个routers文件或包已经满足不了我们的需求了
因为我们把所有的路由注册都写在一个SetupRouter函数中的话就会太复杂了。
我们可以分开定义多个路由文件
gin_demo
├── main.go
└── routers
    ├── blog.go
    └── shop.go
 1
2
3
4
5
2
3
4
5
# 3.1 main.go
func main() {
    r := gin.Default()
    routers.LoadBlog(r)
    routers.LoadShop(r)
    if err := r.Run(); err != nil {
        fmt.Println("startup service failed, err:%v\n", err)
    }
}
 1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 3.2 routers/blog.go
- routers/blog.go中添加一个LoadBlog的函数,将blog相关的路由注册到指定的路由器
 
package routers
import (
	"github.com/gin-gonic/gin"
	"net/http"
)
func LoadBlog(e *gin.Engine) {
	e.GET("/blog", blogHandler)
}
func blogHandler(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"message": "Blog Router",
	})
}
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 3.3 routers/shop.go
- routers/shop.go中添加一个LoadShop的函数,将shop相关的路由注册到指定的路由器
 
package routers
import (
	"github.com/gin-gonic/gin"
	"net/http"
)
func LoadShop(e *gin.Engine)  {
	e.GET("/shop", shopHandler)
}
func shopHandler(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"message": "Shop Router",
	})
}
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 04.路由拆分到不同的APP
# 4.0 项目结构
有时候项目规模实在太大,那么我们就更倾向于把业务拆分的更详细一些,例如把不同的业务代码拆分成不同的APP。
因此我们在项目目录下单独定义一个app目录,用来存放我们不同业务线的代码文件,这样就很容易进行横向扩展。
gin_demo
├── app
│   ├── blog
│   │   ├── handler.go
│   │   └── router.go
│   └── shop
│       ├── handler.go
│       └── router.go
├── main.go
└── routers
    └── routers.go
 1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 4.1 main.go
package main
import (
	"fmt"
	"gin_demo/app/blog"
	"gin_demo/app/shop"
	"gin_demo/routers"
)
func main() {
	// 加载多个APP的路由配置
	routers.Include(shop.Routers, blog.Routers)
	// 初始化路由
	r := routers.Init()
	if err := r.Run(); err != nil {
		fmt.Println("startup service failed, err:%v\n", err)
	}
}
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 4.2 routers/routers.go
package routers
import "github.com/gin-gonic/gin"
type Option func(*gin.Engine)
var options = []Option{}
// 注册app的路由配置
func Include(opts ...Option) {
	options = append(options, opts...)
}
// 初始化
func Init() *gin.Engine {
	r := gin.New()
	for _, opt := range options {
		opt(r)
	}
	return r
}
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 4.3 app/blog
app/blog/router.go
package blog
import (
	"github.com/gin-gonic/gin"
)
func Routers(e *gin.Engine) {
	e.GET("/blog", blogHandler)
}
 1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
app/blog/handler.go
package blog
import (
	"github.com/gin-gonic/gin"
	"net/http"
)
func blogHandler(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"message": "Blog Router",
	})
}
 1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 4.4 app/blog
app/shop/router.go
package shop
import (
	"github.com/gin-gonic/gin"
)
func Routers(e *gin.Engine) {
	e.GET("/shop", shopHandler)
}
 1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
app/shop/handler.go
package shop
import (
	"github.com/gin-gonic/gin"
	"net/http"
)
func shopHandler(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"message": "Shop Router",
	})
}
 1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
上次更新: 2024/3/13 15:35:10