Skip to content

Commit

Permalink
Merge pull request #12 from feng9797/main
Browse files Browse the repository at this point in the history
refactor web package resp
  • Loading branch information
junzhiL authored Apr 18, 2022
2 parents 4247afd + d1b00ec commit 10f64cb
Show file tree
Hide file tree
Showing 11 changed files with 138 additions and 106 deletions.
5 changes: 4 additions & 1 deletion mock/mysql.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ func (m *MysqlMock) StartMockMysql() error {
}

func (m *MysqlMock) StopMockMysql() {
m.mysqlServer.Close()
if err := m.mysqlServer.Close(); err != nil {
log.Println("mysql-server stop failed!")
return
}
log.Println("mysql-server stop!")
}
2 changes: 1 addition & 1 deletion redis/config/configuration.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ func LoadConfiguration(yamlFilePath string) (*Configuration, error) {
if err != nil {
return nil, err
}
yamlFile, err := ioutil.ReadFile(realPath)
yamlFile, err := ioutil.ReadFile(filepath.Clean(realPath))
if err != nil {
return nil, err
}
Expand Down
3 changes: 2 additions & 1 deletion redis/file/file_operation.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"io/ioutil"
"log"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
Expand Down Expand Up @@ -143,7 +144,7 @@ func (f *Operation) CreateFile(originPath string) (*os.File, error) {
nameItem = append(nameItem, strconv.FormatInt(f.lastCreateTime, 10))
nameItem = append(nameItem, DefaultVersion)
path := strings.Join(nameItem, Delimiter) + Suffix
return os.OpenFile(path, os.O_CREATE, CacheFilePerm)
return os.OpenFile(filepath.Clean(path), os.O_CREATE, CacheFilePerm)
}

// traversal Traverse and check whether the execution requirements are met
Expand Down
24 changes: 18 additions & 6 deletions redis/file/replay.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"fmt"
"log"
"os"
"path/filepath"
"reflect"
"regexp"
"sort"
Expand Down Expand Up @@ -71,7 +72,7 @@ func ReplayExec(client redis.UniversalClient, interrupted, lineIndex *int64, lin
// Replay Traverse all commands in the file and execute them
func Replay(filename string, client redis.UniversalClient) bool {
var lineIndex, interrupted int64 = 0, 0
file, err := os.OpenFile(filename, os.O_APPEND, CacheFilePerm)
file, err := os.OpenFile(filepath.Clean(filename), os.O_APPEND, CacheFilePerm)
if err != nil {
interrupted++
log.Println("ERROR: OpenFile " + filename + " failed")
Expand All @@ -84,7 +85,10 @@ func Replay(filename string, client redis.UniversalClient) bool {
}
ReplayExec(client, &interrupted, &lineIndex, line)
}
file.Close()
err = file.Close()
if err != nil {
log.Println("ERROR: Close File " + filename + " failed")
}
}
if interrupted > 0 {
oldFilenameInfo, err := Parse(filename)
Expand All @@ -106,20 +110,28 @@ func Replay(filename string, client redis.UniversalClient) bool {

// failDispose Write the execution exception and subsequent contents to the new version number file
func failDispose(srcPath, dstPath string, startLine int64) {
srcFile, err := os.OpenFile(srcPath, os.O_APPEND, CacheFilePerm)
srcFile, err := os.OpenFile(filepath.Clean(srcPath), os.O_APPEND, CacheFilePerm)
if err != nil {
log.Println("ERROR: OpenFile " + srcPath + " failed")
return
}
defer srcFile.Close()
defer func() {
if err := srcFile.Close(); err != nil {
log.Println("ERROR: Close File " + srcPath + " failed")
}
}()
br := bufio.NewReader(srcFile)

dstFile, err := os.OpenFile(dstPath, os.O_CREATE, CacheFilePerm)
dstFile, err := os.OpenFile(filepath.Clean(dstPath), os.O_CREATE, CacheFilePerm)
if err != nil {
log.Println("ERROR: OpenFile " + dstPath + " failed")
return
}
defer dstFile.Close()
defer func() {
if err := dstFile.Close(); err != nil {
log.Println("ERROR: Close File " + dstPath + " failed")
}
}()
bw := bufio.NewWriter(dstFile)
var curLine int64 = 0
for {
Expand Down
3 changes: 2 additions & 1 deletion sql-driver/rds/config/configuration.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"errors"
"io/ioutil"
"os"
"path/filepath"

"github.com/huaweicloud/devcloud-go/common/etcd"
"github.com/huaweicloud/devcloud-go/mas"
Expand Down Expand Up @@ -129,7 +130,7 @@ func ValidateClusterConfiguration(configuration *ClusterConfiguration) error {

// Unmarshal yamlConfigFile to *ClusterConfiguration
func Unmarshal(yamlFilePath string) (*ClusterConfiguration, error) {
yamlFile, err := ioutil.ReadFile(yamlFilePath)
yamlFile, err := ioutil.ReadFile(filepath.Clean(yamlFilePath))
if err != nil {
return nil, err
}
Expand Down
3 changes: 2 additions & 1 deletion sql-driver/rds/config/loader/configuration_file_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"sync"
"time"
Expand Down Expand Up @@ -101,7 +102,7 @@ func (h *ConfigurationFileHandler) Load(hashCode string) *config.RemoteClusterCo
log.Printf("WARNING: %v", err)
return nil
}
content, err := ioutil.ReadFile(cacheConfigPath)
content, err := ioutil.ReadFile(filepath.Clean(cacheConfigPath))
if err != nil {
log.Printf("WARNING: read config from local cache file failed, err %v", err)
return nil
Expand Down
64 changes: 22 additions & 42 deletions web/controller/abstract_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
package controller

import (
"errors"
"github.com/gin-gonic/gin"
"net/http"

Expand All @@ -37,67 +36,48 @@ func NewAbstractController(domain *domain.AbstractDomain) *AbstractController {

func (c *AbstractController) Get(ctx *gin.Context) {
pk := utils.GetStringParam(ctx, c.domain.PKJson)
model, errMsg := c.domain.GetOneByPK(pk)
if errMsg != nil {
ctx.JSON(errMsg.Errno, errMsg)
return
}
ctx.JSON(http.StatusOK, model)
response := c.domain.GetOneByPK(pk)
ctx.JSON(response.Code, resp.GetResp(response))
}

func (c *AbstractController) Add(ctx *gin.Context) {
model := c.domain.GetModel()
response := new(resp.ResponseInfo)
if err := ctx.BindJSON(model.Interface()); err != nil {
ctx.JSON(http.StatusBadRequest, resp.BadRequestErr2Json(err))
return
}
curModel, errMsg := c.domain.Add(model.Interface())
if errMsg != nil {
ctx.JSON(errMsg.Errno, errMsg)
return
response = resp.FailureStatus(http.StatusBadRequest, err.Error())
} else {
response = c.domain.Add(model.Interface())
}
ctx.JSON(http.StatusOK, curModel)
ctx.JSON(response.Code, resp.GetResp(response))
}

func (c *AbstractController) Update(ctx *gin.Context) {
pk := utils.GetStringParam(ctx, c.domain.PKJson)
model := c.domain.GetModel()
var err error
if err = ctx.BindJSON(model.Interface()); err != nil {
ctx.JSON(http.StatusBadRequest, resp.BadRequestErr2Json(err))
return
}
if model.Elem().FieldByName(c.domain.PKName).String() != pk {
ctx.JSON(http.StatusBadRequest, resp.BadRequestErr2Json(errors.New("different "+c.domain.PKJson+" between path and body")))
return
}
curModel, errMsg := c.domain.Update(model.Interface(), pk)
if errMsg != nil {
ctx.JSON(errMsg.Errno, errMsg)
return
response := new(resp.ResponseInfo)
if err := ctx.BindJSON(model.Interface()); err != nil {
response = resp.FailureStatus(http.StatusBadRequest, err.Error())
} else if model.Elem().FieldByName(c.domain.PKName).String() != pk {
response = resp.FailureStatus(http.StatusBadRequest, "different "+c.domain.PKJson+" between path and body")
} else {
response = c.domain.Update(model.Interface(), pk)
}
ctx.JSON(http.StatusOK, curModel)
ctx.JSON(response.Code, resp.GetResp(response))
}

func (c *AbstractController) Delete(ctx *gin.Context) {
pk := utils.GetStringParam(ctx, c.domain.PKJson)
if errMsg := c.domain.Delete(pk); errMsg != nil {
ctx.JSON(errMsg.Errno, errMsg)
return
}
ctx.JSON(http.StatusOK, "OK")
response := c.domain.Delete(pk)
ctx.JSON(response.Code, resp.GetResp(response))
}

func (c *AbstractController) GetAll(ctx *gin.Context) {
queryCond, err := utils.ParseQueryCond(ctx)
response := new(resp.ResponseInfo)
if err != nil {
ctx.JSON(http.StatusBadRequest, resp.BadRequestErr2Json(err))
return
}
models, errMsg := c.domain.GetList(queryCond)
if errMsg != nil {
ctx.JSON(errMsg.Errno, errMsg)
return
response = resp.FailureStatus(http.StatusBadRequest, err.Error())
} else {
response = c.domain.GetList(queryCond)
}
ctx.JSON(http.StatusOK, models)
ctx.JSON(response.Code, resp.GetResp(response))
}
21 changes: 12 additions & 9 deletions web/dao/abstract_dao.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import (
)

type AbstractDao struct {
db *gorm.DB
DB *gorm.DB
*utils.ModelInfo
}

Expand All @@ -34,55 +34,58 @@ func NewAbstractDao(db *gorm.DB, modelInfo *utils.ModelInfo) *AbstractDao {
}

func (d *AbstractDao) Add(model interface{}) (interface{}, error) {
if err := d.db.Create(model).Error; err != nil {
if err := d.DB.Create(model).Error; err != nil {
return nil, err
}
return model, nil
}

func (d *AbstractDao) AddBatch(models interface{}) (interface{}, error) {
if err := d.db.Create(models).Error; err != nil {
if err := d.DB.Create(models).Error; err != nil {
return nil, err
}
return models, nil
}

func (d *AbstractDao) Update(model interface{}, pk string) (interface{}, error) {
if err := d.db.Updates(model).Error; err != nil {
if _, err := d.GetOneByPrimaryKey(pk); err != nil {
return nil, err
}
if err := d.DB.Where(d.PKJson+" = ?", pk).Updates(model).Error; err != nil {
return nil, err
}
return d.GetOneByPrimaryKey(pk)
}

func (d *AbstractDao) DeleteByPrimaryKey(primaryKey string) error {
model := d.GetModel().Interface()
return d.db.Where(d.PKJson+" = ?", primaryKey).Delete(model).Error
return d.DB.Where(d.PKJson+" = ?", primaryKey).Delete(model).Error
}

func (d *AbstractDao) DeleteByPrimaryKeys(primaryKeys []string) error {
model := d.GetModel().Interface()
return d.db.Where(d.PKJson+" IN ?", primaryKeys).Delete(model).Error
return d.DB.Where(d.PKJson+" IN ?", primaryKeys).Delete(model).Error
}

func (d *AbstractDao) GetOneByPrimaryKey(primaryKey string) (interface{}, error) {
model := d.GetModel().Interface()
if err := d.db.Where(d.PKJson+" = ?", primaryKey).First(model).Error; err != nil {
if err := d.DB.Where(d.PKJson+" = ?", primaryKey).First(model).Error; err != nil {
return nil, err
}
return model, nil
}

func (d *AbstractDao) GetListByPrimaryKeys(primaryKeys []string) (interface{}, error) {
models := d.GetModels().Interface()
if err := d.db.Where(d.PKJson+" IN ?", primaryKeys).Find(models).Error; err != nil {
if err := d.DB.Where(d.PKJson+" IN ?", primaryKeys).Find(models).Error; err != nil {
return nil, err
}
return models, nil
}

func (d *AbstractDao) GetList(queryCond utils.QueryConditions) (interface{}, error) {
models := d.GetModels().Interface()
db := d.db.Model(d.GetModel().Interface())
db := d.DB.Model(d.GetModel().Interface())
db = getCondGormDB(db, queryCond)
if err := db.Find(models).Error; err != nil {
return nil, err
Expand Down
50 changes: 32 additions & 18 deletions web/domain/abstract_domain.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@
package domain

import (
"net/http"
"strings"

"gorm.io/gorm"

"github.com/huaweicloud/devcloud-go/web/dao"
"github.com/huaweicloud/devcloud-go/web/resp"
"github.com/huaweicloud/devcloud-go/web/utils"
Expand All @@ -33,42 +38,51 @@ func NewAbstractDomain(abstractDao *dao.AbstractDao) *AbstractDomain {
}
}

func (d *AbstractDomain) Add(model interface{}) (interface{}, *resp.ErrorMsg) {
func (d *AbstractDomain) Add(model interface{}) *resp.ResponseInfo {
model, err := d.abstractDao.Add(model)
if err != nil {
return nil, resp.InternalServerErr2Json(err)
if err == nil {
return resp.CreateData(model)
}
if strings.Contains(err.Error(), utils.ErrDuplicateKey) {
return resp.FailureStatus(http.StatusBadRequest, "duplicate primary key")
}
return model, nil
return resp.Failure(err.Error())
}

func (d *AbstractDomain) GetOneByPK(pk string) (interface{}, *resp.ErrorMsg) {
func (d *AbstractDomain) GetOneByPK(pk string) *resp.ResponseInfo {
model, err := d.abstractDao.GetOneByPrimaryKey(pk)
if err != nil {
return nil, resp.InternalServerErr2Json(err)
if err == nil {
return resp.SuccessData(model)
}
if err == gorm.ErrRecordNotFound {
return resp.FailureStatus(http.StatusNotFound, err.Error())
}
return model, nil
return resp.Failure(err.Error())
}

func (d *AbstractDomain) Update(model interface{}, pk string) (interface{}, *resp.ErrorMsg) {
func (d *AbstractDomain) Update(model interface{}, pk string) *resp.ResponseInfo {
model, err := d.abstractDao.Update(model, pk)
if err != nil {
return nil, resp.InternalServerErr2Json(err)
if err == nil {
return resp.SuccessData(model)
}
if err == gorm.ErrRecordNotFound {
return resp.FailureStatus(http.StatusNotFound, err.Error())
}
return model, nil
return resp.Failure(err.Error())
}

func (d *AbstractDomain) Delete(pk string) *resp.ErrorMsg {
func (d *AbstractDomain) Delete(pk string) *resp.ResponseInfo {
err := d.abstractDao.DeleteByPrimaryKey(pk)
if err != nil {
return resp.InternalServerErr2Json(err)
return resp.Failure(err.Error())
}
return nil
return resp.SuccessData("OK")
}

func (d *AbstractDomain) GetList(queryCond utils.QueryConditions) (interface{}, *resp.ErrorMsg) {
func (d *AbstractDomain) GetList(queryCond utils.QueryConditions) *resp.ResponseInfo {
models, err := d.abstractDao.GetList(queryCond)
if err != nil {
return nil, resp.InternalServerErr2Json(err)
return resp.Failure(err.Error())
}
return models, nil
return resp.SuccessData(models)
}
Loading

0 comments on commit 10f64cb

Please sign in to comment.