To undertake: Gin frame package own routing ②
For a project, the need to separate the various functional modules, so-called three-tier model, introduce personal approach here:
contorller responsible for routing
Data model is mainly responsible for program input and output
service is mainly responsible for data processing
Utils common method is mainly responsible for storage, such as a database connection
code show as below:
project->index.go
package main import ( c "project/controller" "github.com/gin-gonic/gin" ) func main() { r := gin.Default() rr := c.GinRouter(r) // listening and start the service on 0.0.0.0:8080 rr.Run ( " : 8080 " ) }
project->controller->index.go
package controller import ( "fmt" "project/controller/second" "github.com/gin-gonic/gin" ) func GinRouter(r *gin.Engine) *gin.Engine { rr := r.Group("/") rr.GET("/first", func(c *gin.Context) { fmt.Println("first .........") }) rr = r.Group("/a") second.Routers(rr) return r }
project->controller->second->index.go
package second import ( "fmt" ms "project/model/second" ss "project/services/second" "github.com/gin-gonic/gin" ) func Routers(r *gin.RouterGroup) { rr := r.Group("") rr.POST("/second", Function) return } func Function(c *gin.Context) { var input ms.Input if err := c.BindJSON(&input); err != nil { fmt.Println(err) } ss.Function(c, input) return }
project->model->second->index.go
package second type Input struct { Id int `view:"id号" json:"id" from:"id"` }
project->services->second->index.go
package second import ( "fmt" ms "project/model/second" "github.com/gin-gonic/gin" ) func Function(c *gin.Context, input ms.Input) { fmt.Println("second .........,input:", input.Id) return }