Skip to content

Commit

Permalink
优化配置结构,复用file,增加图片上传
Browse files Browse the repository at this point in the history
  • Loading branch information
eddycjy committed May 27, 2018
1 parent 84c228b commit 1adf40f
Show file tree
Hide file tree
Showing 20 changed files with 372 additions and 140 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
.idea/
.DS_Store

/runtime
40 changes: 26 additions & 14 deletions conf/app.ini
Original file line number Diff line number Diff line change
@@ -1,19 +1,31 @@
#debug or release
RUN_MODE = debug

[app]
PAGE_SIZE = 10
JWT_SECRET = 233
PageSize = 10
JwtSecret = 233

RuntimeRootPath = runtime/

ImagePrefixUrl = http://127.0.0.1:8000
ImageSavePath = upload/images/
# MB
ImageMaxSize = 5
ImageAllowExts = .jpg,.jpeg,.png

LogSavePath = logs/
LogSaveName = log
LogFileExt = log
TimeFormat = 20060102

[server]
HTTP_PORT = 8000
READ_TIMEOUT = 60
WRITE_TIMEOUT = 60
#debug or release
RunMode = debug
HttpPort = 8000
ReadTimeout = 60
WriteTimeout = 60

[database]
TYPE = mysql
USER = root
PASSWORD = rootroot
HOST = 127.0.0.1:3306
NAME = blog
TABLE_PREFIX = blog_
Type = mysql
User = root
Password = rootroot
Host = 127.0.0.1:3306
Name = blog
TablePrefix = blog_
14 changes: 10 additions & 4 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@ import (

"github.com/fvbock/endless"

"github.com/EDDYCJY/go-gin-example/pkg/setting"
"github.com/EDDYCJY/go-gin-example/routers"
"github.com/EDDYCJY/go-gin-example/pkg/setting"
"github.com/EDDYCJY/go-gin-example/models"
"github.com/EDDYCJY/go-gin-example/pkg/logging"
)

// @title Golang Gin API
Expand All @@ -19,10 +21,14 @@ import (
// @license.name MIT
// @license.url https://github.com/EDDYCJY/go-gin-example/blob/master/LICENSE
func main() {
endless.DefaultReadTimeOut = setting.ReadTimeout
endless.DefaultWriteTimeOut = setting.WriteTimeout
setting.Setup()
models.Setup()
logging.Setup()

endless.DefaultReadTimeOut = setting.ServerSetting.ReadTimeout
endless.DefaultWriteTimeOut = setting.ServerSetting.WriteTimeout
endless.DefaultMaxHeaderBytes = 1 << 20
endPoint := fmt.Sprintf(":%d", setting.HTTPPort)
endPoint := fmt.Sprintf(":%d", setting.ServerSetting.HttpPort)

server := endless.NewServer(endPoint, routers.InitRouter())
server.BeforeBegin = func(add string) {
Expand Down
2 changes: 2 additions & 0 deletions models/article.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ type Article struct {
Title string `json:"title"`
Desc string `json:"desc"`
Content string `json:"content"`
CoverImageUrl string `json:"cover_image_url"`
CreatedBy string `json:"created_by"`
ModifiedBy string `json:"modified_by"`
State int `json:"state"`
Expand Down Expand Up @@ -58,6 +59,7 @@ func AddArticle(data map[string]interface{}) bool {
Content: data["content"].(string),
CreatedBy: data["created_by"].(string),
State: data["state"].(int),
CoverImageUrl: data["cover_image_url"].(string),
})

return true
Expand Down
35 changes: 10 additions & 25 deletions models/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"

"github.com/EDDYCJY/go-gin-example/pkg/setting"

"time"
"github.com/EDDYCJY/go-gin-example/pkg/setting"
)

var db *gorm.DB
Expand All @@ -20,36 +21,20 @@ type Model struct {
DeletedOn int `json:"deleted_on"`
}

func init() {
var (
err error
dbType, dbName, user, password, host, tablePrefix string
)

sec, err := setting.Cfg.GetSection("database")
if err != nil {
log.Fatal(2, "Fail to get section 'database': %v", err)
}

dbType = sec.Key("TYPE").String()
dbName = sec.Key("NAME").String()
user = sec.Key("USER").String()
password = sec.Key("PASSWORD").String()
host = sec.Key("HOST").String()
tablePrefix = sec.Key("TABLE_PREFIX").String()

db, err = gorm.Open(dbType, fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local",
user,
password,
host,
dbName))
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",
setting.DatabaseSetting.User,
setting.DatabaseSetting.Password,
setting.DatabaseSetting.Host,
setting.DatabaseSetting.Name))

if err != nil {
log.Println(err)
}

gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
return tablePrefix + defaultTableName
return setting.DatabaseSetting.TablePrefix + defaultTableName
}

