目录
说明:本节主要说明golang 和 gin 的 项目布局。
操作环境:linux 64
golang 版本: 1.13.1
如果有相关需要可联系我本人(联系方式可参照置顶文章 :获取我的联系方式)获取。
一、项目目录
我的项目globaladmin 在src 目录下,具体如下所示:
接下来详细说明一下每个目录和文件的功能和用途,分目录的目的是为了更好的管理和维护项目。
1、common目录
该目录文件是公用的,里面可包括自定义的变量、自封装的函数处理等。
①common.go
该文件里面 是自封装的函数,如下是文件的Md5 加密函数:
package common
import (
"crypto/md5"
"encoding/hex"
"encoding/json"
"fmt"
"time"
)
//md5加密
func Md5(s string) string{
m := md5.New()
m.Write([]byte (s))
encodeStr := hex.EncodeToString(m.Sum(nil))
return encodeStr
}
使用方法:
(1)先引入
(2)再调用
import (
"fmt"
"../common"
)
....
func test() string {
...
p := common.Md5("待加密的字符串");
fmt.Printf(p)
return p
}
②commonconfig.go
该文件里面是自定义的变量,如:
package common
...
//菜单设置
var LeftMenuJson = "{\"data\":[" +
"{\"id\":\"1\",\"name\":\"黑名单列表\",\"url\":\"getblacklist\",\"style\":\"text-aqua\"}," +
"{\"id\":\"2\",\"name\":\"URL处理列表\",\"url\":\"urllist\",\"style\":\"text-yellow\"}," +
"{\"id\":\"3\",\"name\":\"手动设置黑白名单列表\",\"url\":\"blackAndWhiteList\",\"style\":\"text-green\"}," +
"{\"id\":\"4\",\"name\":\"系统参数设置\",\"url\":\"paramsIndex\",\"style\":\"text-red\"}" +
"]}"
...
使用方法如同①中所示。
2、conf 目录
该目录文件为项目配置目录,里面包括各种数据库的连接等。
①config.go
该文件是环境配置文件,主要定义一些参数和参数类型,通过func GetEnv 来加载不同开发环境下的相关配置,内容可如下:
package conf
import "github.com/go-sql-driver/mysql"
// 环境配置文件
// 可配置多个环境配置,进行切换
type Env struct {
Debug bool
Database mysql.Config
MaxIdleConns int
MaxOpenConns int
ServerPort string
RedisIp string
RedisPort string
RedisPassword string
RedisDb int
RedisSessionDb int
RedisCacheDb int
AppSecret string
AccessLog bool
AccessLogPath string
ErrorLog bool
ErrorLogPath string
InfoLog bool
InfoLogPath string
SqlLog bool
TemplatePath string // 静态文件相对路径
EsearchServer string
}
func GetEnv() *Env {
return &env
}
② env
该文件是开发环境配置,和config.go 中定义的一一对应即可。如下:
package conf
import "github.com/go-sql-driver/mysql"
// 本文件建议在代码协同工具(git/svn等)中忽略
var env = Env{
Debug: true,
ServerPort: "服务端口",
Database: mysql.Config{
User: "用户名",
Passwd: "密码",
Addr: "IP地址:端口",
DBName: "数据库名",
Collation: "utf8mb4_unicode_ci",
Net: "tcp",
AllowNativePasswords: true,
},
MaxIdleConns: 50,
MaxOpenConns: 100,
RedisIp: "redis ip地址",
RedisPort: "redis 端口",
RedisPassword: "",
RedisDb: 0,
RedisSessionDb: 1,
RedisCacheDb: 2,
AccessLog: true,
AccessLogPath: "storage/logs/access.log",
ErrorLog: true,
ErrorLogPath: "storage/logs/error.log",
InfoLog: true,
InfoLogPath: "storage/logs/info.log",
TemplatePath: "frontend/templates",
//APP_SECRET: "YbskZqLNT6TEVLUA9HWdnHmZErypNJpL",
AppSecret: "something-very-secret",
EsearchServer: "",
}
3、connections 目录
该目录下文件为自封装的一些连接服务和操作,比如redis,mysql 等。
比如 当前的 redis.go 文件
package connections
import (
"../conf"
"github.com/go-redis/redis"
"time"
)
type ClientType struct {
RedisCon *redis.Client
}
var Client ClientType
func init() {
Client.RedisCon = redis.NewClient(&redis.Options{
Addr: conf.GetEnv().RedisIp + ":" + conf.GetEnv().RedisPort,
Password: conf.GetEnv().RedisPassword, // no password set
DB: conf.GetEnv().RedisDb, // use default DB
})
}
func (client *ClientType) Set(key string, value interface{}, expiration time.Duration) *redis.Client {
err := client.RedisCon.Set(key, value, expiration).Err()
if err != nil {
panic(err)
}
return (*client).RedisCon
}
func (client *ClientType) Get(key string) (string, *redis.Client) {
val, err := (*client).RedisCon.Get(key).Result()
if err == redis.Nil {
return "", (*client).RedisCon
}
if err != nil {
panic(err)
}
return val, (*client).RedisCon
}
func (client *ClientType) Del(key string) *redis.Client {
_, err := client.RedisCon.Del(key).Result()
if err != nil {
panic(err)
}
return (*client).RedisCon
}
4、controller 目录
该目录下文件是用来处理逻辑的函数,每一个文件处理不同的功能。
比如index.go
package controller
import (
"github.com/gin-gonic/gin"
)
func Index (c *gin.Context) {
now_time,_:=c.Get("now_time")
user_name,_ := c.Get("user_name")
c.HTML(200, "index", gin.H{
"title": "首页",
"user_name":user_name,
"now_time":now_time,
})
}
5、router 目录
该目录下文件 router.go 是项目路由设置。
如当前设置,里面包括模板使用和路由定义,具体的内容可以在后续文章中加以说明。
package router
import (
"../common"
"../controller"
"github.com/foolin/gin-template"
"github.com/gin-gonic/gin"
"html/template"
"time"
)
func InitRouter() *gin.Engine {
router := gin.Default()
router.HTMLRender = gintemplate.New(gintemplate.TemplateConfig{
Root: "views",
Extension: ".html",
Master: "layouts/master",
Partials: []string{"layouts/left_menu","layouts/top"},
Funcs: template.FuncMap{
"copy": func() string{
return time.Now().Format("2006")
},
"left_menu":func() (map[string]interface{}){
return common.LeftMenu()
},
},
DisableCache: true,
})
router.Static("/static/", "static/")
router.GET("/", controller.Users)
router.GET("admin/login", controller.Login)
router.POST("admin/login", controller.LoginPost)
router.Use(controller.Base())
{
router.GET("admin/index", controller.Index)
router.GET("admin/getblacklist",controller.Blacklist)
router.POST("admin/getblacklist",controller.BlacklistPost)
}
return router
}
6、service 目录
公共服务文件,主要给 controller 中的文件调取使用,对于数据操作也可以建一个类似 model 的文件夹。
7、static 目录
该文件是 静态文件目录,包括 js、css、jpg/png等格式图片。
为了能够正常使用需要在路由中设置,见第5 部分:
...
router.Static("/static/", "static/")
...
8、views 目录
该目录下文件 是html 模板文件,以便web 使用。其中 layouts 可以存放公共模板,以便管理。
为了能够正常使用模板需要在路由中设置,见第5 部分:
go get github.com/foolin/gin-template
...
router.HTMLRender = gintemplate.New(gintemplate.TemplateConfig{
Root: "views",
Extension: ".html",
Master: "layouts/master",
Partials: []string{"layouts/left_menu","layouts/top"},
Funcs: template.FuncMap{
"copy": func() string{
return time.Now().Format("2006")
},
"left_menu":func() (map[string]interface{}){
return common.LeftMenu()
},
},
DisableCache: true,
})
...
本项目的具体操作和具体使用将在后续章节中详细说明。
希望本文对你学习有所帮助,感谢您的阅读。