Golang的Gin框架与Django的路由器类似吗?

huangapple go评论84阅读模式
英文:

golang gin: router like django?

问题

gin能像django一样描述路由吗?

在所有的例子中,路由器都在一个地方,从未涉及附件。

我想在包中描述路由,然后在主文件中只需简单地写一些东西,例如:

r := gin.New()
r.Include("/main", here_imported_route.Route)

here_imported_route.go

package here_imported_route

Router := gin.New()
Router.Use(midl())
Router.Get("/test", hello)

然后在"/main/test"上我们得到"hello"。

英文:

Can gin describe route like django?

In all examples, the routers are in one place, never found about attachment.

I would like to describe the routes in the package, and in the main file is simply to write something like.
example:

r := gin.New()
r.Include("/main", here_imported_route.Route)

#here_imported_route.go

package here_imported_route

Router := gin.New()
Router.Use(midl())
Router.Get("/test", hello)

and then on "/main/test" we get "hello".
1: https://github.com/gin-gonic/gin

答案1

得分: 2

在主路由中,像这样:

package main

import (
  "path_to_pkg/pkg"

  "github.com/gin-gonic/gin"
)

var r *gin.Engine

func init() {
  r = gin.New()
  pkg.Concon(r.Group("/pkg"))

}

func main() {
  r.Run(":8080")
}

在导入的包中创建连接函数:

pkg.go

package pkg

import "github.com/gin-gonic/gin"

func Concon(g *gin.RouterGroup) {
  g.GET("/ping", func(c *gin.Context) {
    c.String(200, "pong")
  })
}

打开 127.0.0.1:8080/pkg/ping 并获取 "pong"。

英文:

in main route like here

package main

import (
  "path_to_pkg/pkg"

  "github.com/gin-gonic/gin"
)

var r *gin.Engine

func init() {
  r = gin.New()
  pkg.Concon(r.Group("/pkg"))

}

func main() {
  r.Run(":8080")
}

in imported package create concatenation func

pkg.go

package pkg

import "github.com/gin-gonic/gin"

func Concon(g *gin.RouterGroup) {
  g.GET("/ping", func(c *gin.Context) {
    c.String(200, "pong")
  })
}

open 127.0.0.1:8080/pkg/ping and get "pong"

答案2

得分: 1

如果我正确理解你的问题,我认为你可以通过路由分组来实现这个目标。你可以像这样设置:

r := gin.New()
main := r.Group("/main")
{
  main.GET("/test", hello)
}

在这里可以查看更多详细信息:链接

英文:

If I understand your question correctly, I think you can accomplish this with route grouping. So you would have something like this:

r := gin.New()
main := r.Group("/main")
{
  main.GET("/test", hello)
}

See more details here.

huangapple
  • 本文由 发表于 2015年10月3日 20:30:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/32922581.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定