db.SingularTable(true)
Expand Down
4 changes: 4 additions & 0 deletions pkg/e/code.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,8 @@ const (
ERROR_AUTH_CHECK_TOKEN_TIMEOUT = 20002
ERROR_AUTH_TOKEN = 20003
ERROR_AUTH = 20004

ERROR_UPLOAD_SAVE_IMAGE_FAIL = 30001
ERROR_UPLOAD_CHECK_IMAGE_FAIL = 30002
ERROR_UPLOAD_CHECK_IMAGE_FORMAT = 30003
)
3 changes: 3 additions & 0 deletions pkg/e/msg.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ var MsgFlags = map[int]string{
ERROR_AUTH_CHECK_TOKEN_TIMEOUT: "Token已超时",
ERROR_AUTH_TOKEN: "Token生成失败",
ERROR_AUTH: "Token错误",
ERROR_UPLOAD_SAVE_IMAGE_FAIL: "保存图片失败",
ERROR_UPLOAD_CHECK_IMAGE_FAIL: "检查图片失败",
ERROR_UPLOAD_CHECK_IMAGE_FORMAT: "校验图片错误,图片格式或大小有问题",
}

func GetMsg(code int) string {
Expand Down
59 changes: 59 additions & 0 deletions pkg/file/file.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package file

import (
"os"
"path"
"mime/multipart"
"io/ioutil"
)

func GetSize(f multipart.File) (int, error) {
content, err := ioutil.ReadAll(f)

return len(content), err
}

func GetExt(fileName string) string {
return path.Ext(fileName)
}

func CheckExist(src string) bool {
_, err := os.Stat(src)

return os.IsNotExist(err)
}

func CheckPermission(src string) bool {
_, err := os.Stat(src)

return os.IsPermission(err)
}

func IsNotExistMkDir(src string) error {
if exist := CheckExist(src); exist == false {
if err := MkDir(src); err != nil {
return err
}
}

return nil
}

func MkDir(src string) error {
err := os.MkdirAll(src, os.ModePerm)
if err != nil {
return err
}

return nil
}

func Open(name string, flag int, perm os.FileMode) (*os.File, error) {
f, err := os.OpenFile(name, flag, perm)
if err != nil {
return nil, err
}

return f, nil
}

56 changes: 27 additions & 29 deletions pkg/logging/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,50 +2,48 @@ package logging

import (
"fmt"
"log"
"os"
"time"
)

var (
LogSavePath = "runtime/logs/"
LogSaveName = "log"
LogFileExt = "log"
TimeFormat = "20060102"
"github.com/EDDYCJY/go-gin-example/pkg/setting"
"github.com/EDDYCJY/go-gin-example/pkg/file"
)

func getLogFilePath() string {
return fmt.Sprintf("%s", LogSavePath)
return fmt.Sprintf("%s%s", setting.AppSetting.RuntimeRootPath, setting.AppSetting.LogSavePath)
}

func getLogFileFullPath() string {
prefixPath := getLogFilePath()
suffixPath := fmt.Sprintf("%s%s.%s", LogSaveName, time.Now().Format(TimeFormat), LogFileExt)

return fmt.Sprintf("%s%s", prefixPath, suffixPath)
func getLogFileName() string {
return fmt.Sprintf("%s%s.%s",
setting.AppSetting.LogSaveName,
time.Now().Format(setting.AppSetting.TimeFormat),
setting.AppSetting.LogFileExt,
)
}

func openLogFile(filePath string) *os.File {
_, err := os.Stat(filePath)
switch {
case os.IsNotExist(err):
mkDir(getLogFilePath())
case os.IsPermission(err):
log.Fatalf("Permission :%v", err)
func openLogFile(fileName, filePath string) (*os.File, error) {
dir, err := os.Getwd()
if err != nil {
return nil, fmt.Errorf("os.Getwd err: %v", err)
}

handle, err := os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatalf("Fail to OpenFile :%v", err)
src := dir + "/" + filePath
perm := file.CheckPermission(src)
if perm == true {
return nil, fmt.Errorf("file.CheckPermission Permission denied src: %s", src)
}

return handle
}
err = file.IsNotExistMkDir(src)
if err != nil {
return nil, fmt.Errorf("file.IsNotExistMkDir src: %s, err: %v", src, err)
}

func mkDir(filePath string) {
dir, _ := os.Getwd()
err := os.MkdirAll(dir+"/"+getLogFilePath(), os.ModePerm)
f, err := file.Open(src + fileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
panic(err)
return nil, fmt.Errorf("Fail to OpenFile :%v", err)
}

return f, nil
}


11 changes: 8 additions & 3 deletions pkg/logging/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,14 @@ const (
FATAL
)

func init() {
filePath := getLogFileFullPath()
F = openLogFile(filePath)
func Setup() {
var err error
filePath := getLogFilePath()
fileName := getLogFileName()
F, err = openLogFile(fileName, filePath)
if err != nil {
log.Fatalln(err)
}

logger = log.New(F, DefaultPrefix, log.LstdFlags)
}
Expand Down
Loading

0 comments on commit 1adf40f

Please sign in to comment.