Skip to content

Commit

Permalink
add comment.
Browse files Browse the repository at this point in the history
  • Loading branch information
eddycjy committed Mar 24, 2019
1 parent 4bfc659 commit e466d3c
Show file tree
Hide file tree
Showing 22 changed files with 81 additions and 35 deletions.
1 change: 1 addition & 0 deletions middleware/jwt/jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/EDDYCJY/go-gin-example/pkg/util"
)

// JWT is jwt middleware
func JWT() gin.HandlerFunc {
return func(c *gin.Context) {
var code int
Expand Down
8 changes: 8 additions & 0 deletions models/article.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ type Article struct {
State int `json:"state"`
}

// ExistArticleByID checks if an article exists based on ID
func ExistArticleByID(id int) (bool, error) {
var article Article
err := db.Select("id").Where("id = ? AND deleted_on = ? ", id, 0).First(&article).Error
Expand All @@ -31,6 +32,7 @@ func ExistArticleByID(id int) (bool, error) {
return false, nil
}

// GetArticleTotal gets the total number of articles based on the constraints
func GetArticleTotal(maps interface{}) (int, error) {
var count int
if err := db.Model(&Article{}).Where(maps).Count(&count).Error; err != nil {
Expand All @@ -40,6 +42,7 @@ func GetArticleTotal(maps interface{}) (int, error) {
return count, nil
}

// GetArticles gets a list of articles based on paging constraints
func GetArticles(pageNum int, pageSize int, maps interface{}) ([]*Article, error) {
var articles []*Article
err := db.Preload("Tag").Where(maps).Offset(pageNum).Limit(pageSize).Find(&articles).Error
Expand All @@ -50,6 +53,7 @@ func GetArticles(pageNum int, pageSize int, maps interface{}) ([]*Article, error
return articles, nil
}

// GetArticle Get a single article based on ID
func GetArticle(id int) (*Article, error) {
var article Article
err := db.Where("id = ? AND deleted_on = ? ", id, 0).First(&article).Related(&article.Tag).Error
Expand All @@ -60,6 +64,7 @@ func GetArticle(id int) (*Article, error) {
return &article, nil
}

// EditArticle modify a single article
func EditArticle(id int, data interface{}) error {
if err := db.Model(&Article{}).Where("id = ? AND deleted_on = ? ", id, 0).Updates(data).Error; err != nil {
return err
Expand All @@ -68,6 +73,7 @@ func EditArticle(id int, data interface{}) error {
return nil
}

// AddArticle add a single article
func AddArticle(data map[string]interface{}) error {
article := Article{
TagID: data["tag_id"].(int),
Expand All @@ -85,6 +91,7 @@ func AddArticle(data map[string]interface{}) error {
return nil
}

// DeleteArticle delete a single article
func DeleteArticle(id int) error {
if err := db.Where("id = ?", id).Delete(Article{}).Error; err != nil {
return err
Expand All @@ -93,6 +100,7 @@ func DeleteArticle(id int) error {
return nil
}

// CleanAllArticle clear all article
func CleanAllArticle() error {
if err := db.Unscoped().Where("deleted_on != ? ", 0).Delete(&Article{}).Error; err != nil {
return err
Expand Down
1 change: 1 addition & 0 deletions models/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ type Auth struct {
Password string `json:"password"`
}

// CheckAuth checks if authentication information exists
func CheckAuth(username, password string) (bool, error) {
var auth Auth
err := db.Select("id").Where(Auth{Username: username, Password: password}).First(&auth).Error
Expand Down
4 changes: 4 additions & 0 deletions models/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ type Model struct {
DeletedOn int `json:"deleted_on"`
}

// Setup initializes the database instance
func Setup() {
var err error
db, err = gorm.Open(setting.DatabaseSetting.Type, fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local",
Expand All @@ -44,6 +45,7 @@ func Setup() {
db.DB().SetMaxOpenConns(100)
}

// CloseDB closes database connection (unnecessary)
func CloseDB() {
defer db.Close()
}
Expand Down Expand Up @@ -73,6 +75,7 @@ func updateTimeStampForUpdateCallback(scope *gorm.Scope) {
}
}

// deleteCallback will set `DeletedOn` where deleting
func deleteCallback(scope *gorm.Scope) {
if !scope.HasError() {
var extraOption string
Expand Down Expand Up @@ -102,6 +105,7 @@ func deleteCallback(scope *gorm.Scope) {
}
}

// addExtraSpaceIfExist adds a separator
func addExtraSpaceIfExist(str string) string {
if str != "" {
return " " + str
Expand Down
8 changes: 8 additions & 0 deletions models/tag.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ type Tag struct {
State int `json:"state"`
}

// ExistTagByName checks if there is a tag with the same name
func ExistTagByName(name string) (bool, error) {
var tag Tag
err := db.Select("id").Where("name = ? AND deleted_on = ? ", name, 0).First(&tag).Error
Expand All @@ -27,6 +28,7 @@ func ExistTagByName(name string) (bool, error) {
return false, nil
}

// AddTag Add a Tag
func AddTag(name string, state int, createdBy string) error {
tag := Tag{
Name: name,
Expand All @@ -40,6 +42,7 @@ func AddTag(name string, state int, createdBy string) error {
return nil
}

// GetTags gets a list of tags based on paging and constraints
func GetTags(pageNum int, pageSize int, maps interface{}) ([]Tag, error) {
var (
tags []Tag
Expand All @@ -59,6 +62,7 @@ func GetTags(pageNum int, pageSize int, maps interface{}) ([]Tag, error) {
return tags, nil
}

// GetTagTotal counts the total number of tags based on the constraint
func GetTagTotal(maps interface{}) (int, error) {
var count int
if err := db.Model(&Tag{}).Where(maps).Count(&count).Error; err != nil {
Expand All @@ -68,6 +72,7 @@ func GetTagTotal(maps interface{}) (int, error) {
return count, nil
}

// ExistTagByID determines whether a Tag exists based on the ID
func ExistTagByID(id int) (bool, error) {
var tag Tag
err := db.Select("id").Where("id = ? AND deleted_on = ? ", id, 0).First(&tag).Error
Expand All @@ -81,6 +86,7 @@ func ExistTagByID(id int) (bool, error) {
return false, nil
}

// DeleteTag delete a tag
func DeleteTag(id int) error {
if err := db.Where("id = ?", id).Delete(&Tag{}).Error; err != nil {
return err
Expand All @@ -89,6 +95,7 @@ func DeleteTag(id int) error {
return nil
}

// EditTag modify a single tag
func EditTag(id int, data interface{}) error {
if err := db.Model(&Tag{}).Where("id = ? AND deleted_on = ? ", id, 0).Updates(data).Error; err != nil {
return err
Expand All @@ -97,6 +104,7 @@ func EditTag(id int, data interface{}) error {
return nil
}

// CleanAllTag clear all tag
func CleanAllTag() (bool, error) {
if err := db.Unscoped().Where("deleted_on != ? ", 0).Delete(&Tag{}).Error; err != nil {
return false, err
Expand Down
1 change: 1 addition & 0 deletions pkg/app/form.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"github.com/EDDYCJY/go-gin-example/pkg/e"
)

// BindAndValid binds and validates data
func BindAndValid(c *gin.Context, form interface{}) (int, int) {
err := c.Bind(form)
if err != nil {
Expand Down
1 change: 1 addition & 0 deletions pkg/app/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"github.com/EDDYCJY/go-gin-example/pkg/logging"
)

// MarkErrors logs error logs
func MarkErrors(errors []*validation.Error) {
for _, err := range errors {
logging.Info(err.Key, err.Message)
Expand Down
1 change: 1 addition & 0 deletions pkg/app/response.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ type Response struct {
Data interface{} `json:"data"`
}

// Response setting gin.JSON
func (g *Gin) Response(httpCode, errCode int, data interface{}) {
g.C.JSON(httpCode, Response{
Code: httpCode,
Expand Down
1 change: 1 addition & 0 deletions pkg/e/msg.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ var MsgFlags = map[int]string{
ERROR_UPLOAD_CHECK_IMAGE_FORMAT: "校验图片错误,图片格式或大小有问题",
}

// GetMsg get error information based on Code
func GetMsg(code int) string {
msg, ok := MsgFlags[code]
if ok {
Expand Down
3 changes: 3 additions & 0 deletions pkg/export/excel.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,17 @@ import "github.com/EDDYCJY/go-gin-example/pkg/setting"

const EXT = ".xlsx"

// GetExcelFullUrl get the full access path of the Excel file
func GetExcelFullUrl(name string) string {
return setting.AppSetting.PrefixUrl + "/" + GetExcelPath() + name
}

// GetExcelPath get the relative save path of the Excel file
func GetExcelPath() string {
return setting.AppSetting.ExportSavePath
}

// GetExcelFullPath Get the full save path of the Excel file
func GetExcelFullPath() string {
return setting.AppSetting.RuntimeRootPath + GetExcelPath()
}
8 changes: 8 additions & 0 deletions pkg/file/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,28 +8,33 @@ import (
"path"
)

// GetSize get the file size
func GetSize(f multipart.File) (int, error) {
content, err := ioutil.ReadAll(f)

return len(content), err
}

// GetExt get the file ext
func GetExt(fileName string) string {
return path.Ext(fileName)
}

// CheckNotExist check if the file exists
func CheckNotExist(src string) bool {
_, err := os.Stat(src)

return os.IsNotExist(err)
}

// CheckPermission check if the file has permission
func CheckPermission(src string) bool {
_, err := os.Stat(src)

return os.IsPermission(err)
}

// IsNotExistMkDir create a directory if it does not exist
func IsNotExistMkDir(src string) error {
if notExist := CheckNotExist(src); notExist == true {
if err := MkDir(src); err != nil {
Expand All @@ -40,6 +45,7 @@ func IsNotExistMkDir(src string) error {
return nil
}

// MkDir create a directory
func MkDir(src string) error {
err := os.MkdirAll(src, os.ModePerm)
if err != nil {
Expand All @@ -49,6 +55,7 @@ func MkDir(src string) error {
return nil
}

// Open a file according to a specific mode
func Open(name string, flag int, perm os.FileMode) (*os.File, error) {
f, err := os.OpenFile(name, flag, perm)
if err != nil {
Expand All @@ -58,6 +65,7 @@ func Open(name string, flag int, perm os.FileMode) (*os.File, error) {
return f, nil
}

// MustOpen maximize trying to open the file
func MustOpen(fileName, filePath string) (*os.File, error) {
dir, err := os.Getwd()
if err != nil {
Expand Down
6 changes: 6 additions & 0 deletions pkg/gredis/redis.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (

var RedisConn *redis.Pool

// Setup Initialize the Redis instance
func Setup() error {
RedisConn = &redis.Pool{
MaxIdle: setting.RedisSetting.MaxIdle,
Expand Down Expand Up @@ -38,6 +39,7 @@ func Setup() error {
return nil
}

// Set a key/value
func Set(key string, data interface{}, time int) error {
conn := RedisConn.Get()
defer conn.Close()
Expand All @@ -60,6 +62,7 @@ func Set(key string, data interface{}, time int) error {
return nil
}

// Exists check a key
func Exists(key string) bool {
conn := RedisConn.Get()
defer conn.Close()
Expand All @@ -72,6 +75,7 @@ func Exists(key string) bool {
return exists
}

// Get get a key
func Get(key string) ([]byte, error) {
conn := RedisConn.Get()
defer conn.Close()
Expand All @@ -84,13 +88,15 @@ func Get(key string) ([]byte, error) {
return reply, nil
}

// Delete delete a kye
func Delete(key string) (bool, error) {
conn := RedisConn.Get()
defer conn.Close()

return redis.Bool(conn.Do("DEL", key))
}

// LikeDeletes batch delete
func LikeDeletes(key string) error {
conn := RedisConn.Get()
defer conn.Close()
Expand Down
29 changes: 3 additions & 26 deletions pkg/logging/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,39 +7,16 @@ import (
"github.com/EDDYCJY/go-gin-example/pkg/setting"
)

// getLogFilePath get the log file save path
func getLogFilePath() string {
return fmt.Sprintf("%s%s", setting.AppSetting.RuntimeRootPath, setting.AppSetting.LogSavePath)
}

// getLogFileName get the save name of the log file
func getLogFileName() string {
return fmt.Sprintf("%s%s.%s",
setting.AppSetting.LogSaveName,
time.Now().Format(setting.AppSetting.TimeFormat),
setting.AppSetting.LogFileExt,
)
}

//func openLogFile(fileName, filePath string) (*os.File, error) {
// dir, err := os.Getwd()
// if err != nil {
// return nil, fmt.Errorf("os.Getwd err: %v", err)
// }
//
// src := dir + "/" + filePath
// perm := file.CheckPermission(src)
// if perm == true {
// return nil, fmt.Errorf("file.CheckPermission Permission denied src: %s", src)
// }
//
// err = file.IsNotExistMkDir(src)
// if err != nil {
// return nil, fmt.Errorf("file.IsNotExistMkDir src: %s, err: %v", src, err)
// }
//
// f, err := file.Open(src+fileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
// if err != nil {
// return nil, fmt.Errorf("Fail to OpenFile :%v", err)
// }
//
// return f, nil
//}
}
Loading

0 comments on commit e466d3c

Please sign in to comment.