一个 Gin 项目结构示例
0.4632019.07.18 02:21:02字数 144阅读 6,104
├── gin
│ ├── Router
│ └── router.go
│ ├── Middlewares
│ └── corsMiddleware.go
│ ├── Controllers
│ └── testController.go
│ ├── Services
│ └── testService.go
│ ├── Models
│ └── testModel.go
│ ├── Databases
│ └── mysql.go
│ ├── Sessions
│ └── session.go
└── main.go
- 使用gorm访问数据库
- gin 为项目根目录
- main.go 为入口文件
- Router 为路由目录
- Middlewares 为中间件目录
- Controllers 为控制器目录(MVC)
- Services 为服务层目录,这里把DAO逻辑也写入其中,如果分开也可以
- Models 为模型目录
- Databases 为数据库初始化目录
- Sessions 为session初始化目录
- 文件 引用顺序 大致如下:
main.go(在main中关闭数据库) - router(Middlewares) - Controllers - Services(sessions) - Models - Databases
package Mysql
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"fmt"
)
var DB *gorm.DB
func init() {
var err error
DB, err = gorm.Open("mysql", "wuyu:MIDSUMMERfish0@/gin?charset=utf8&parseTime=True&loc=Local")
if err != nil {
fmt.Printf("mysql connect error %v", err)
}
if DB.Error != nil {
fmt.Printf("database error %v", DB.Error)
}
}
package Models
import (
"gin/Databases"
)
type Test struct {
Id int
Testcol string `gorm:"column:testcol"`
}
- Services / testService.go
package Services
import (
"gin/Models"
)
type Test struct {
Id int `json:"id"`
Testcol string `json:"testcol"`
}
func (this *Test) Insert() (id int, err error) {
var testModel Models.Test
testModel.Id = this.Id
testModel.Testcol = this.Testcol
id, err = testModel.Insert()
return
}
- Controllers / testController.go
package Controllers
import (
"github.com/gin-gonic/gin"
"net/http"
"strconv"
"fmt"
"gin/Services"
)
func TestInsert(c *gin.Context) {
var testService Services.Test
err := c.ShouldBindJSON(&testService)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
id, err := testService.Insert()
if err != nil {
c.JSON(http.StatusOK, gin.H{
"code": -1,
"message": "Insert() error!",
})
return
}
c.JSON(http.StatusOK, gin.H{
"code": 1,
"message": "success",
"data": id,
})
}
package Router
import (
"github.com/gin-gonic/gin"
"gin/Controllers"
"gin/Middlewares"
"gin/Sessions"
"github.com/gin-contrib/sessions"
)
func InitRouter() {
router := gin.Default()
- Middlewares / corsMiddleware.go
package Middlewares
import (
"github.com/gin-gonic/gin"
"net/http"
)
package Sessions
import (
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
"github.com/gin-gonic/gin"
"time"
"strconv"
)
var Store = cookie.NewStore([]byte("very-very-secret"))
func SetSession(c *gin.Context, username string) string {
session := sessions.Default(c)
sessionId := "sessionIdxxxxxxxok"
session.Set(sessionId, username)
session.Save()
return sessionId
}
func GetSession(c *gin.Context, sessionId string) (username string) {
session := sessions.Default(c)
result := session.Get(sessionId)
username = result.(string)
return
}
package main
import (
"gin/Router"
"gin/Databases"
)
func main() {
defer Mysql.DB.Close()
Router.InitRouter()
}