gin funn and testing
This commit is contained in:
29
lib/app/form.go
Normal file
29
lib/app/form.go
Normal file
@ -0,0 +1,29 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"gin-server/lib/messages"
|
||||
"github.com/astaxie/beego/validation"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// BindAndValid binds and validates data
|
||||
func BindAndValid(c *gin.Context, form interface{}) (int, int) {
|
||||
err := c.Bind(form)
|
||||
if err != nil {
|
||||
return http.StatusBadRequest, messages.INVALID_PARAMS
|
||||
}
|
||||
|
||||
valid := validation.Validation{}
|
||||
check, err := valid.Valid(form)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, messages.ERROR
|
||||
}
|
||||
if !check {
|
||||
MarkErrors(valid.Errors)
|
||||
return http.StatusBadRequest, messages.INVALID_PARAMS
|
||||
}
|
||||
|
||||
return http.StatusOK, messages.SUCCESS
|
||||
}
|
||||
|
15
lib/app/request.go
Normal file
15
lib/app/request.go
Normal file
@ -0,0 +1,15 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"github.com/astaxie/beego/validation"
|
||||
"gin-server/lib/logging"
|
||||
)
|
||||
|
||||
// MarkErrors logs error logs
|
||||
func MarkErrors(errors []*validation.Error) {
|
||||
for _, err := range errors {
|
||||
logging.Info(err.Key, err.Message)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
26
lib/app/response.go
Normal file
26
lib/app/response.go
Normal file
@ -0,0 +1,26 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"gin-server/lib/messages"
|
||||
)
|
||||
|
||||
type Gin struct {
|
||||
C *gin.Context
|
||||
}
|
||||
|
||||
type Response struct {
|
||||
Code int `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
Data interface{} `json:"data"`
|
||||
}
|
||||
|
||||
// Response setting gin.JSON
|
||||
func (g *Gin) Response(httpCode, errCode int, data interface{}) {
|
||||
g.C.JSON(httpCode, Response{
|
||||
Code: errCode,
|
||||
Msg: messages.GetMsg(errCode),
|
||||
Data: data,
|
||||
})
|
||||
return
|
||||
}
|
93
lib/file/file.go
Normal file
93
lib/file/file.go
Normal file
@ -0,0 +1,93 @@
|
||||
package file
|
||||
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"mime/multipart"
|
||||
"os"
|
||||
"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 {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// MkDir create a directory
|
||||
func MkDir(src string) error {
|
||||
err := os.MkdirAll(src, os.ModePerm)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
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 {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
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 {
|
||||
return nil, fmt.Errorf("os.Getwd err: %v", err)
|
||||
}
|
||||
|
||||
src := dir + "/" + filePath
|
||||
perm := CheckPermission(src)
|
||||
if perm == true {
|
||||
return nil, fmt.Errorf("file.CheckPermission Permission denied src: %s", src)
|
||||
}
|
||||
|
||||
err = IsNotExistMkDir(src)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("file.IsNotExistMkDir src: %s, err: %v", src, err)
|
||||
}
|
||||
|
||||
f, err := Open(src+fileName, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0644)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Fail to OpenFile :%v", err)
|
||||
}
|
||||
|
||||
return f, nil
|
||||
}
|
24
lib/logging/file.go
Normal file
24
lib/logging/file.go
Normal file
@ -0,0 +1,24 @@
|
||||
package logging
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"gin-server/lib/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,
|
||||
)
|
||||
}
|
||||
|
||||
|
87
lib/logging/log.go
Normal file
87
lib/logging/log.go
Normal file
@ -0,0 +1,87 @@
|
||||
package logging
|
||||
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"gin-server/lib/file"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
type Level int
|
||||
|
||||
var (
|
||||
F *os.File
|
||||
|
||||
DefaultPrefix = ""
|
||||
DefaultCallerDepth = 2
|
||||
|
||||
logger *log.Logger
|
||||
logPrefix = ""
|
||||
levelFlags = []string{"DEBUG", "INFO", "WARN", "ERROR", "FATAL"}
|
||||
)
|
||||
|
||||
const (
|
||||
DEBUG Level = iota
|
||||
INFO
|
||||
WARNING
|
||||
ERROR
|
||||
FATAL
|
||||
)
|
||||
|
||||
// Setup initialize the log instance
|
||||
func Setup() {
|
||||
var err error
|
||||
filePath := getLogFilePath()
|
||||
fileName := getLogFileName()
|
||||
F, err = file.MustOpen(fileName, filePath)
|
||||
if err != nil {
|
||||
log.Fatalf("logging.Setup err: %v", err)
|
||||
}
|
||||
|
||||
logger = log.New(F, DefaultPrefix, log.LstdFlags)
|
||||
}
|
||||
|
||||
// Debug output logs at debug level
|
||||
func Debug(v ...interface{}) {
|
||||
setPrefix(DEBUG)
|
||||
logger.Println(v)
|
||||
}
|
||||
|
||||
// Info output logs at info level
|
||||
func Info(v ...interface{}) {
|
||||
setPrefix(INFO)
|
||||
logger.Println(v)
|
||||
}
|
||||
|
||||
// Warn output logs at warn level
|
||||
func Warn(v ...interface{}) {
|
||||
setPrefix(WARNING)
|
||||
logger.Println(v)
|
||||
}
|
||||
|
||||
// Error output logs at error level
|
||||
func Error(v ...interface{}) {
|
||||
setPrefix(ERROR)
|
||||
logger.Println(v)
|
||||
}
|
||||
|
||||
// Fatal output logs at fatal level
|
||||
func Fatal(v ...interface{}) {
|
||||
setPrefix(FATAL)
|
||||
logger.Fatalln(v)
|
||||
}
|
||||
|
||||
// setPrefix set the prefix of the log output
|
||||
func setPrefix(level Level) {
|
||||
_, file, line, ok := runtime.Caller(DefaultCallerDepth)
|
||||
if ok {
|
||||
logPrefix = fmt.Sprintf("[%s][%s:%d]", levelFlags[level], filepath.Base(file), line)
|
||||
} else {
|
||||
logPrefix = fmt.Sprintf("[%s]", levelFlags[level])
|
||||
}
|
||||
|
||||
logger.SetPrefix(logPrefix)
|
||||
}
|
11
lib/messages/code.go
Normal file
11
lib/messages/code.go
Normal file
@ -0,0 +1,11 @@
|
||||
package messages
|
||||
|
||||
const (
|
||||
SUCCESS = 200
|
||||
ERROR = 500
|
||||
INVALID_PARAMS = 400
|
||||
ERROR_AUTH_CHECK_TOKEN_FAIL = 20001
|
||||
ERROR_AUTH_CHECK_TOKEN_TIMEOUT = 20002
|
||||
ERROR_AUTH_TOKEN = 20003
|
||||
ERROR_AUTH = 20004
|
||||
)
|
22
lib/messages/messages.go
Normal file
22
lib/messages/messages.go
Normal file
@ -0,0 +1,22 @@
|
||||
package messages
|
||||
|
||||
var MsgFlags = map[int]string{
|
||||
SUCCESS: "ok",
|
||||
ERROR: "fail",
|
||||
INVALID_PARAMS: "Invalid parameters",
|
||||
ERROR_AUTH_CHECK_TOKEN_FAIL: "Token fail",
|
||||
ERROR_AUTH_CHECK_TOKEN_TIMEOUT: "Token timeout",
|
||||
ERROR_AUTH_TOKEN: "Bad token",
|
||||
ERROR_AUTH: "Token error",
|
||||
}
|
||||
|
||||
// GetMsg get error information based on Code
|
||||
func GetMsg(code int) string {
|
||||
msg, ok := MsgFlags[code]
|
||||
if ok {
|
||||
return msg
|
||||
}
|
||||
|
||||
return MsgFlags[ERROR]
|
||||
}
|
||||
|
81
lib/setting/setting.go
Normal file
81
lib/setting/setting.go
Normal file
@ -0,0 +1,81 @@
|
||||
package setting
|
||||
|
||||
import (
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/go-ini/ini"
|
||||
)
|
||||
|
||||
type App struct {
|
||||
JwtSecret string
|
||||
PageSize int
|
||||
PrefixUrl string
|
||||
|
||||
RuntimeRootPath string
|
||||
|
||||
LogSavePath string
|
||||
LogSaveName string
|
||||
LogFileExt string
|
||||
TimeFormat string
|
||||
}
|
||||
|
||||
var AppSetting = &App{}
|
||||
|
||||
type Server struct {
|
||||
RunMode string
|
||||
HttpPort int
|
||||
ReadTimeout time.Duration
|
||||
WriteTimeout time.Duration
|
||||
}
|
||||
|
||||
var ServerSetting = &Server{}
|
||||
|
||||
type Database struct {
|
||||
Type string
|
||||
User string
|
||||
Password string
|
||||
Host string
|
||||
Name string
|
||||
TablePrefix string
|
||||
}
|
||||
|
||||
var DatabaseSetting = &Database{}
|
||||
|
||||
type Redis struct {
|
||||
Host string
|
||||
Password string
|
||||
MaxIdle int
|
||||
MaxActive int
|
||||
IdleTimeout time.Duration
|
||||
}
|
||||
|
||||
var RedisSetting = &Redis{}
|
||||
|
||||
var cfg *ini.File
|
||||
|
||||
// Setup initialize the configuration instance
|
||||
func Setup() {
|
||||
var err error
|
||||
cfg, err = ini.Load("conf/app.ini")
|
||||
if err != nil {
|
||||
log.Fatalf("setting.Setup, fail to parse 'conf/app.ini': %v", err)
|
||||
}
|
||||
|
||||
mapTo("app", AppSetting)
|
||||
mapTo("server", ServerSetting)
|
||||
mapTo("database", DatabaseSetting)
|
||||
mapTo("redis", RedisSetting)
|
||||
|
||||
ServerSetting.ReadTimeout = ServerSetting.ReadTimeout * time.Second
|
||||
ServerSetting.WriteTimeout = ServerSetting.WriteTimeout * time.Second
|
||||
RedisSetting.IdleTimeout = RedisSetting.IdleTimeout * time.Second
|
||||
}
|
||||
|
||||
// mapTo map section
|
||||
func mapTo(section string, v interface{}) {
|
||||
err := cfg.Section(section).MapTo(v)
|
||||
if err != nil {
|
||||
log.Fatalf("Cfg.MapTo %s err: %v", section, err)
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user