fix: lint error

pull/111/head
1379 2 years ago committed by 1379Monitor
parent 0e95384973
commit 4b8edb4624

@ -28,5 +28,5 @@ jobs:
uses: golangci/golangci-lint-action@v3
with:
version: latest
args: --config=.github/linters/.golangci.yml
args: --config=.golangci.yml
only-new-issues: true

@ -6,41 +6,39 @@ run:
issues:
new: true
exclude-rules:
- linters:
- staticcheck
text: "SA1019:"
- linters:
- stylecheck
text: "ST1016:"
linters:
enable:
- errcheck
- gosimple
- govet
- ineffassign
- staticcheck
- typecheck
- unused
- asasalint
- asciicheck
- bodyclose
- decorder
- depguard
- dogsled
- errname
- errorlint
- gocritic
- gofmt
- gofumpt
- goimports
- goprintffuncname
- gosimple
- govet
- ineffassign
- misspell
- nakedret
- revive
- rowserrcheck
- staticcheck
- prealloc
- stylecheck
- typecheck
- unconvert
- unparam
- whitespace
disable:
- deadcode
- errcheck
- unused
- usestdlibvars
- wastedassign
linters-settings:
goimports:

@ -27,7 +27,7 @@ func main() {
OutPath: "./dal",
ModelPkgPath: "./model/entity",
/* Mode: gen.WithoutContext,*/
//if you want the nullable field generation property to be pointer type, set FieldNullable true
// if you want the nullable field generation property to be pointer type, set FieldNullable true
FieldNullable: true,
FieldWithIndexTag: true,
FieldWithTypeTag: true,

@ -97,7 +97,7 @@ func initDirectory(conf *Config) {
err := mkdirFunc(conf.Sonic.LogDir, nil)
err = mkdirFunc(conf.Sonic.UploadDir, err)
if err != nil {
panic(fmt.Errorf("initDirectory err=%v", err))
panic(fmt.Errorf("initDirectory err=%w", err))
}
}

@ -34,7 +34,7 @@ var (
)
const (
DefaultThemeId = "caicai_anatole"
DefaultThemeID = "caicai_anatole"
ThemeScreenshotsName = "screenshot"
ThemeCustomSheetPrefix = "sheet_"
ThemeCustomPostPrefix = "post_"

@ -229,11 +229,12 @@ func (m MFAType) MarshalJSON() ([]byte, error) {
func (m *MFAType) UnmarshalJSON(data []byte) error {
str := string(data)
if str == `"NONE"` {
switch str {
case `"NONE"`:
*m = MFANone
} else if str == `"TFA_TOTP"` {
case `"TFA_TOTP"`:
*m = MFATFATotp
} else {
default:
return xerr.BadParam.New("").WithMsg("unknown MFAType")
}
return nil
@ -270,13 +271,14 @@ const (
)
func (c PostStatus) MarshalJSON() ([]byte, error) {
if c == PostStatusPublished {
switch c {
case PostStatusPublished:
return []byte(`"PUBLISHED"`), nil
} else if c == PostStatusDraft {
case PostStatusDraft:
return []byte(`"DRAFT"`), nil
} else if c == PostStatusRecycle {
case PostStatusRecycle:
return []byte(`"RECYCLE"`), nil
} else if c == PostStatusIntimate {
case PostStatusIntimate:
return []byte(`"INTIMATE"`), nil
}
return nil, nil
@ -284,17 +286,18 @@ func (c PostStatus) MarshalJSON() ([]byte, error) {
func (c *PostStatus) UnmarshalJSON(data []byte) error {
str := string(data)
if str == `"PUBLISHED"` {
switch str {
case `"PUBLISHED"`:
*c = PostStatusPublished
} else if str == `"DRAFT"` {
case `"DRAFT"`:
*c = PostStatusDraft
} else if str == `"RECYCLE"` {
case `"RECYCLE"`:
*c = PostStatusRecycle
} else if str == `"INTIMATE"` {
case `"INTIMATE"`:
*c = PostStatusIntimate
} else if str == "" {
case "":
*c = PostStatusDraft
} else {
default:
return xerr.BadParam.New("").WithMsg("unknown PostStatus")
}
return nil
@ -326,16 +329,18 @@ func (c PostStatus) Ptr() *PostStatus {
}
func PostStatusFromString(str string) (PostStatus, error) {
if str == "PUBLISHED" {
switch str {
case "PUBLISHED":
return PostStatusPublished, nil
} else if str == "DRAFT" {
case "DRAFT":
return PostStatusDraft, nil
} else if str == "RECYCLE" {
case "RECYCLE":
return PostStatusRecycle, nil
} else if str == "INTIMATE" {
case "INTIMATE":
return PostStatusIntimate, nil
default:
return PostStatusDraft, xerr.BadParam.New("").WithMsg("unknown PostStatus")
}
return PostStatusDraft, xerr.BadParam.New("").WithMsg("unknown PostStatus")
}
type CommentStatus int32
@ -347,11 +352,12 @@ const (
)
func (c CommentStatus) MarshalJSON() ([]byte, error) {
if c == CommentStatusPublished {
switch c {
case CommentStatusPublished:
return []byte(`"PUBLISHED"`), nil
} else if c == CommentStatusAuditing {
case CommentStatusAuditing:
return []byte(`"AUDITING"`), nil
} else if c == CommentStatusRecycle {
case CommentStatusRecycle:
return []byte(`"RECYCLE"`), nil
}
return nil, nil
@ -359,13 +365,15 @@ func (c CommentStatus) MarshalJSON() ([]byte, error) {
func (c *CommentStatus) UnmarshalJSON(data []byte) error {
str := string(data)
if str == `"PUBLISHED"` {
switch str {
case `"PUBLISHED"`:
*c = CommentStatusPublished
} else if str == `"AUDITING"` {
case `"AUDITING"`:
*c = CommentStatusAuditing
} else if str == `"RECYCLE"` {
case `"RECYCLE"`:
*c = CommentStatusRecycle
} else {
default:
return xerr.BadParam.New("").WithMsg("unknown CommentStatus")
}
return nil
@ -389,13 +397,14 @@ func (c *CommentStatus) Scan(src interface{}) error {
}
func CommentStatusFromString(str string) (CommentStatus, error) {
if str == "PUBLISHED" {
switch str {
case "PUBLISHED":
return CommentStatusPublished, nil
} else if str == "AUDITING" {
case "AUDITING":
return CommentStatusAuditing, nil
} else if str == "RECYCLE" {
case "RECYCLE":
return CommentStatusRecycle, nil
} else {
default:
return CommentStatusPublished, xerr.BadParam.New("").WithMsg("unknown CommentStatus")
}
}
@ -462,13 +471,14 @@ func (e EditorType) MarshalJSON() ([]byte, error) {
func (e *EditorType) UnmarshalJSON(data []byte) error {
str := string(data)
if str == `"MARKDOWN"` {
switch str {
case `"MARKDOWN"`:
*e = EditorTypeMarkdown
} else if str == `"RICHTEXT"` {
case `"RICHTEXT"`:
*e = EditorTypeRichText
} else if str == "" {
case "":
*e = EditorTypeMarkdown
} else {
default:
return xerr.BadParam.New("").WithMsg("unknown editorType")
}
return nil
@ -491,12 +501,12 @@ func (o OptionType) MarshalJSON() ([]byte, error) {
}
func (o *OptionType) UnmarshalJSON(data []byte) error {
str := string(data)
if str == `"INTERNAL"` {
switch string(data) {
case `"INTERNAL"`:
*o = OptionTypeInternal
} else if str == `"CUSTOM"` {
case `"CUSTOM"`:
*o = OptionTypeCustom
} else {
default:
return xerr.BadParam.New("").WithMsg("unknown OptionType")
}
return nil
@ -608,12 +618,12 @@ func (j JournalType) MarshalJSON() ([]byte, error) {
}
func (j *JournalType) UnmarshalJSON(data []byte) error {
str := string(data)
if str == `"PUBLIC"` {
switch string(data) {
case `"PUBLIC"`:
*j = JournalTypePublic
} else if str == `"INTIMATE"` {
case `"INTIMATE"`:
*j = JournalTypeIntimate
} else {
default:
return xerr.BadParam.New("").WithMsg("unknown JournalType")
}
return nil
@ -858,7 +868,7 @@ func (t ThemeConfigDataType) FormatToStr(value interface{}) (string, error) {
case float32:
valueStr = strconv.FormatFloat(float64(data), 'f', 5, 32)
case float64:
valueStr = strconv.FormatFloat(float64(data), 'f', 5, 64)
valueStr = strconv.FormatFloat(data, 'f', 5, 64)
default:
return "", xerr.WithErrMsgf(nil, "value invalid ThemeConfigDataType")
}
@ -971,12 +981,12 @@ func (c CategoryType) MarshalJSON() ([]byte, error) {
}
func (c *CategoryType) UnmarshalJSON(data []byte) error {
str := string(data)
if str == `"NORMAL"` {
switch string(data) {
case `"NORMAL"`:
*c = CategoryTypeNormal
} else if str == `"INTIMATE"` {
case `"INTIMATE"`:
*c = CategoryTypeIntimate
} else {
default:
return xerr.BadParam.New("").WithMsg("unknown PostStatus")
}
return nil

@ -28,6 +28,8 @@ var (
func NewGormDB(conf *config.Config, gormLogger logger.Interface) *gorm.DB {
var err error
//nolint:gocritic
if conf.SQLite3 != nil && conf.SQLite3.Enable {
DB, err = initSQLite(conf, gormLogger)
if err != nil {

@ -26,7 +26,7 @@ type LogEvent struct {
LogKey string
LogType consts.LogType
Content string
IpAddress string
IPAddress string
}
func (*LogEvent) EventType() string {

@ -29,7 +29,7 @@ func (l *LogEventListener) HandleEvent(ctx context.Context, logEvent event.Event
logDAL := dal.GetQueryByCtx(ctx).Log
logEntity := &entity.Log{
Content: log.Content,
IPAddress: log.IpAddress,
IPAddress: log.IPAddress,
LogKey: log.LogKey,
Type: log.LogType,
}

@ -163,7 +163,7 @@ func (t *TemplateConfigListener) loadOption(ctx context.Context) error {
for _, option := range options {
optionMap[option.Key] = option.Value
}
blogBaseURL := t.OptionService.GetOrByDefault(ctx, property.BlogUrl)
blogBaseURL := t.OptionService.GetOrByDefault(ctx, property.BlogURL)
blogTitle := t.OptionService.GetOrByDefault(ctx, property.BlogTitle)
blogLogo := t.OptionService.GetOrByDefault(ctx, property.BlogLogo)
globalAbsolutePathEnabled := t.OptionService.GetOrByDefault(ctx, property.GlobalAbsolutePathEnabled)

@ -1,6 +1,8 @@
package admin
import (
"errors"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
@ -35,7 +37,8 @@ func (a *AdminHandler) AuthPreCheck(ctx *gin.Context) (interface{}, error) {
var loginParam param.LoginParam
err := ctx.ShouldBindJSON(&loginParam)
if err != nil {
if e, ok := err.(validator.ValidationErrors); ok {
e := validator.ValidationErrors{}
if errors.As(err, &e) {
return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e))
}
return nil, xerr.BadParam.Wrapf(err, "")
@ -52,7 +55,8 @@ func (a *AdminHandler) Auth(ctx *gin.Context) (interface{}, error) {
var loginParam param.LoginParam
err := ctx.ShouldBindJSON(&loginParam)
if err != nil {
if e, ok := err.(validator.ValidationErrors); ok {
e := validator.ValidationErrors{}
if errors.As(err, &e) {
return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e))
}
return nil, xerr.BadParam.Wrapf(err, "").WithStatus(xerr.StatusBadRequest)
@ -70,7 +74,8 @@ func (a *AdminHandler) SendResetCode(ctx *gin.Context) (interface{}, error) {
var resetPasswordParam param.ResetPasswordParam
err := ctx.ShouldBindJSON(&resetPasswordParam)
if err != nil {
if e, ok := err.(validator.ValidationErrors); ok {
e := validator.ValidationErrors{}
if errors.As(err, &e) {
return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e))
}
return nil, xerr.BadParam.Wrapf(err, "").WithStatus(xerr.StatusBadRequest)

@ -1,6 +1,7 @@
package admin
import (
"errors"
"net/http"
"path"
"path/filepath"
@ -41,7 +42,7 @@ func (b *BackupHandler) GetDataBackup(ctx *gin.Context) (interface{}, error) {
if err != nil {
return nil, err
}
return b.BackupService.GetBackup(ctx, filepath.Join(config.DataExportDir, filename), service.JsonData)
return b.BackupService.GetBackup(ctx, filepath.Join(config.DataExportDir, filename), service.JSONData)
}
func (b *BackupHandler) GetMarkDownBackup(ctx *gin.Context) (interface{}, error) {
@ -56,7 +57,8 @@ func (b *BackupHandler) BackupWholeSite(ctx *gin.Context) (interface{}, error) {
toBackupItems := make([]string, 0)
err := ctx.ShouldBindJSON(&toBackupItems)
if err != nil {
if e, ok := err.(validator.ValidationErrors); ok {
e := validator.ValidationErrors{}
if errors.As(err, &e) {
return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e))
}
return nil, xerr.WithStatus(err, xerr.StatusBadRequest)
@ -98,7 +100,7 @@ func (b *BackupHandler) DownloadBackups(ctx *gin.Context) {
filePath, err := b.BackupService.GetBackupFilePath(ctx, config.BackupDir, filename)
if err != nil {
log.CtxErrorf(ctx, "err=%+v", err)
status := xerr.GetHttpStatus(err)
status := xerr.GetHTTPStatus(err)
ctx.JSON(status, &dto.BaseDTO{Status: status, Message: xerr.GetMessage(err)})
}
ctx.File(filePath)
@ -142,7 +144,7 @@ func (b *BackupHandler) HandleData(ctx *gin.Context) {
}
func (b *BackupHandler) ListExportData(ctx *gin.Context) (interface{}, error) {
return b.BackupService.ListFiles(ctx, config.DataExportDir, service.JsonData)
return b.BackupService.ListFiles(ctx, config.DataExportDir, service.JSONData)
}
func (b *BackupHandler) DownloadData(ctx *gin.Context) {
@ -156,7 +158,7 @@ func (b *BackupHandler) DownloadData(ctx *gin.Context) {
filePath, err := b.BackupService.GetBackupFilePath(ctx, config.DataExportDir, filename)
if err != nil {
log.CtxErrorf(ctx, "err=%+v", err)
status := xerr.GetHttpStatus(err)
status := xerr.GetHTTPStatus(err)
ctx.JSON(status, &dto.BaseDTO{Status: status, Message: xerr.GetMessage(err)})
}
ctx.File(filePath)
@ -174,7 +176,8 @@ func (b *BackupHandler) ExportMarkdown(ctx *gin.Context) (interface{}, error) {
var exportMarkdownParam param.ExportMarkdown
err := ctx.ShouldBindJSON(&exportMarkdownParam)
if err != nil {
if e, ok := err.(validator.ValidationErrors); ok {
e := validator.ValidationErrors{}
if errors.As(err, &e) {
return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e))
}
return nil, xerr.WithStatus(err, xerr.StatusBadRequest)
@ -206,7 +209,7 @@ func (b *BackupHandler) DownloadMarkdown(ctx *gin.Context) {
filePath, err := b.BackupService.GetBackupFilePath(ctx, config.BackupMarkdownDir, filename)
if err != nil {
log.CtxErrorf(ctx, "err=%+v", err)
status := xerr.GetHttpStatus(err)
status := xerr.GetHTTPStatus(err)
ctx.JSON(status, &dto.BaseDTO{Status: status, Message: xerr.GetMessage(err)})
}
ctx.File(filePath)
@ -219,7 +222,7 @@ func wrapHandler(handler wrapperHandler) gin.HandlerFunc {
data, err := handler(ctx)
if err != nil {
log.CtxErrorf(ctx, "err=%+v", err)
status := xerr.GetHttpStatus(err)
status := xerr.GetHTTPStatus(err)
ctx.JSON(status, &dto.BaseDTO{Status: status, Message: xerr.GetMessage(err)})
return
}

@ -1,6 +1,8 @@
package admin
import (
"errors"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
@ -26,7 +28,7 @@ func (c *CategoryHandler) GetCategoryByID(ctx *gin.Context) (interface{}, error)
if err != nil {
return nil, err
}
category, err := c.CategoryService.GetByID(ctx, int32(id))
category, err := c.CategoryService.GetByID(ctx, id)
if err != nil {
return nil, err
}
@ -72,7 +74,8 @@ func (c *CategoryHandler) CreateCategory(ctx *gin.Context) (interface{}, error)
var categoryParam param.Category
err := ctx.ShouldBindJSON(&categoryParam)
if err != nil {
if e, ok := err.(validator.ValidationErrors); ok {
e := validator.ValidationErrors{}
if errors.As(err, &e) {
return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e))
}
return nil, xerr.WithStatus(err, xerr.StatusBadRequest)
@ -88,7 +91,8 @@ func (c *CategoryHandler) UpdateCategory(ctx *gin.Context) (interface{}, error)
var categoryParam param.Category
err := ctx.ShouldBindJSON(&categoryParam)
if err != nil {
if e, ok := err.(validator.ValidationErrors); ok {
e := validator.ValidationErrors{}
if errors.As(err, &e) {
return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e))
}
return nil, xerr.WithStatus(err, xerr.StatusBadRequest)
@ -109,7 +113,8 @@ func (c *CategoryHandler) UpdateCategoryBatch(ctx *gin.Context) (interface{}, er
categoryParams := make([]*param.Category, 0)
err := ctx.ShouldBindJSON(&categoryParams)
if err != nil {
if e, ok := err.(validator.ValidationErrors); ok {
e := validator.ValidationErrors{}
if errors.As(err, &e) {
return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e))
}
return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error")

@ -1,6 +1,8 @@
package admin
import (
"errors"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
@ -133,7 +135,8 @@ func (j *JournalCommentHandler) CreateJournalComment(ctx *gin.Context) (interfac
var commentParam *param.AdminComment
err := ctx.ShouldBindJSON(&commentParam)
if err != nil {
if e, ok := err.(validator.ValidationErrors); ok {
e := validator.ValidationErrors{}
if errors.As(err, &e) {
return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e))
}
return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error")
@ -187,7 +190,8 @@ func (j *JournalCommentHandler) UpdateJournalComment(ctx *gin.Context) (interfac
var commentParam *param.Comment
err = ctx.ShouldBindJSON(&commentParam)
if err != nil {
if e, ok := err.(validator.ValidationErrors); ok {
e := validator.ValidationErrors{}
if errors.As(err, &e) {
return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e))
}
return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error")

@ -1,6 +1,8 @@
package admin
import (
"errors"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
@ -139,7 +141,8 @@ func (p *PostCommentHandler) CreatePostComment(ctx *gin.Context) (interface{}, e
var commentParam *param.AdminComment
err := ctx.ShouldBindJSON(&commentParam)
if err != nil {
if e, ok := err.(validator.ValidationErrors); ok {
e := validator.ValidationErrors{}
if errors.As(err, &e) {
return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e))
}
return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error")
@ -177,7 +180,8 @@ func (p *PostCommentHandler) UpdatePostComment(ctx *gin.Context) (interface{}, e
var commentParam *param.Comment
err = ctx.ShouldBindJSON(&commentParam)
if err != nil {
if e, ok := err.(validator.ValidationErrors); ok {
e := validator.ValidationErrors{}
if errors.As(err, &e) {
return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e))
}
return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error")

@ -2,6 +2,7 @@ package admin
import (
"context"
"errors"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
@ -146,7 +147,8 @@ func (s *SheetCommentHandler) CreateSheetComment(ctx *gin.Context) (interface{},
var commentParam *param.AdminComment
err := ctx.ShouldBindJSON(&commentParam)
if err != nil {
if e, ok := err.(validator.ValidationErrors); ok {
e := validator.ValidationErrors{}
if errors.As(err, &e) {
return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e))
}
return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error")

@ -1,6 +1,8 @@
package admin
import (
"errors"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
@ -24,7 +26,8 @@ func (i *InstallHandler) InstallBlog(ctx *gin.Context) (interface{}, error) {
var installParam param.Install
err := ctx.ShouldBindJSON(&installParam)
if err != nil {
if e, ok := err.(validator.ValidationErrors); ok {
e := validator.ValidationErrors{}
if errors.As(err, &e) {
return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e))
}
return nil, xerr.WithStatus(err, xerr.StatusBadRequest)

@ -1,6 +1,8 @@
package admin
import (
"errors"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
@ -63,7 +65,8 @@ func (j *JournalHandler) CreateJournal(ctx *gin.Context) (interface{}, error) {
var journalParam param.Journal
err := ctx.ShouldBindJSON(&journalParam)
if err != nil {
if e, ok := err.(validator.ValidationErrors); ok {
e := validator.ValidationErrors{}
if errors.As(err, &e) {
return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e))
}
return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error")
@ -82,7 +85,8 @@ func (j *JournalHandler) UpdateJournal(ctx *gin.Context) (interface{}, error) {
var journalParam param.Journal
err := ctx.ShouldBindJSON(&journalParam)
if err != nil {
if e, ok := err.(validator.ValidationErrors); ok {
e := validator.ValidationErrors{}
if errors.As(err, &e) {
return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e))
}
return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error")
@ -100,5 +104,5 @@ func (j *JournalHandler) DeleteJournal(ctx *gin.Context) (interface{}, error) {
if err != nil {
return nil, err
}
return nil, j.JournalService.Delete(ctx, int32(journalID))
return nil, j.JournalService.Delete(ctx, journalID)
}

@ -1,6 +1,8 @@
package admin
import (
"errors"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
@ -56,7 +58,8 @@ func (l *LinkHandler) CreateLink(ctx *gin.Context) (interface{}, error) {
linkParam := &param.Link{}
err := ctx.ShouldBindJSON(linkParam)
if err != nil {
if e, ok := err.(validator.ValidationErrors); ok {
e := validator.ValidationErrors{}
if errors.As(err, &e) {
return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e))
}
return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error")
@ -77,7 +80,8 @@ func (l *LinkHandler) UpdateLink(ctx *gin.Context) (interface{}, error) {
err = ctx.ShouldBindJSON(linkParam)
if err != nil {
if e, ok := err.(validator.ValidationErrors); ok {
e := validator.ValidationErrors{}
if errors.As(err, &e) {
return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e))
}
return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error")

@ -1,6 +1,8 @@
package admin
import (
"errors"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
@ -97,7 +99,8 @@ func (m *MenuHandler) CreateMenu(ctx *gin.Context) (interface{}, error) {
menuParam := &param.Menu{}
err := ctx.ShouldBindJSON(menuParam)
if err != nil {
if e, ok := err.(validator.ValidationErrors); ok {
e := validator.ValidationErrors{}
if errors.As(err, &e) {
return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e))
}
return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error")
@ -113,7 +116,8 @@ func (m *MenuHandler) CreateMenuBatch(ctx *gin.Context) (interface{}, error) {
menuParams := make([]*param.Menu, 0)
err := ctx.ShouldBindJSON(&menuParams)
if err != nil {
if e, ok := err.(validator.ValidationErrors); ok {
e := validator.ValidationErrors{}
if errors.As(err, &e) {
return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e))
}
return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error")
@ -134,7 +138,8 @@ func (m *MenuHandler) UpdateMenu(ctx *gin.Context) (interface{}, error) {
err = ctx.ShouldBindJSON(menuParam)
if err != nil {
if e, ok := err.(validator.ValidationErrors); ok {
e := validator.ValidationErrors{}
if errors.As(err, &e) {
return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e))
}
return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error")
@ -150,7 +155,8 @@ func (m *MenuHandler) UpdateMenuBatch(ctx *gin.Context) (interface{}, error) {
menuParams := make([]*param.Menu, 0)
err := ctx.ShouldBindJSON(&menuParams)
if err != nil {
if e, ok := err.(validator.ValidationErrors); ok {
e := validator.ValidationErrors{}
if errors.As(err, &e) {
return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e))
}
return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error")

@ -1,6 +1,8 @@
package admin
import (
"errors"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
@ -74,7 +76,8 @@ func (p *PhotoHandler) CreatePhoto(ctx *gin.Context) (interface{}, error) {
photoParam := &param.Photo{}
err := ctx.ShouldBindJSON(photoParam)
if err != nil {
if e, ok := err.(validator.ValidationErrors); ok {
e := validator.ValidationErrors{}
if errors.As(err, &e) {
return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e))
}
return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error")
@ -95,7 +98,8 @@ func (p *PhotoHandler) UpdatePhoto(ctx *gin.Context) (interface{}, error) {
err = ctx.ShouldBindJSON(photoParam)
if err != nil {
if e, ok := err.(validator.ValidationErrors); ok {
e := validator.ValidationErrors{}
if errors.As(err, &e) {
return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e))
}
return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error")

@ -1,6 +1,7 @@
package admin
import (
"errors"
"strconv"
"github.com/gin-gonic/gin"
@ -154,14 +155,15 @@ func (p *PostHandler) LikePost(ctx *gin.Context) (interface{}, error) {
if err != nil {
return nil, err
}
return nil, p.PostService.IncreaseLike(ctx, int32(postID))
return nil, p.PostService.IncreaseLike(ctx, postID)
}
func (p *PostHandler) CreatePost(ctx *gin.Context) (interface{}, error) {
var postParam param.Post
err := ctx.ShouldBindJSON(&postParam)
if err != nil {
if e, ok := err.(validator.ValidationErrors); ok {
e := validator.ValidationErrors{}
if errors.As(err, &e) {
return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e))
}
return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error")
@ -178,7 +180,8 @@ func (p *PostHandler) UpdatePost(ctx *gin.Context) (interface{}, error) {
var postParam param.Post
err := ctx.ShouldBindJSON(&postParam)
if err != nil {
if e, ok := err.(validator.ValidationErrors); ok {
e := validator.ValidationErrors{}
if errors.As(err, &e) {
return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e))
}
return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error")
@ -214,7 +217,7 @@ func (p *PostHandler) UpdatePostStatus(ctx *gin.Context) (interface{}, error) {
if int32(status) < int32(consts.PostStatusPublished) || int32(status) > int32(consts.PostStatusIntimate) {
return nil, xerr.WithStatus(nil, xerr.StatusBadRequest).WithMsg("status error")
}
post, err := p.PostService.UpdateStatus(ctx, int32(postID), consts.PostStatus(status))
post, err := p.PostService.UpdateStatus(ctx, int32(postID), status)
if err != nil {
return nil, err
}
@ -239,7 +242,7 @@ func (p *PostHandler) UpdatePostStatusBatch(ctx *gin.Context) (interface{}, erro
return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("post ids error")
}
return p.PostService.UpdateStatusBatch(ctx, consts.PostStatus(status), ids)
return p.PostService.UpdateStatusBatch(ctx, status, ids)
}
func (p *PostHandler) UpdatePostDraft(ctx *gin.Context) (interface{}, error) {
@ -252,7 +255,7 @@ func (p *PostHandler) UpdatePostDraft(ctx *gin.Context) (interface{}, error) {
if err != nil {
return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("content param error")
}
post, err := p.PostService.UpdateDraftContent(ctx, int32(postID), postContentParam.Content)
post, err := p.PostService.UpdateDraftContent(ctx, postID, postContentParam.Content)
if err != nil {
return nil, err
}
@ -281,5 +284,5 @@ func (p *PostHandler) PreviewPost(ctx *gin.Context) (interface{}, error) {
if err != nil {
return nil, err
}
return p.PostService.Preview(ctx, int32(postID))
return p.PostService.Preview(ctx, postID)
}

@ -1,6 +1,8 @@
package admin
import (
"errors"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
@ -69,7 +71,8 @@ func (s *SheetHandler) CreateSheet(ctx *gin.Context) (interface{}, error) {
var sheetParam param.Sheet
err := ctx.ShouldBindJSON(&sheetParam)
if err != nil {
if e, ok := err.(validator.ValidationErrors); ok {
e := validator.ValidationErrors{}
if errors.As(err, &e) {
return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e))
}
return nil, xerr.WithStatus(err, xerr.StatusBadRequest)
@ -89,7 +92,8 @@ func (s *SheetHandler) UpdateSheet(ctx *gin.Context) (interface{}, error) {
var sheetParam param.Sheet
err := ctx.ShouldBindJSON(&sheetParam)
if err != nil {
if e, ok := err.(validator.ValidationErrors); ok {
e := validator.ValidationErrors{}
if errors.As(err, &e) {
return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e))
}
return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error")
@ -111,14 +115,18 @@ func (s *SheetHandler) UpdateSheetStatus(ctx *gin.Context) (interface{}, error)
if err != nil {
return nil, err
}
status, err := util.ParamInt32(ctx, "status")
statusStr, err := util.ParamString(ctx, "status")
if err != nil {
return nil, err
}
status, err := consts.PostStatusFromString(statusStr)
if err != nil {
return nil, err
}
if status < int32(consts.PostStatusPublished) || status > int32(consts.PostStatusIntimate) {
if status < consts.PostStatusPublished || status > consts.PostStatusIntimate {
return nil, xerr.WithStatus(nil, xerr.StatusBadRequest).WithMsg("status error")
}
return s.SheetService.UpdateStatus(ctx, sheetID, consts.PostStatus(status))
return s.SheetService.UpdateStatus(ctx, sheetID, status)
}
func (s *SheetHandler) UpdateSheetDraft(ctx *gin.Context) (interface{}, error) {
@ -131,7 +139,7 @@ func (s *SheetHandler) UpdateSheetDraft(ctx *gin.Context) (interface{}, error) {
if err != nil {
return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("content param error")
}
post, err := s.SheetService.UpdateDraftContent(ctx, int32(sheetID), postContentParam.Content)
post, err := s.SheetService.UpdateDraftContent(ctx, sheetID, postContentParam.Content)
if err != nil {
return nil, err
}
@ -143,7 +151,7 @@ func (s *SheetHandler) DeleteSheet(ctx *gin.Context) (interface{}, error) {
if err != nil {
return nil, err
}
return nil, s.SheetService.Delete(ctx, int32(sheetID))
return nil, s.SheetService.Delete(ctx, sheetID)
}
func (s *SheetHandler) PreviewSheet(ctx *gin.Context) (interface{}, error) {
@ -151,5 +159,5 @@ func (s *SheetHandler) PreviewSheet(ctx *gin.Context) (interface{}, error) {
if err != nil {
return nil, err
}
return s.PostService.Preview(ctx, int32(sheetID))
return s.PostService.Preview(ctx, sheetID)
}

@ -1,6 +1,8 @@
package admin
import (
"errors"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
@ -59,7 +61,8 @@ func (t *TagHandler) CreateTag(ctx *gin.Context) (interface{}, error) {
tagParam := &param.Tag{}
err := ctx.ShouldBindJSON(tagParam)
if err != nil {
if e, ok := err.(validator.ValidationErrors); ok {
e := validator.ValidationErrors{}
if errors.As(err, &e) {
return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e))
}
return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error")
@ -80,7 +83,8 @@ func (t *TagHandler) UpdateTag(ctx *gin.Context) (interface{}, error) {
err = ctx.ShouldBindJSON(tagParam)
if err != nil {
if e, ok := err.(validator.ValidationErrors); ok {
e := validator.ValidationErrors{}
if errors.As(err, &e) {
return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e))
}
return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error")

@ -1,6 +1,8 @@
package admin
import (
"errors"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
@ -37,7 +39,7 @@ func (t *ThemeHandler) ListAllThemes(ctx *gin.Context) (interface{}, error) {
}
func (t *ThemeHandler) ListActivatedThemeFile(ctx *gin.Context) (interface{}, error) {
activatedThemeID, err := t.OptionService.GetActivatedThemeId(ctx)
activatedThemeID, err := t.OptionService.GetActivatedThemeID(ctx)
if err != nil {
return nil, err
}
@ -57,7 +59,7 @@ func (t *ThemeHandler) GetThemeFileContent(ctx *gin.Context) (interface{}, error
if err != nil {
return nil, err
}
activatedThemeID, err := t.OptionService.GetActivatedThemeId(ctx)
activatedThemeID, err := t.OptionService.GetActivatedThemeID(ctx)
if err != nil {
return nil, err
}
@ -82,13 +84,14 @@ func (t *ThemeHandler) UpdateThemeFile(ctx *gin.Context) (interface{}, error) {
err := ctx.ShouldBindJSON(themeParam)
if err != nil {
if err != nil {
if e, ok := err.(validator.ValidationErrors); ok {
e := validator.ValidationErrors{}
if errors.As(err, &e) {
return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e))
}
return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error")
}
}
activatedThemeID, err := t.OptionService.GetActivatedThemeId(ctx)
activatedThemeID, err := t.OptionService.GetActivatedThemeID(ctx)
if err != nil {
return nil, err
}
@ -104,7 +107,8 @@ func (t *ThemeHandler) UpdateThemeFileByID(ctx *gin.Context) (interface{}, error
err = ctx.ShouldBindJSON(themeParam)
if err != nil {
if err != nil {
if e, ok := err.(validator.ValidationErrors); ok {
e := validator.ValidationErrors{}
if errors.As(err, &e) {
return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e))
}
return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error")
@ -114,7 +118,7 @@ func (t *ThemeHandler) UpdateThemeFileByID(ctx *gin.Context) (interface{}, error
}
func (t *ThemeHandler) ListCustomSheetTemplate(ctx *gin.Context) (interface{}, error) {
activatedThemeID, err := t.OptionService.GetActivatedThemeId(ctx)
activatedThemeID, err := t.OptionService.GetActivatedThemeID(ctx)
if err != nil {
return nil, err
}
@ -122,7 +126,7 @@ func (t *ThemeHandler) ListCustomSheetTemplate(ctx *gin.Context) (interface{}, e
}
func (t *ThemeHandler) ListCustomPostTemplate(ctx *gin.Context) (interface{}, error) {
activatedThemeID, err := t.OptionService.GetActivatedThemeId(ctx)
activatedThemeID, err := t.OptionService.GetActivatedThemeID(ctx)
if err != nil {
return nil, err
}
@ -138,7 +142,7 @@ func (t *ThemeHandler) ActivateTheme(ctx *gin.Context) (interface{}, error) {
}
func (t *ThemeHandler) GetActivatedTheme(ctx *gin.Context) (interface{}, error) {
activatedThemeID, err := t.OptionService.GetActivatedThemeId(ctx)
activatedThemeID, err := t.OptionService.GetActivatedThemeID(ctx)
if err != nil {
return nil, err
}
@ -146,7 +150,7 @@ func (t *ThemeHandler) GetActivatedTheme(ctx *gin.Context) (interface{}, error)
}
func (t *ThemeHandler) GetActivatedThemeConfig(ctx *gin.Context) (interface{}, error) {
activatedThemeID, err := t.OptionService.GetActivatedThemeId(ctx)
activatedThemeID, err := t.OptionService.GetActivatedThemeID(ctx)
if err != nil {
return nil, err
}
@ -199,7 +203,7 @@ func (t *ThemeHandler) GetThemeConfigGroupNames(ctx *gin.Context) (interface{},
}
func (t *ThemeHandler) GetActivatedThemeSettingMap(ctx *gin.Context) (interface{}, error) {
activatedThemeID, err := t.OptionService.GetActivatedThemeId(ctx)
activatedThemeID, err := t.OptionService.GetActivatedThemeID(ctx)
if err != nil {
return nil, err
}
@ -227,7 +231,7 @@ func (t *ThemeHandler) GetThemeSettingMapByGroupAndThemeID(ctx *gin.Context) (in
}
func (t *ThemeHandler) SaveActivatedThemeSetting(ctx *gin.Context) (interface{}, error) {
activatedThemeID, err := t.OptionService.GetActivatedThemeId(ctx)
activatedThemeID, err := t.OptionService.GetActivatedThemeID(ctx)
if err != nil {
return nil, err
}

@ -1,6 +1,8 @@
package admin
import (
"errors"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
@ -37,7 +39,8 @@ func (u *UserHandler) UpdateUserProfile(ctx *gin.Context) (interface{}, error) {
userParam := &param.User{}
err := ctx.ShouldBindJSON(userParam)
if err != nil {
if e, ok := err.(validator.ValidationErrors); ok {
e := validator.ValidationErrors{}
if errors.As(err, &e) {
return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e))
}
return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error")
@ -57,7 +60,8 @@ func (u *UserHandler) UpdatePassword(ctx *gin.Context) (interface{}, error) {
passwordParam := &Password{}
err := ctx.ShouldBindJSON(passwordParam)
if err != nil {
if e, ok := err.(validator.ValidationErrors); ok {
e := validator.ValidationErrors{}
if errors.As(err, &e) {
return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e))
}
return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error")
@ -72,7 +76,8 @@ func (u *UserHandler) GenerateMFAQRCode(ctx *gin.Context) (interface{}, error) {
param := &Param{}
err := ctx.ShouldBindJSON(param)
if err != nil {
if e, ok := err.(validator.ValidationErrors); ok {
e := validator.ValidationErrors{}
if errors.As(err, &e) {
return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e))
}
return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error")
@ -92,7 +97,7 @@ func (u *UserHandler) GenerateMFAQRCode(ctx *gin.Context) (interface{}, error) {
return nil, err
}
mfaFactorAuthDTO.MFAType = consts.MFATFATotp
mfaFactorAuthDTO.OptAuthUrl = url
mfaFactorAuthDTO.OptAuthURL = url
mfaFactorAuthDTO.MFAKey = key
qrCode, err := u.TwoFactorMFAService.GenerateMFAQRCode(ctx, url)
if err != nil {
@ -114,7 +119,8 @@ func (u *UserHandler) UpdateMFA(ctx *gin.Context) (interface{}, error) {
mfaParam := &Param{}
err := ctx.ShouldBindJSON(mfaParam)
if err != nil {
if e, ok := err.(validator.ValidationErrors); ok {
e := validator.ValidationErrors{}
if errors.As(err, &e) {
return nil, xerr.WithStatus(e, xerr.StatusBadRequest).WithMsg(trans.Translate(e))
}
return nil, xerr.WithStatus(err, xerr.StatusBadRequest).WithMsg("parameter error")

@ -1,6 +1,7 @@
package binding
import (
"errors"
"net/http"
"github.com/gin-gonic/gin/binding"
@ -10,8 +11,10 @@ const defaultMemory = 32 << 20
// CustomFormBinding If the type implements the UnmarshalJSON interface, use JSON to bind
// For the purpose of support enum string to turn the enum type binding
var CustomFormBinding = customFormBinding{}
var CustomFormPostBinding = customFormPostBinding{}
var (
CustomFormBinding = customFormBinding{}
CustomFormPostBinding = customFormPostBinding{}
)
type (
customFormBinding struct{}
@ -27,7 +30,7 @@ func (customFormBinding) Bind(req *http.Request, obj interface{}) error {
return err
}
if err := req.ParseMultipartForm(defaultMemory); err != nil {
if err != http.ErrNotMultipart {
if !errors.Is(err, http.ErrNotMultipart) {
return err
}
}

@ -212,8 +212,7 @@ func setWithProperType(val string, value reflect.Value, field reflect.StructFiel
case reflect.Int32:
return setIntField(val, 32, value)
case reflect.Int64:
switch value.Interface().(type) {
case time.Duration:
if _, ok := value.Interface().(time.Duration); ok {
return setTimeDuration(val, value)
}
return setIntField(val, 64, value)
@ -236,8 +235,7 @@ func setWithProperType(val string, value reflect.Value, field reflect.StructFiel
case reflect.String:
value.SetString(val)
case reflect.Struct:
switch value.Interface().(type) {
case time.Time:
if _, ok := value.Interface().(time.Time); ok {
return setTimeField(val, field, value)
}
return json.Unmarshal(util.StringToBytes(val), value.Addr().Interface())

@ -37,12 +37,12 @@ func NewSheetHandler(
}
}
func (j *SheetHandler) ListTopComment(ctx *gin.Context) (interface{}, error) {
func (s *SheetHandler) ListTopComment(ctx *gin.Context) (interface{}, error) {
sheetID, err := util.ParamInt32(ctx, "sheetID")
if err != nil {
return nil, err
}
pageSize := j.OptionService.GetOrByDefault(ctx, property.CommentPageSize).(int)
pageSize := s.OptionService.GetOrByDefault(ctx, property.CommentPageSize).(int)
commentQuery := param.CommentQuery{}
err = ctx.ShouldBindWith(&commentQuery, binding.CustomFormBinding)
@ -60,19 +60,19 @@ func (j *SheetHandler) ListTopComment(ctx *gin.Context) (interface{}, error) {
commentQuery.PageSize = pageSize
commentQuery.ParentID = util.Int32Ptr(0)
comments, totalCount, err := j.SheetCommentService.Page(ctx, commentQuery, consts.CommentTypeSheet)
comments, totalCount, err := s.SheetCommentService.Page(ctx, commentQuery, consts.CommentTypeSheet)
if err != nil {
return nil, err
}
_ = j.SheetCommentAssembler.ClearSensitiveField(ctx, comments)
commenVOs, err := j.SheetCommentAssembler.ConvertToWithHasChildren(ctx, comments)
_ = s.SheetCommentAssembler.ClearSensitiveField(ctx, comments)
commenVOs, err := s.SheetCommentAssembler.ConvertToWithHasChildren(ctx, comments)
if err != nil {
return nil, err
}
return dto.NewPage(commenVOs, totalCount, commentQuery.Page), nil
}
func (j *SheetHandler) ListChildren(ctx *gin.Context) (interface{}, error) {
func (s *SheetHandler) ListChildren(ctx *gin.Context) (interface{}, error) {
sheetID, err := util.ParamInt32(ctx, "sheetID")
if err != nil {
return nil, err
@ -81,20 +81,20 @@ func (j *SheetHandler) ListChildren(ctx *gin.Context) (interface{}, error) {
if err != nil {
return nil, err
}
children, err := j.SheetCommentService.GetChildren(ctx, parentID, sheetID, consts.CommentTypeSheet)
children, err := s.SheetCommentService.GetChildren(ctx, parentID, sheetID, consts.CommentTypeSheet)
if err != nil {
return nil, err
}
_ = j.SheetCommentAssembler.ClearSensitiveField(ctx, children)
return j.SheetCommentAssembler.ConvertToDTOList(ctx, children)
_ = s.SheetCommentAssembler.ClearSensitiveField(ctx, children)
return s.SheetCommentAssembler.ConvertToDTOList(ctx, children)
}
func (p *SheetHandler) ListCommentTree(ctx *gin.Context) (interface{}, error) {
func (s *SheetHandler) ListCommentTree(ctx *gin.Context) (interface{}, error) {
sheetID, err := util.ParamInt32(ctx, "sheetID")
if err != nil {
return nil, err
}
pageSize := p.OptionService.GetOrByDefault(ctx, property.CommentPageSize).(int)
pageSize := s.OptionService.GetOrByDefault(ctx, property.CommentPageSize).(int)
commentQuery := param.CommentQuery{}
err = ctx.ShouldBindWith(&commentQuery, binding.CustomFormBinding)
@ -112,24 +112,24 @@ func (p *SheetHandler) ListCommentTree(ctx *gin.Context) (interface{}, error) {
commentQuery.PageSize = pageSize
commentQuery.ParentID = util.Int32Ptr(0)
allComments, err := p.SheetCommentService.GetByContentID(ctx, sheetID, consts.CommentTypeSheet, commentQuery.Sort)
allComments, err := s.SheetCommentService.GetByContentID(ctx, sheetID, consts.CommentTypeSheet, commentQuery.Sort)
if err != nil {
return nil, err
}
_ = p.SheetCommentAssembler.ClearSensitiveField(ctx, allComments)
commentVOs, total, err := p.SheetCommentAssembler.PageConvertToVOs(ctx, allComments, commentQuery.Page)
_ = s.SheetCommentAssembler.ClearSensitiveField(ctx, allComments)
commentVOs, total, err := s.SheetCommentAssembler.PageConvertToVOs(ctx, allComments, commentQuery.Page)
if err != nil {
return nil, err
}
return dto.NewPage(commentVOs, total, commentQuery.Page), nil
}
func (p *SheetHandler) ListComment(ctx *gin.Context) (interface{}, error) {
func (s *SheetHandler) ListComment(ctx *gin.Context) (interface{}, error) {
sheetID, err := util.ParamInt32(ctx, "sheetID")
if err != nil {
return nil, err
}
pageSize := p.OptionService.GetOrByDefault(ctx, property.CommentPageSize).(int)
pageSize := s.OptionService.GetOrByDefault(ctx, property.CommentPageSize).(int)
commentQuery := param.CommentQuery{}
err = ctx.ShouldBindWith(&commentQuery, binding.CustomFormBinding)
@ -147,21 +147,21 @@ func (p *SheetHandler) ListComment(ctx *gin.Context) (interface{}, error) {
commentQuery.PageSize = pageSize
commentQuery.ParentID = util.Int32Ptr(0)
comments, total, err := p.SheetCommentService.Page(ctx, commentQuery, consts.CommentTypeSheet)
comments, total, err := s.SheetCommentService.Page(ctx, commentQuery, consts.CommentTypeSheet)
if err != nil {
return nil, err
}
_ = p.SheetCommentAssembler.ClearSensitiveField(ctx, comments)
result, err := p.SheetCommentAssembler.ConvertToWithParentVO(ctx, comments)
_ = s.SheetCommentAssembler.ClearSensitiveField(ctx, comments)
result, err := s.SheetCommentAssembler.ConvertToWithParentVO(ctx, comments)
if err != nil {
return nil, err
}
return dto.NewPage(result, total, commentQuery.Page), nil
}
func (p *SheetHandler) CreateComment(ctx *gin.Context) (interface{}, error) {
func (s *SheetHandler) CreateComment(ctx *gin.Context) (interface{}, error) {
comment := param.Comment{}
err := ctx.ShouldBindJSON(&p)
err := ctx.ShouldBindJSON(&comment)
if err != nil {
return nil, err
}
@ -170,9 +170,9 @@ func (p *SheetHandler) CreateComment(ctx *gin.Context) (interface{}, error) {
comment.Content = template.HTMLEscapeString(comment.Content)
comment.Email = template.HTMLEscapeString(comment.Email)
comment.CommentType = consts.CommentTypeSheet
result, err := p.SheetCommentService.CreateBy(ctx, &comment)
result, err := s.SheetCommentService.CreateBy(ctx, &comment)
if err != nil {
return nil, err
}
return p.SheetCommentAssembler.ConvertToDTO(ctx, result)
return s.SheetCommentAssembler.ConvertToDTO(ctx, result)
}

@ -54,20 +54,20 @@ func (c *CategoryAuthentication) Authenticate(ctx context.Context, token string,
if !ok || parentCategory == nil {
return "", nil
}
if parentCategory.Password == "" {
switch parentCategory.Password {
case "":
parentID = parentCategory.ParentID
parentIDs = append(parentIDs, parentID)
} else if parentCategory.Password == password {
case password:
return c.doAuthenticate(ctx, token, parentIDs...)
} else {
default:
return "", xerr.WithMsg(nil, "密码不正确").WithStatus(http.StatusUnauthorized)
}
}
} else if category.Password == password {
return c.doAuthenticate(ctx, token, id)
} else {
return "", xerr.WithMsg(nil, "密码不正确").WithStatus(http.StatusUnauthorized)
}
return "", xerr.WithMsg(nil, "密码不正确").WithStatus(http.StatusUnauthorized)
}
func (c *CategoryAuthentication) IsAuthenticated(ctx context.Context, tokenStr string, id int32) (bool, error) {
@ -83,7 +83,7 @@ func (c *CategoryAuthentication) IsAuthenticated(ctx context.Context, tokenStr s
}
token, err := jwt.ParseWithClaims(tokenStr, &customClaims{}, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return []byte(secret.(string)), nil
})
@ -117,7 +117,7 @@ func (c *CategoryAuthentication) doAuthenticate(ctx context.Context, tokenStr st
if tokenStr != "" {
token, err := jwt.ParseWithClaims(tokenStr, &customClaims{}, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return []byte(secret.(string)), nil
})

@ -75,11 +75,12 @@ func (p *PostAuthentication) Authenticate(ctx context.Context, token string, id
if !ok || parentCategory == nil {
break
}
if parentCategory.Password == "" {
switch parentCategory.Password {
case "":
parentID = parentCategory.ParentID
} else if parentCategory.Password == password {
case password:
return p.doAuthenticate(ctx, token, id)
} else {
default:
break
}
}
@ -107,7 +108,7 @@ func (p *PostAuthentication) IsAuthenticated(ctx context.Context, tokenStr strin
token, err := jwt.ParseWithClaims(tokenStr, &customClaims{}, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return []byte(secret.(string)), nil
})
@ -160,7 +161,7 @@ func (p *PostAuthentication) doAuthenticate(ctx context.Context, tokenStr string
if tokenStr != "" {
token, err := jwt.ParseWithClaims(tokenStr, &customClaims{}, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return []byte(secret.(string)), nil
})

@ -13,7 +13,6 @@ import (
func NewJournalModel(optionService service.OptionService,
themeService service.ThemeService,
journalService service.JournalService,
JournalService service.JournalService,
) *JournalModel {
return &JournalModel{
OptionService: optionService,

@ -13,7 +13,6 @@ import (
func NewPhotoModel(optionService service.OptionService,
themeService service.ThemeService,
photoService service.PhotoService,
PhotoService service.PhotoService,
) *PhotoModel {
return &PhotoModel{
OptionService: optionService,

@ -126,13 +126,13 @@ func (p *PostModel) Content(ctx context.Context, post *entity.Post, token string
if post.MetaKeywords != "" {
model["meta_keywords"] = post.MetaKeywords
} else if len(tags) > 0 {
meta_keywords := strings.Builder{}
meta_keywords.Write([]byte(tags[0].Name))
metaKeywords := strings.Builder{}
metaKeywords.Write([]byte(tags[0].Name))
for _, tag := range tags[1:] {
meta_keywords.Write([]byte(","))
meta_keywords.Write([]byte(tag.Name))
metaKeywords.Write([]byte(","))
metaKeywords.Write([]byte(tag.Name))
}
model["meta_keywords"] = meta_keywords.String()
model["meta_keywords"] = metaKeywords.String()
}
model["is_post"] = true

@ -92,13 +92,13 @@ func (s *SheetModel) Content(ctx context.Context, sheet *entity.Post, token stri
if sheet.MetaKeywords != "" {
model["meta_keywords"] = sheet.MetaKeywords
} else if len(tags) > 0 {
meta_keywords := strings.Builder{}
meta_keywords.Write([]byte(tags[0].Name))
metaKeywords := strings.Builder{}
metaKeywords.Write([]byte(tags[0].Name))
for _, tag := range tags[1:] {
meta_keywords.Write([]byte(","))
meta_keywords.Write([]byte(tag.Name))
metaKeywords.Write([]byte(","))
metaKeywords.Write([]byte(tag.Name))
}
model["meta_keywords"] = meta_keywords.String()
model["meta_keywords"] = metaKeywords.String()
}
s.SheetService.IncreaseVisit(ctx, sheet.ID)

@ -15,7 +15,6 @@ import (
func NewTagModel(optionService service.OptionService,
themeService service.ThemeService,
tagService service.TagService,
TagService service.TagService,
postTagService service.PostTagService,
postAssembler assembler.PostAssembler,
) *TagModel {

@ -54,14 +54,13 @@ func (g *GinLoggerMiddleware) LoggerWithConfig(conf GinLoggerConfig) gin.Handler
}
// Log only when path is not being skipped
if _, ok := skip[path]; !ok {
if raw != "" {
path = path + "?" + raw
}
path = strings.Replace(path, "\n", "", -1)
path = strings.Replace(path, "\r", "", -1)
clientIP := strings.Replace(ctx.ClientIP(), "\n", "", -1)
clientIP = strings.Replace(clientIP, "\r", "", -1)
path = strings.ReplaceAll(path, "\n", "")
path = strings.ReplaceAll(path, "\r", "")
clientIP := strings.ReplaceAll(ctx.ClientIP(), "\n", "")
clientIP = strings.ReplaceAll(clientIP, "\r", "")
logger.Info("[GIN]",
zap.Time("beginTime", start),

@ -31,7 +31,9 @@ func (r *RecoveryMiddleware) RecoveryWithLogger() gin.HandlerFunc {
// Check for a broken connection, as it is not really a
// condition that warrants a panic stack trace.
var brokenPipe bool
//nolint:errorlint
if ne, ok := err.(*net.OpError); ok {
//nolint:errorlint
if se, ok := ne.Err.(*os.SyscallError); ok {
if strings.Contains(strings.ToLower(se.Error()), "broken pipe") || strings.Contains(strings.ToLower(se.Error()), "connection reset by peer") {
brokenPipe = true

@ -45,15 +45,15 @@ func (s *Server) RegisterRouters() {
staticRouter.StaticFS("/themes/", gin.Dir(s.Config.Sonic.ThemeDir, false))
}
{
adminApiRouter := router.Group("/api/admin")
adminApiRouter.Use(s.LogMiddleware.LoggerWithConfig(middleware.GinLoggerConfig{}), s.RecoveryMiddleware.RecoveryWithLogger(), s.InstallRedirectMiddleware.InstallRedirect())
adminApiRouter.GET("/is_installed", s.wrapHandler(s.AdminHandler.IsInstalled))
adminApiRouter.POST("/login/precheck", s.wrapHandler(s.AdminHandler.AuthPreCheck))
adminApiRouter.POST("/login", s.wrapHandler(s.AdminHandler.Auth))
adminApiRouter.POST("/refresh/:refreshToken", s.wrapHandler(s.AdminHandler.RefreshToken))
adminApiRouter.POST("/installations", s.wrapHandler(s.InstallHandler.InstallBlog))
adminAPIRouter := router.Group("/api/admin")
adminAPIRouter.Use(s.LogMiddleware.LoggerWithConfig(middleware.GinLoggerConfig{}), s.RecoveryMiddleware.RecoveryWithLogger(), s.InstallRedirectMiddleware.InstallRedirect())
adminAPIRouter.GET("/is_installed", s.wrapHandler(s.AdminHandler.IsInstalled))
adminAPIRouter.POST("/login/precheck", s.wrapHandler(s.AdminHandler.AuthPreCheck))
adminAPIRouter.POST("/login", s.wrapHandler(s.AdminHandler.Auth))
adminAPIRouter.POST("/refresh/:refreshToken", s.wrapHandler(s.AdminHandler.RefreshToken))
adminAPIRouter.POST("/installations", s.wrapHandler(s.InstallHandler.InstallBlog))
{
authRouter := adminApiRouter.Group("")
authRouter := adminAPIRouter.Group("")
authRouter.Use(s.AuthMiddleware.GetWrapHandler())
authRouter.POST("/logout", s.wrapHandler(s.AdminHandler.LogOut))
authRouter.POST("/password/code", s.wrapHandler(s.AdminHandler.SendResetCode))

@ -27,7 +27,7 @@ import (
type Server struct {
logger *zap.Logger
Config *config.Config
HttpServer *http.Server
HTTPServer *http.Server
Router *gin.Engine
Template *template.Template
AuthMiddleware *middleware.AuthMiddleware
@ -145,7 +145,7 @@ func NewServer(param ServerParams, lifecycle fx.Lifecycle) *Server {
s := &Server{
logger: param.Logger,
Config: param.Config,
HttpServer: httpServer,
HTTPServer: httpServer,
Router: router,
Template: param.Template,
AuthMiddleware: param.AuthMiddleware,
@ -207,7 +207,7 @@ func (s *Server) Run(ctx context.Context) error {
gin.SetMode(gin.DebugMode)
}
go func() {
if err := s.HttpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
if err := s.HTTPServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
// print err info when httpServer start failed
s.logger.Error("unexpected error from ListenAndServe", zap.Error(err))
fmt.Printf("http server start error:%s\n", err.Error())
@ -224,7 +224,7 @@ func (s *Server) wrapHandler(handler wrapperHandler) gin.HandlerFunc {
data, err := handler(ctx)
if err != nil {
s.logger.Error("handler error", zap.Error(err))
status := xerr.GetHttpStatus(err)
status := xerr.GetHTTPStatus(err)
ctx.JSON(status, &dto.BaseDTO{Status: status, Message: xerr.GetMessage(err)})
return
}
@ -286,12 +286,12 @@ func (s *Server) wrapTextHandler(handler wrapperHTMLHandler) gin.HandlerFunc {
}
func (s *Server) handleError(ctx *gin.Context, err error) {
status := xerr.GetHttpStatus(err)
status := xerr.GetHTTPStatus(err)
message := xerr.GetMessage(err)
model := template.Model{}
templateName, _ := s.ThemeService.Render(ctx, strconv.Itoa(status))
t := s.Template.HtmlTemplate.Lookup(templateName)
t := s.Template.HTMLTemplate.Lookup(templateName)
if t == nil {
templateName = "common/error/error"
}

@ -37,7 +37,7 @@ func init() {
}
func Translate(errs validator.ValidationErrors) string {
var errList []string
errList := make([]string, 0, len(errs))
for _, e := range errs {
// can translate each error one at a time.
errList = append(errList, e.Translate(trans))

@ -92,6 +92,6 @@ func CtxFatal(ctx context.Context, msg string, fields ...zap.Field) {
}
func Sync() {
exportUseLogger.Sync()
exportUseSugarLogger.Sync()
_ = exportUseLogger.Sync()
_ = exportUseSugarLogger.Sync()
}

@ -10,7 +10,6 @@ import (
"github.com/go-sonic/sonic/dal"
"github.com/go-sonic/sonic/event"
"github.com/go-sonic/sonic/event/listener"
_ "github.com/go-sonic/sonic/event/listener"
"github.com/go-sonic/sonic/handler"
"github.com/go-sonic/sonic/handler/middleware"
"github.com/go-sonic/sonic/injection"

@ -6,7 +6,7 @@ type Comment struct {
ID int32 `json:"id"`
Author string `json:"author"`
Email string `json:"email"`
IpAddress string `json:"ipAddress"`
IPAddress string `json:"ipAddress"`
AuthorURL string `json:"authorUrl"`
GravatarMD5 string `json:"gravatarMd5"`
Content string `json:"content"`

@ -4,5 +4,5 @@ type Install struct {
User
Locale string `json:"locale"`
Title string `json:"title" binding:"required"`
Url string `json:"url"`
URL string `json:"url"`
}

@ -222,7 +222,7 @@ var TencentCosBucketName = Property{
Kind: reflect.String,
}
var TencentCosSecretId = Property{
var TencentCosSecretID = Property{
DefaultValue: "",
KeyValue: "cos_tencent_secret_id",
Kind: reflect.String,

@ -43,7 +43,7 @@ var AllProperty = []Property{
BlogLocale,
BlogTitle,
BlogLogo,
BlogUrl,
BlogURL,
BlogFavicon,
BlogFooterInfo,
EmailHost,
@ -84,12 +84,12 @@ var AllProperty = []Property{
RecycledPostCleaningEnabled,
RecycledPostRetentionTime,
RecycledPostRetentionTimeunit,
ApiAccessKey,
APIAccessKey,
CommentGravatarDefault,
CommentNewNeedCheck,
CommentNewNotice,
CommentReplyNotice,
CommentApiEnabled,
CommentAPIEnabled,
CommentPageSize,
CommentContentPlaceholder,
CommentInternalPluginJs,
@ -128,7 +128,7 @@ var AllProperty = []Property{
TencentCosProtocol,
TencentCosRegion,
TencentCosBucketName,
TencentCosSecretId,
TencentCosSecretID,
TencentCosSecretKey,
TencentCosSource,
TencentCosStyleRule,

@ -18,7 +18,7 @@ var (
DefaultValue: "",
Kind: reflect.String,
}
BlogUrl = Property{
BlogURL = Property{
KeyValue: "blog_url",
DefaultValue: "",
Kind: reflect.String,

@ -23,7 +23,7 @@ var (
DefaultValue: false,
Kind: reflect.Bool,
}
CommentApiEnabled = Property{
CommentAPIEnabled = Property{
KeyValue: "comment_api_enabled",
DefaultValue: true,
Kind: reflect.Bool,

@ -28,7 +28,7 @@ var (
KeyValue: "default_editor",
Kind: reflect.String,
}
ApiAccessKey = Property{
APIAccessKey = Property{
DefaultValue: nil,
KeyValue: "api_access_key",
Kind: reflect.String,

@ -14,7 +14,7 @@ var (
}
Theme = Property{
KeyValue: "theme",
DefaultValue: consts.DefaultThemeId,
DefaultValue: consts.DefaultThemeID,
Kind: reflect.String,
}
BirthDay = Property{

@ -4,7 +4,7 @@ import "github.com/go-sonic/sonic/consts"
type MFAFactorAuth struct {
QRImage string `json:"qrImage"`
OptAuthUrl string `json:"optAuthUrl"`
OptAuthURL string `json:"optAuthUrl"`
MFAKey string `json:"mfaKey"`
MFAType consts.MFAType `json:"mfaType"`
}

@ -82,7 +82,7 @@ func (b *baseCommentAssembler) ConvertToDTO(ctx context.Context, comment *entity
ID: comment.ID,
Author: comment.Author,
Email: comment.Email,
IpAddress: comment.IPAddress,
IPAddress: comment.IPAddress,
AuthorURL: comment.AuthorURL,
GravatarMD5: comment.GravatarMd5,
Content: comment.Content,
@ -116,7 +116,7 @@ func (b *baseCommentAssembler) ConvertToDTOList(ctx context.Context, comments []
ID: comment.ID,
Author: comment.Author,
Email: comment.Email,
IpAddress: comment.IPAddress,
IPAddress: comment.IPAddress,
AuthorURL: comment.AuthorURL,
GravatarMD5: comment.GravatarMd5,
Content: comment.Content,

@ -31,6 +31,6 @@ type BackupType string
const (
WholeSite BackupType = "/api/admin/backups/work-dir"
JsonData BackupType = "/api/admin/backups/data"
JSONData BackupType = "/api/admin/backups/data"
Markdown BackupType = "/api/admin/backups/markdown/export"
)

@ -85,7 +85,7 @@ func (a *adminServiceImpl) Auth(ctx context.Context, loginParam param.LoginParam
if err != nil {
return nil, err
}
if a.TwoFactorTOTPMFA.UseMFA(consts.MFAType(user.MfaType)) {
if a.TwoFactorTOTPMFA.UseMFA(user.MfaType) {
if len(loginParam.AuthCode) != 6 {
return nil, xerr.WithMsg(nil, "请输入6位两步验证码").WithStatus(xerr.StatusBadRequest)
}
@ -98,7 +98,7 @@ func (a *adminServiceImpl) Auth(ctx context.Context, loginParam param.LoginParam
LogKey: user.Username,
LogType: consts.LogTypeLoggedIn,
Content: user.Nickname,
IpAddress: util.GetClientIP(ctx),
IPAddress: util.GetClientIP(ctx),
})
return a.buildAuthToken(user), nil
}
@ -120,7 +120,7 @@ func (a *adminServiceImpl) ClearToken(ctx context.Context) error {
LogKey: user.Username,
LogType: consts.LogTypeLoggedOut,
Content: user.Nickname,
IpAddress: util.GetClientIP(ctx),
IPAddress: util.GetClientIP(ctx),
})
return nil
}
@ -226,7 +226,6 @@ func (a *adminServiceImpl) GetLogFiles(ctx context.Context, lineNum int64) (stri
for position > 0 {
if !globalIsPrefix {
position--
_, err = file.Seek(position, 0)
@ -264,7 +263,6 @@ func (a *adminServiceImpl) GetLogFiles(ctx context.Context, lineNum int64) (stri
if linesCount == lineNum {
break
}
}
result := bytes.Buffer{}
result.Grow(linesTotalByteNum)

@ -2,6 +2,7 @@ package impl
import (
"context"
"errors"
"mime/multipart"
"os"
"strings"
@ -16,13 +17,13 @@ import (
"github.com/go-sonic/sonic/model/entity"
"github.com/go-sonic/sonic/model/param"
"github.com/go-sonic/sonic/service"
"github.com/go-sonic/sonic/service/file_storage"
"github.com/go-sonic/sonic/service/storage"
"github.com/go-sonic/sonic/util/xerr"
)
type attachmentServiceImpl struct {
OptionService service.OptionService
FileStorageComposite file_storage.FileStorageComposite
FileStorageComposite storage.FileStorageComposite
}
func (a *attachmentServiceImpl) ConvertToDTOs(ctx context.Context, attachments []*entity.Attachment) ([]*dto.AttachmentDTO, error) {
@ -39,14 +40,14 @@ func (a *attachmentServiceImpl) ConvertToDTOs(ctx context.Context, attachments [
Width: attachment.Width,
Height: attachment.Height,
Size: attachment.Size,
AttachmentType: consts.AttachmentType(attachment.Type),
AttachmentType: attachment.Type,
}
dtos = append(dtos, dto)
path, err := a.FileStorageComposite.GetFileStorage(consts.AttachmentType(attachment.Type)).GetFilePath(ctx, attachment.Path)
path, err := a.FileStorageComposite.GetFileStorage(attachment.Type).GetFilePath(ctx, attachment.Path)
if err != nil {
log.CtxError(ctx, "GetFilePath err", zap.Error(err))
}
thumbPath, err := a.FileStorageComposite.GetFileStorage(consts.AttachmentType(attachment.Type)).GetFilePath(ctx, attachment.ThumbPath)
thumbPath, err := a.FileStorageComposite.GetFileStorage(attachment.Type).GetFilePath(ctx, attachment.ThumbPath)
if err != nil {
log.CtxError(ctx, "GetFilePath err", zap.Error(err))
}
@ -56,7 +57,7 @@ func (a *attachmentServiceImpl) ConvertToDTOs(ctx context.Context, attachments [
return dtos, nil
}
func NewAttachmentService(optionService service.OptionService, fileStorageComposite file_storage.FileStorageComposite) service.AttachmentService {
func NewAttachmentService(optionService service.OptionService, fileStorageComposite storage.FileStorageComposite) service.AttachmentService {
return &attachmentServiceImpl{
FileStorageComposite: fileStorageComposite,
OptionService: optionService,
@ -75,13 +76,13 @@ func (a *attachmentServiceImpl) ConvertToDTO(ctx context.Context, attachment *en
Width: attachment.Width,
Height: attachment.Height,
Size: attachment.Size,
AttachmentType: consts.AttachmentType(attachment.Type),
AttachmentType: attachment.Type,
}
path, err := a.FileStorageComposite.GetFileStorage(consts.AttachmentType(attachment.Type)).GetFilePath(ctx, attachment.Path)
path, err := a.FileStorageComposite.GetFileStorage(attachment.Type).GetFilePath(ctx, attachment.Path)
if err != nil {
return nil, err
}
thumbPath, err := a.FileStorageComposite.GetFileStorage(consts.AttachmentType(attachment.Type)).GetFilePath(ctx, attachment.ThumbPath)
thumbPath, err := a.FileStorageComposite.GetFileStorage(attachment.Type).GetFilePath(ctx, attachment.ThumbPath)
if err != nil {
return nil, err
}
@ -146,7 +147,7 @@ func (a *attachmentServiceImpl) Upload(ctx context.Context, fileHeader *multipar
WithStatus(xerr.StatusBadRequest).
WithMsg("附件路径为 " + attachmentDTO.Path + " 已经存在")
}
if err != nil && err != gorm.ErrRecordNotFound {
if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
return nil, WrapDBErr(err)
}
attachmentEntity := &entity.Attachment{
@ -181,7 +182,7 @@ func (a *attachmentServiceImpl) Delete(ctx context.Context, attachmentID int32)
if err != nil || result.RowsAffected != 1 {
return nil, xerr.WithMsg(err, "delete file failed")
}
fileStorage := a.FileStorageComposite.GetFileStorage(consts.AttachmentType(attachment.Type))
fileStorage := a.FileStorageComposite.GetFileStorage(attachment.Type)
err = fileStorage.Delete(ctx, attachment.FileKey)
if err != nil {
return nil, xerr.WithMsg(err, "delete file failed")
@ -189,10 +190,10 @@ func (a *attachmentServiceImpl) Delete(ctx context.Context, attachmentID int32)
return attachment, nil
}
func (a *attachmentServiceImpl) DeleteBatch(ctx context.Context, IDs []int32) (attachments []*entity.Attachment, err error) {
func (a *attachmentServiceImpl) DeleteBatch(ctx context.Context, ids []int32) (attachments []*entity.Attachment, err error) {
attachments = make([]*entity.Attachment, 0)
var globalErr error
for _, id := range IDs {
for _, id := range ids {
attachment, err := a.Delete(ctx, id)
if err != nil {
globalErr = err

@ -86,11 +86,12 @@ func (b *backupServiceImpl) ListFiles(ctx context.Context, path string, backupTy
return nil, xerr.NoType.Wrap(err).WithMsg("Failed to fetch backups")
}
prefix := ""
if backupType == service.WholeSite {
switch backupType {
case service.WholeSite:
prefix = consts.SonicBackupPrefix
} else if backupType == service.JsonData {
case service.JSONData:
prefix = consts.SonicDataExportPrefix
} else if backupType == service.Markdown {
case service.Markdown:
prefix = consts.SonicBackupMarkdownPrefix
}
err := filepath.WalkDir(path, func(path string, d fs.DirEntry, err error) error {
@ -198,7 +199,7 @@ func (b *backupServiceImpl) ExportData(ctx context.Context) (*dto.BackupDTO, err
if err != nil {
return nil, xerr.NoType.Wrap(err).WithMsg("write to file err")
}
return b.buildBackupDTO(ctx, string(service.JsonData), filepath.Join(backupFilePath, backupFilename))
return b.buildBackupDTO(ctx, string(service.JSONData), filepath.Join(backupFilePath, backupFilename))
}
func (b *backupServiceImpl) ExportMarkdown(ctx context.Context, needFrontMatter bool) (*dto.BackupDTO, error) {

@ -114,11 +114,11 @@ func (b basePostServiceImpl) buildPostFullPath(ctx context.Context, post *entity
return "", err
}
if isEnabled {
blogBaseUrl, err := b.OptionService.GetBlogBaseURL(ctx)
blogBaseURL, err := b.OptionService.GetBlogBaseURL(ctx)
if err != nil {
return "", err
}
fullPath.WriteString(blogBaseUrl)
fullPath.WriteString(blogBaseURL)
}
fullPath.WriteString("/")
switch consts.PostPermalinkType(postPermaLinkType.(string)) {
@ -180,11 +180,11 @@ func (b basePostServiceImpl) buildSheetFullPath(ctx context.Context, sheet *enti
return "", err
}
if isEnabled {
blogBaseUrl, err := b.OptionService.GetBlogBaseURL(ctx)
blogBaseURL, err := b.OptionService.GetBlogBaseURL(ctx)
if err != nil {
return "", err
}
fullPath.WriteString(blogBaseUrl)
fullPath.WriteString(blogBaseURL)
}
fullPath.WriteString("/")
switch consts.SheetPermaLinkType(sheetPermaLinkType.(string)) {
@ -212,7 +212,7 @@ func (b basePostServiceImpl) GetByPostID(ctx context.Context, postID int32) (*en
var summaryPattern = regexp.MustCompile(`[\t\r\n]`)
func (b basePostServiceImpl) GenerateSummary(ctx context.Context, htmlContent string) string {
text := util.CleanHtmlTag(htmlContent)
text := util.CleanHTMLTag(htmlContent)
text = summaryPattern.ReplaceAllString(text, "")
summaryLength := b.OptionService.GetPostSummaryLength(ctx)
end := summaryLength
@ -347,7 +347,6 @@ func (b basePostServiceImpl) CreateOrUpdate(ctx context.Context, post *entity.Po
}
post.Status = status
}
} else {
// update post
slugCount, err := postDAL.WithContext(ctx).Where(postDAL.Slug.Eq(post.Slug), postDAL.ID.Neq(post.ID)).Count()

@ -152,11 +152,11 @@ func (c categoryServiceImpl) ConvertToCategoryDTO(ctx context.Context, e *entity
}
fullPath := strings.Builder{}
if isEnabled {
blogBaseUrl, err := c.OptionService.GetBlogBaseURL(ctx)
blogBaseURL, err := c.OptionService.GetBlogBaseURL(ctx)
if err != nil {
return nil, err
}
fullPath.WriteString(blogBaseUrl)
fullPath.WriteString(blogBaseURL)
}
fullPath.WriteString("/")
categoryPrefix, err := c.OptionService.GetOrByDefaultWithErr(ctx, property.CategoriesPrefix, "categories")
@ -181,7 +181,7 @@ func (c categoryServiceImpl) ConvertToCategoryDTOs(ctx context.Context, categori
if err != nil {
return nil, err
}
blogBaseUrl, err := c.OptionService.GetBlogBaseURL(ctx)
blogBaseURL, err := c.OptionService.GetBlogBaseURL(ctx)
if err != nil {
return nil, err
}
@ -207,7 +207,7 @@ func (c categoryServiceImpl) ConvertToCategoryDTOs(ctx context.Context, categori
fullPath := strings.Builder{}
if isEnabled {
fullPath.WriteString(blogBaseUrl)
fullPath.WriteString(blogBaseURL)
}
fullPath.WriteString("/")
fullPath.WriteString(categoryPrefix.(string))
@ -700,10 +700,8 @@ func (c *categoryUpdateExecutor) refreshPostStatus(ctx context.Context) error {
}
if status == consts.PostStatusIntimate {
needEncryptPostID = append(needEncryptPostID, id)
} else {
if post.Status == consts.PostStatusIntimate && post.Password == "" {
needDecryptPostID = append(needDecryptPostID, id)
}
} else if post.Status == consts.PostStatusIntimate && post.Password == "" {
needDecryptPostID = append(needDecryptPostID, id)
}
}
if len(needEncryptPostID) > 0 {

@ -56,7 +56,7 @@ func (c *clientOptionServiceImpl) getPrivateOption() map[string]struct{} {
property.EmailUsername,
property.EmailPassword,
property.EmailFromName,
property.ApiAccessKey,
property.APIAccessKey,
property.MinioEndpoint,
property.MinioBucketName,
property.MinioAccessKey,
@ -86,7 +86,7 @@ func (c *clientOptionServiceImpl) getPrivateOption() map[string]struct{} {
property.TencentCosProtocol,
property.TencentCosRegion,
property.TencentCosBucketName,
property.TencentCosSecretId,
property.TencentCosSecretID,
property.TencentCosSecretKey,
property.TencentCosSource,
property.TencentCosStyleRule,

@ -319,7 +319,7 @@ func (*baseCommentServiceImpl) CountChildren(ctx context.Context, parentCommentI
}
func (b *baseCommentServiceImpl) GetChildren(ctx context.Context, parentCommentID int32, contentID int32, commentType consts.CommentType) ([]*entity.Comment, error) {
allComments, err := b.GetByContentID(ctx, int32(contentID), commentType, nil)
allComments, err := b.GetByContentID(ctx, contentID, commentType, nil)
if err != nil {
return nil, err
}

@ -2,6 +2,7 @@ package impl
import (
"context"
"errors"
"gorm.io/gorm"
@ -26,7 +27,7 @@ func NewPostCommentService(baseCommentService service.BaseCommentService) servic
func (p postCommentServiceImpl) CreateBy(ctx context.Context, commentParam *param.Comment) (*entity.Comment, error) {
postDAL := dal.GetQueryByCtx(ctx).Post
post, err := postDAL.WithContext(ctx).Where(postDAL.ID.Eq(commentParam.PostID)).First()
if err == gorm.ErrRecordNotFound {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, xerr.WithMsg(nil, "post not found").WithStatus(xerr.StatusBadRequest)
}
if err != nil {

@ -1,6 +1,7 @@
package impl
import (
"errors"
"reflect"
"strings"
"unicode"
@ -16,7 +17,7 @@ func WrapDBErr(err error) error {
if err == nil {
return nil
}
if err == gorm.ErrRecordNotFound {
if errors.Is(err, gorm.ErrRecordNotFound) {
return xerr.NoRecord.Wrap(err).WithMsg("The resource does not exist or has been deleted").WithStatus(xerr.StatusNotFound)
}
return xerr.DB.Wrap(err).WithStatus(xerr.StatusInternalServerError)
@ -100,13 +101,16 @@ func ConvertSort(sorts *param.Sort) ([]*Order, error) {
if len(items) == 2 {
order.Property = UnderscoreName(items[0])
items[1] = strings.ToLower(items[1])
if items[1] == "asc" {
switch items[1] {
case "asc":
order.Asc = true
} else if items[1] == "desc" {
case "desc":
order.Asc = false
} else {
default:
return nil, xerr.WithStatus(nil, xerr.StatusBadRequest).WithMsg("sort parameter error")
}
result = append(result, &order)
}
}

@ -380,7 +380,7 @@ func convertJekyllMetaData(metadata map[string]any, postName string, postDate ti
func convertJekyllContent(metadata map[string]any, content string) string {
lines := strings.Split(content, "\n")
var resultLines []string
resultLines := make([]string, 0, len(lines))
for _, line := range lines {
resultLines = append(resultLines, strings.Trim(line, "\r\n"))
}

@ -2,7 +2,7 @@ package impl
import (
"github.com/go-sonic/sonic/injection"
"github.com/go-sonic/sonic/service/file_storage"
"github.com/go-sonic/sonic/service/storage"
)
func init() {
@ -39,6 +39,6 @@ func init() {
NewThemeService,
NewUserService,
NewExportImport,
file_storage.NewFileStorageComposite,
storage.NewFileStorageComposite,
)
}

@ -110,14 +110,14 @@ func (i installServiceImpl) createDefaultSetting(ctx context.Context, installPar
optionMap[property.IsInstalled.KeyValue] = "true"
optionMap[property.GlobalAbsolutePathEnabled.KeyValue] = "false"
optionMap[property.BlogTitle.KeyValue] = installParam.Title
if installParam.Url == "" {
if installParam.URL == "" {
blogURL, err := i.OptionService.GetBlogBaseURL(ctx)
if err != nil {
return err
}
optionMap[property.BlogUrl.KeyValue] = blogURL
optionMap[property.BlogURL.KeyValue] = blogURL
} else {
optionMap[property.BlogUrl.KeyValue] = installParam.Url
optionMap[property.BlogURL.KeyValue] = installParam.URL
}
if installParam.Locale == "" {
optionMap[property.BlogLocale.KeyValue] = property.BlogLocale.DefaultValue.(string)

@ -3,7 +3,6 @@ package impl
import (
"context"
"github.com/go-sonic/sonic/consts"
"github.com/go-sonic/sonic/dal"
"github.com/go-sonic/sonic/model/dto"
"github.com/go-sonic/sonic/model/entity"
@ -45,7 +44,7 @@ func (l *logServiceImpl) ConvertToDTO(log *entity.Log) *dto.Log {
return &dto.Log{
ID: log.ID,
LogKey: log.LogKey,
LogType: consts.LogType(log.Type),
LogType: log.Type,
Content: log.Content,
IPAddress: log.IPAddress,
CreateTime: log.CreateTime.UnixMilli(),

@ -68,13 +68,13 @@ func (o *optionServiceImpl) GetPostSummaryLength(ctx context.Context) int {
func (o *optionServiceImpl) GetPostSort(ctx context.Context) param.Sort {
p := property.IndexSort
value, err := o.getFromCacheMissFromDB(ctx, p)
var sort string
sort := p.DefaultValue.(string)
//nolint:gocritic
if xerr.GetType(err) == xerr.NoRecord {
o.Cache.SetDefault(p.KeyValue, p.DefaultValue)
sort = p.DefaultValue.(string)
} else if err != nil {
log.CtxErrorf(ctx, "query option err=%v", err)
sort = p.DefaultValue.(string)
} else {
sort = value.(string)
}
@ -88,10 +88,10 @@ func (o *optionServiceImpl) GetIndexPageSize(ctx context.Context) int {
value, err := o.getFromCacheMissFromDB(ctx, p)
if xerr.GetType(err) == xerr.NoRecord {
o.Cache.SetDefault(p.KeyValue, p.DefaultValue)
return int(p.DefaultValue.(int))
return p.DefaultValue.(int)
} else if err != nil {
log.CtxErrorf(ctx, "query option err=%v", err)
return int(p.DefaultValue.(int))
return p.DefaultValue.(int)
}
return value.(int)
}
@ -121,7 +121,7 @@ func (o *optionServiceImpl) GetOrByDefaultWithErr(ctx context.Context, p propert
}
func (o *optionServiceImpl) GetBlogBaseURL(ctx context.Context) (string, error) {
blogURL, err := o.GetOrByDefaultWithErr(ctx, property.BlogUrl, "")
blogURL, err := o.GetOrByDefaultWithErr(ctx, property.BlogURL, "")
if err != nil {
return "", err
}
@ -364,7 +364,7 @@ func (o *optionServiceImpl) GetJournalPrefix(ctx context.Context) (string, error
return value.(string), nil
}
func (o *optionServiceImpl) GetActivatedThemeId(ctx context.Context) (string, error) {
func (o *optionServiceImpl) GetActivatedThemeID(ctx context.Context) (string, error) {
p := property.Theme
value, err := o.getFromCacheMissFromDB(ctx, p)
if xerr.GetType(err) == xerr.NoRecord {

@ -3,6 +3,7 @@ package impl
import (
"context"
"database/sql/driver"
"errors"
"net/url"
"strconv"
"strings"
@ -116,7 +117,7 @@ func (p postServiceImpl) Create(ctx context.Context, postParam *param.Post) (*en
LogKey: strconv.Itoa(int(post.ID)),
LogType: consts.LogTypePostPublished,
Content: post.Title,
IpAddress: util.GetClientIP(ctx),
IPAddress: util.GetClientIP(ctx),
})
return post, nil
}
@ -147,7 +148,7 @@ func (p postServiceImpl) Update(ctx context.Context, postID int32, postParam *pa
LogKey: strconv.Itoa(int(post.ID)),
LogType: consts.LogTypePostEdited,
Content: post.Title,
IpAddress: util.GetClientIP(ctx),
IPAddress: util.GetClientIP(ctx),
})
return post, nil
}
@ -181,7 +182,7 @@ func (p postServiceImpl) ConvertParam(ctx context.Context, postParam *param.Post
post.UpdateTime = util.TimePtr(time.UnixMilli(*postParam.UpdateTime))
}
post.WordCount = util.HtmlFormatWordCount(post.FormatContent)
post.WordCount = util.HTMLFormatWordCount(post.FormatContent)
if postParam.Slug == "" {
post.Slug = util.Slug(postParam.Title)
} else {
@ -262,25 +263,24 @@ func (p postServiceImpl) GetPrevPosts(ctx context.Context, post *entity.Post, si
postDAL := dal.GetQueryByCtx(ctx).Post
postDO := postDAL.WithContext(ctx).Where(postDAL.Status.Eq(consts.PostStatusPublished))
if postSort == "createTime" {
switch postSort {
case "createTime":
postDO = postDO.Where(postDAL.CreateTime.Gt(post.CreateTime)).Order(postDAL.CreateTime)
} else if postSort == "editTime" {
var editTime time.Time
if post.EditTime == nil {
editTime = post.CreateTime
} else {
case "editTime":
editTime := post.CreateTime
if post.EditTime != nil {
editTime = *post.EditTime
}
postDO = postDO.Where(postDAL.EditTime.Gt(editTime)).Order(postDAL.EditTime)
} else if postSort == "visits" {
case "visits":
postDO = postDO.Where(postDAL.Visits.Gt(post.Visits)).Order(postDAL.EditTime)
} else {
default:
return nil, nil
}
posts, err := postDO.Find()
if err != nil {
if err == gorm.ErrRecordNotFound {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
return nil, WrapDBErr(err)
@ -293,19 +293,18 @@ func (p postServiceImpl) GetNextPosts(ctx context.Context, post *entity.Post, si
postDAL := dal.GetQueryByCtx(ctx).Post
postDO := postDAL.WithContext(ctx).Where(postDAL.Status.Eq(consts.PostStatusPublished))
if postSort == "createTime" {
switch postSort {
case "createTime":
postDO = postDO.Where(postDAL.CreateTime.Lt(post.CreateTime)).Order(postDAL.CreateTime.Desc())
} else if postSort == "editTime" {
var editTime time.Time
if post.EditTime == nil {
editTime = post.CreateTime
} else {
case "editTime":
editTime := post.CreateTime
if post.EditTime != nil {
editTime = *post.EditTime
}
postDO = postDO.Where(postDAL.EditTime.Lt(editTime)).Order(postDAL.EditTime.Desc())
} else if postSort == "visits" {
case "visits":
postDO = postDO.Where(postDAL.Visits.Lt(post.Visits)).Order(postDAL.EditTime.Desc())
} else {
default:
return nil, nil
}

@ -96,7 +96,7 @@ func (s sheetServiceImpl) ConvertParam(ctx context.Context, sheetParam *param.Sh
sheet.EditorType = consts.EditorTypeMarkdown
}
sheet.WordCount = util.HtmlFormatWordCount(sheet.FormatContent)
sheet.WordCount = util.HTMLFormatWordCount(sheet.FormatContent)
if sheetParam.Slug == "" {
sheet.Slug = util.Slug(sheetParam.Title)
} else {
@ -135,7 +135,7 @@ func (s sheetServiceImpl) Update(ctx context.Context, sheetID int32, sheetParam
LogKey: strconv.Itoa(int(sheet.ID)),
LogType: consts.LogTypeSheetEdited,
Content: sheet.Title,
IpAddress: util.GetClientIP(ctx),
IPAddress: util.GetClientIP(ctx),
})
return sheet, nil
}

@ -142,11 +142,11 @@ func (t tagServiceImpl) ConvertToDTO(ctx context.Context, tag *entity.Tag) (*dto
return nil, err
}
if isEnabled {
blogBaseUrl, err := t.OptionService.GetBlogBaseURL(ctx)
blogBaseURL, err := t.OptionService.GetBlogBaseURL(ctx)
if err != nil {
return nil, err
}
fullPath.WriteString(blogBaseUrl)
fullPath.WriteString(blogBaseURL)
}
fullPath.WriteString("/")
@ -171,9 +171,9 @@ func (t tagServiceImpl) ConvertToDTOs(ctx context.Context, tags []*entity.Tag) (
if err != nil {
return nil, err
}
var blogBaseUrl string
var blogBaseURL string
if isEnabled {
blogBaseUrl, err = t.OptionService.GetBlogBaseURL(ctx)
blogBaseURL, err = t.OptionService.GetBlogBaseURL(ctx)
if err != nil {
return nil, err
}
@ -191,7 +191,7 @@ func (t tagServiceImpl) ConvertToDTOs(ctx context.Context, tags []*entity.Tag) (
for _, tag := range tags {
fullPath := strings.Builder{}
if isEnabled {
fullPath.WriteString(blogBaseUrl)
fullPath.WriteString(blogBaseURL)
}
fullPath.WriteString("/")
fullPath.WriteString(tagPrefix.(string))

@ -42,7 +42,7 @@ func NewThemeService(optionService service.OptionService, config *config.Config,
}
func (t *themeServiceImpl) GetActivateTheme(ctx context.Context) (*dto.ThemeProperty, error) {
activatedThemeID, err := t.OptionService.GetActivatedThemeId(ctx)
activatedThemeID, err := t.OptionService.GetActivatedThemeID(ctx)
if err != nil {
return nil, err
}
@ -57,7 +57,7 @@ func (t *themeServiceImpl) GetThemeByID(ctx context.Context, themeID string) (*d
if themeProperty == nil {
return nil, xerr.WithStatus(nil, xerr.StatusBadRequest).WithMsg(themeID + " not exist")
}
activatedThemeID, err := t.OptionService.GetActivatedThemeId(ctx)
activatedThemeID, err := t.OptionService.GetActivatedThemeID(ctx)
if err != nil {
return nil, err
}
@ -72,7 +72,7 @@ func (t *themeServiceImpl) ListAllTheme(ctx context.Context) ([]*dto.ThemeProper
if err != nil {
return nil, err
}
activatedThemeID, err := t.OptionService.GetActivatedThemeId(ctx)
activatedThemeID, err := t.OptionService.GetActivatedThemeID(ctx)
if err != nil {
return nil, err
}
@ -351,7 +351,7 @@ func (t *themeServiceImpl) SaveThemeSettings(ctx context.Context, themeID string
}
func (t *themeServiceImpl) DeleteThemeSettings(ctx context.Context, themeID string) error {
activatedThemeID, err := t.OptionService.GetActivatedThemeId(ctx)
activatedThemeID, err := t.OptionService.GetActivatedThemeID(ctx)
if err != nil {
return err
}
@ -365,7 +365,7 @@ func (t *themeServiceImpl) DeleteThemeSettings(ctx context.Context, themeID stri
}
func (t *themeServiceImpl) DeleteTheme(ctx context.Context, themeID string, deleteSettings bool) error {
activatedThemeID, err := t.OptionService.GetActivatedThemeId(ctx)
activatedThemeID, err := t.OptionService.GetActivatedThemeID(ctx)
if err != nil {
return err
}
@ -420,7 +420,7 @@ func (t *themeServiceImpl) ReloadTheme(ctx context.Context) error {
}
func (t *themeServiceImpl) TemplateExist(ctx context.Context, template string) (bool, error) {
activatedThemeID, err := t.OptionService.GetActivatedThemeId(ctx)
activatedThemeID, err := t.OptionService.GetActivatedThemeID(ctx)
if err != nil {
return false, err
}
@ -462,7 +462,7 @@ func (t *themeServiceImpl) addTheme(ctx context.Context, themeProperty *dto.Them
}
func (t *themeServiceImpl) Render(ctx context.Context, name string) (string, error) {
activatedThemeID, err := t.OptionService.GetActivatedThemeId(ctx)
activatedThemeID, err := t.OptionService.GetActivatedThemeID(ctx)
if err != nil {
return "", err
}

@ -21,7 +21,7 @@ type OptionService interface {
GetLinksPrefix(ctx context.Context) (string, error)
GetPhotoPrefix(ctx context.Context) (string, error)
GetJournalPrefix(ctx context.Context) (string, error)
GetActivatedThemeId(ctx context.Context) (string, error)
GetActivatedThemeID(ctx context.Context) (string, error)
GetPostPermalinkType(ctx context.Context) (consts.PostPermalinkType, error)
GetSheetPermalinkType(ctx context.Context) (consts.SheetPermaLinkType, error)
GetIndexPageSize(ctx context.Context) int

@ -1,4 +1,4 @@
package file_storage_impl
package filestorageimpl
import (
"context"

@ -1,4 +1,4 @@
package file_storage_impl
package filestorageimpl
import (
"context"

@ -1,4 +1,4 @@
package file_storage_impl
package filestorageimpl
import (
"path/filepath"

@ -1,4 +1,4 @@
package file_storage_impl
package filestorageimpl
import "github.com/go-sonic/sonic/injection"

@ -1,4 +1,4 @@
package file_storage_impl
package filestorageimpl
import (
"context"
@ -165,12 +165,12 @@ func (l *LocalFileStorage) GetAttachmentType() consts.AttachmentType {
func (l *LocalFileStorage) GetFilePath(ctx context.Context, relativePath string) (string, error) {
isEnabled, _ := l.OptionService.IsEnabledAbsolutePath(ctx)
var blogBaseUrl string
var blogBaseURL string
if isEnabled {
blogBaseUrl, _ = l.OptionService.GetBlogBaseURL(ctx)
blogBaseURL, _ = l.OptionService.GetBlogBaseURL(ctx)
}
fullPath, _ := url.JoinPath(blogBaseUrl, relativePath)
if blogBaseUrl == "" {
fullPath, _ := url.JoinPath(blogBaseURL, relativePath)
if blogBaseURL == "" {
fullPath, _ = url.JoinPath("/", relativePath)
}
fullPath, _ = url.PathUnescape(fullPath)

@ -1,4 +1,4 @@
package file_storage_impl
package filestorageimpl
import (
"context"

@ -1,4 +1,4 @@
package file_storage_impl
package filestorageimpl
import (
"net/url"

@ -1,4 +1,4 @@
package file_storage
package storage
import (
"context"
@ -6,7 +6,7 @@ import (
"github.com/go-sonic/sonic/consts"
"github.com/go-sonic/sonic/model/dto"
"github.com/go-sonic/sonic/service/file_storage/file_storage_impl"
storageimpl "github.com/go-sonic/sonic/service/storage/impl"
)
type FileStorage interface {
@ -20,12 +20,12 @@ type FileStorageComposite interface {
GetFileStorage(storageType consts.AttachmentType) FileStorage
}
type fileStorageComposite struct {
localStorage *file_storage_impl.LocalFileStorage
minio *file_storage_impl.MinIO
aliyunOSS *file_storage_impl.Aliyun
localStorage *storageimpl.LocalFileStorage
minio *storageimpl.MinIO
aliyunOSS *storageimpl.Aliyun
}
func NewFileStorageComposite(localStorage *file_storage_impl.LocalFileStorage, minio *file_storage_impl.MinIO, aliyun *file_storage_impl.Aliyun) FileStorageComposite {
func NewFileStorageComposite(localStorage *storageimpl.LocalFileStorage, minio *storageimpl.MinIO, aliyun *storageimpl.Aliyun) FileStorageComposite {
return &fileStorageComposite{
localStorage: localStorage,
minio: minio,

@ -48,15 +48,20 @@ func (s *propertyScannerImpl) GetThemeByThemeID(ctx context.Context, themeID str
return nil, nil
}
func (s *propertyScannerImpl) ListAll(ctx context.Context, themeRootPath string) ([]*dto.ThemeProperty, error) {
func (s *propertyScannerImpl) ListAll(ctx context.Context, themeRootPath string) (themes []*dto.ThemeProperty, err error) {
themeRootDir, err := os.Open(themeRootPath)
defer themeRootDir.Close()
if err != nil {
return nil, xerr.NoType.Wrap(err)
}
defer func() {
_ = themeRootDir.Close()
}()
themeDirs, err := themeRootDir.ReadDir(0)
result := make([]*dto.ThemeProperty, 0)
if err != nil {
return
}
for _, themeDir := range themeDirs {
if themeDir.IsDir() {
@ -64,11 +69,11 @@ func (s *propertyScannerImpl) ListAll(ctx context.Context, themeRootPath string)
if err != nil {
return nil, err
}
result = append(result, themeProperty)
themes = append(themes, themeProperty)
}
}
return result, nil
return
}
func (s *propertyScannerImpl) ReadThemeProperty(ctx context.Context, themePath string) (*dto.ThemeProperty, error) {
@ -79,10 +84,11 @@ func (s *propertyScannerImpl) ReadThemeProperty(ctx context.Context, themePath s
)
for _, themePropertyFilename := range consts.ThemePropertyFilenames {
themePropertyFile, err = os.Open(filepath.Join(themePath, themePropertyFilename))
defer themePropertyFile.Close()
if os.IsNotExist(err) {
continue
}
defer themePropertyFile.Close()
fileStat, err = themePropertyFile.Stat()
if err != nil {
continue
@ -107,7 +113,7 @@ func (s *propertyScannerImpl) ReadThemeProperty(ctx context.Context, themePath s
themeProperty.ThemePath = themePath
themeProperty.FolderName = filepath.Base(themePath)
themeProperty.Activated = false
hasOptions, _ := s.hasSettingFile(ctx, themePath)
hasOptions, _ := s.hasSettingFile(themePath)
themeProperty.HasOptions = hasOptions
screenshotFilename, err := s.GetThemeScreenshotAbsPath(ctx, themePath)
if err != nil {
@ -128,10 +134,12 @@ func (s *propertyScannerImpl) UnmarshalProperty(ctx context.Context, themeProper
func (s *propertyScannerImpl) GetThemeScreenshotAbsPath(ctx context.Context, themePath string) (string, error) {
themeDir, err := os.Open(themePath)
defer themeDir.Close()
if err != nil {
return "", xerr.NoType.Wrapf(err, "open theme path error themePath=%s", themePath)
}
defer themeDir.Close()
themeFiles, err := themeDir.ReadDir(0)
if err != nil {
return "", xerr.NoType.Wrapf(err, "read theme file error themePath=%s", themePath)
@ -150,7 +158,7 @@ func (s *propertyScannerImpl) GetThemeScreenshotAbsPath(ctx context.Context, the
return "", nil
}
func (s *propertyScannerImpl) hasSettingFile(ctx context.Context, themePath string) (bool, error) {
func (s *propertyScannerImpl) hasSettingFile(themePath string) (bool, error) {
var (
err error
themeSettingFileInfo os.FileInfo
@ -180,10 +188,12 @@ func (s *propertyScannerImpl) ReadThemeConfig(ctx context.Context, themePath str
)
for _, themeSettingFilename := range consts.ThemeSettingFilenames {
themeSettingFile, err = os.Open(filepath.Join(themePath, themeSettingFilename))
defer themeSettingFile.Close()
if os.IsNotExist(err) {
continue
}
defer themeSettingFile.Close()
fileStat, err = themeSettingFile.Stat()
if err != nil {
continue

@ -2,6 +2,7 @@ package theme
import (
"context"
"errors"
"io"
"mime/multipart"
"os"
@ -54,7 +55,7 @@ func (m *multipartZipThemeFetcherImpl) FetchTheme(ctx context.Context, file inte
}
diskFile, err := os.OpenFile(diskFilePath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o444)
if err != nil && err != os.ErrExist {
if !errors.Is(err, os.ErrExist) {
return nil, xerr.WithStatus(err, xerr.StatusInternalServerError).WithMsg("create file error")
}
defer diskFile.Close()

@ -35,7 +35,7 @@ func RegisterPostFunc(template *template.Template, postService service.PostServi
p.addGetPostCount()
p.addGetPostArchiveYear()
p.addGetPostArchiveMonth()
p.addListPostByCategoryId()
p.addListPostByCategoryID()
p.addListPostByCategorySlug()
p.addListPostByTagID()
p.addListPostByTagSlug()
@ -94,8 +94,8 @@ func (p *postExtension) addGetPostArchiveMonth() {
p.Template.AddFunc("listYearArchives", getPostArchiveMonthFunc)
}
func (p *postExtension) addListPostByCategoryId() {
listPostByCategoryId := func(categoryID int32) ([]*vo.Post, error) {
func (p *postExtension) addListPostByCategoryID() {
listPostByCategoryID := func(categoryID int32) ([]*vo.Post, error) {
ctx := context.Background()
posts, err := p.PostCategoryService.ListByCategoryID(ctx, categoryID, consts.PostStatusPublished)
if err != nil {
@ -103,7 +103,7 @@ func (p *postExtension) addListPostByCategoryId() {
}
return p.PostAssembler.ConvertToListVO(ctx, posts)
}
p.Template.AddFunc("listPostByCategoryID", listPostByCategoryId)
p.Template.AddFunc("listPostByCategoryID", listPostByCategoryID)
}
func (p *postExtension) addListPostByCategorySlug() {

@ -22,10 +22,7 @@ func RegisterToolFunc(template *template.Template) {
// addRainbow 彩虹分页算法
func (t *toolExtension) addRainbow() {
rainbowPage := func(page, total, display int) []int {
return util.RainbowPage(page, total, display)
}
t.Template.AddFunc("rainbowPage", rainbowPage)
t.Template.AddFunc("rainbowPage", util.RainbowPage)
}
func (t *toolExtension) addRandom() {

@ -19,7 +19,7 @@ import (
)
type Template struct {
HtmlTemplate *htmlTemplate.Template
HTMLTemplate *htmlTemplate.Template
TextTemplate *template.Template
sharedVariable map[string]any
lock sync.RWMutex
@ -59,8 +59,7 @@ func (t *Template) Load(paths []string) error {
t.paths = paths
filenames := make([]string, 0)
for _, templateDir := range paths {
err := filepath.Walk(templateDir, func(path string, info fs.FileInfo, err error) error {
err := filepath.Walk(templateDir, func(path string, _ fs.FileInfo, _ error) error {
if filepath.Ext(path) == ".tmpl" {
filenames = append(filenames, path)
if err := t.watcher.Add(path); err != nil {
@ -84,7 +83,7 @@ func (t *Template) Load(paths []string) error {
return xerr.WithMsg(err, "parse template err").WithStatus(xerr.StatusInternalServerError)
}
t.TextTemplate = tt
t.HtmlTemplate = ht
t.HTMLTemplate = ht
return nil
}
@ -95,51 +94,35 @@ func (t *Template) SetSharedVariable(name string, value interface{}) {
}
func (t *Template) Execute(wr io.Writer, data Model) error {
dataMap, err := t.wrapData(data)
if err != nil {
return err
}
return t.HtmlTemplate.Execute(wr, dataMap)
return t.HTMLTemplate.Execute(wr, t.wrapData(data))
}
func (t *Template) ExecuteTemplate(wr io.Writer, name string, data Model) error {
dataMap, err := t.wrapData(data)
if err != nil {
return err
}
return t.HtmlTemplate.ExecuteTemplate(wr, name, dataMap)
return t.HTMLTemplate.ExecuteTemplate(wr, name, t.wrapData(data))
}
func (t *Template) ExecuteText(wr io.Writer, data Model) error {
dataMap, err := t.wrapData(data)
if err != nil {
return err
}
return t.TextTemplate.Execute(wr, dataMap)
return t.TextTemplate.Execute(wr, t.wrapData(data))
}
func (t *Template) ExecuteTextTemplate(wr io.Writer, name string, data Model) error {
dataMap, err := t.wrapData(data)
if err != nil {
return err
}
return t.TextTemplate.ExecuteTemplate(wr, name, dataMap)
return t.TextTemplate.ExecuteTemplate(wr, name, t.wrapData(data))
}
func (t *Template) wrapData(data Model) (map[string]any, error) {
func (t *Template) wrapData(data Model) map[string]any {
if data == nil {
return nil, nil
return nil
}
t.lock.RLock()
defer t.lock.RUnlock()
data.MergeAttributes(t.sharedVariable)
data["now"] = time.Now()
return data, nil
return data
}
func (t *Template) AddFunc(name string, fn interface{}) {
if t.HtmlTemplate != nil {
if t.HTMLTemplate != nil {
panic("the template has been parsed")
}
t.funcMap[name] = fn

@ -18,13 +18,15 @@ func (t *Template) Watch() {
continue
}
if event.Op&fsnotify.Write == fsnotify.Write {
switch {
case event.Op&fsnotify.Write == fsnotify.Write:
t.logger.Info("Write file:", zap.String("file", event.Name))
} else if event.Op&fsnotify.Create == fsnotify.Create {
case event.Op&fsnotify.Create == fsnotify.Create:
t.logger.Info("Create file:", zap.String("file", event.Name))
} else {
default:
continue
}
err := t.Reload([]string{event.Name})
if err != nil {
t.logger.Error("reload template error", zap.Error(err))

@ -32,7 +32,7 @@ func CompositeURL(urls ...string) string {
var htmlRegexp = regexp.MustCompile(`(<[^<]*?>)|(<[\s]*?/[^<]*?>)|(<[^<]*?/[\s]*?>)`)
func CleanHtmlTag(htmlContent string) string {
func CleanHTMLTag(htmlContent string) string {
if htmlContent == "" {
return ""
}
@ -41,7 +41,7 @@ func CleanHtmlTag(htmlContent string) string {
var blankRegexp = regexp.MustCompile(`\s`)
func HtmlFormatWordCount(html string) int64 {
text := CleanHtmlTag(html)
func HTMLFormatWordCount(html string) int64 {
text := CleanHTMLTag(html)
return int64(utf8.RuneCountInString(text) - len(blankRegexp.FindSubmatchIndex(StringToBytes(text))))
}

@ -48,7 +48,7 @@ func Md5Hex(str string) string {
}
func MapKeyToArray[K comparable, V any](m map[K]V) []K {
var values []K
values := make([]K, 0, len(m))
for k := range m {
values = append(values, k)

@ -18,14 +18,14 @@ func ZipFile(dst string, srcs ...string) (err error) {
return xerr.NoType.Wrap(err).WithMsg("create zip file err")
}
defer func() {
if err := fw.Close(); err != nil {
if err = fw.Close(); err != nil {
err = xerr.NoType.Wrap(err).WithMsg("close file")
}
}()
// 通过 fw 来创建 zip.Write
zw := zip.NewWriter(fw)
defer func() {
if err := zw.Close(); err != nil {
if err = zw.Close(); err != nil {
err = xerr.NoType.Wrap(err).WithMsg("close zip file")
}
}()
@ -69,10 +69,10 @@ func ZipFile(dst string, srcs ...string) (err error) {
// 打开要压缩的文件
fr, err := os.Open(path)
defer fr.Close()
if err != nil {
return
}
defer fr.Close()
// 将打开的文件 Copy 到 w
_, err = io.Copy(w, fr)
@ -91,16 +91,14 @@ func ZipFile(dst string, srcs ...string) (err error) {
}
func Unzip(src string, dest string) ([]string, error) {
var filenames []string
r, err := zip.OpenReader(src)
if err != nil {
return filenames, err
return nil, err
}
defer r.Close()
filenames := make([]string, 0, len(r.File))
for _, f := range r.File {
// Store filename/path for returning and using later on
fpath := filepath.Join(dest, f.Name)
@ -113,7 +111,10 @@ func Unzip(src string, dest string) ([]string, error) {
if f.FileInfo().IsDir() {
// Make Folder
os.MkdirAll(fpath, os.ModePerm)
err := os.MkdirAll(fpath, os.ModePerm)
if err != nil {
return nil, xerr.WithStatus(err, xerr.StatusInternalServerError)
}
continue
}
@ -148,10 +149,8 @@ func Unzip(src string, dest string) ([]string, error) {
func CopyDir(srcPath, desPath string) error {
if srcInfo, err := os.Stat(srcPath); err != nil {
return err
} else {
if !srcInfo.IsDir() {
return xerr.WithMsg(nil, "src is not dir")
}
} else if !srcInfo.IsDir() {
return xerr.WithMsg(nil, "src is not dir")
}
if err := MakeDir(desPath); err != nil {
@ -159,10 +158,8 @@ func CopyDir(srcPath, desPath string) error {
}
if desInfo, err := os.Stat(desPath); err != nil {
return err
} else {
if !desInfo.IsDir() {
return xerr.WithMsg(nil, "dest is not dir")
}
} else if !desInfo.IsDir() {
return xerr.WithMsg(nil, "dest is not dir")
}
if strings.TrimSpace(srcPath) == strings.TrimSpace(desPath) {
@ -178,14 +175,14 @@ func CopyDir(srcPath, desPath string) error {
return nil
}
destNewPath := strings.Replace(path, srcPath, desPath, -1)
destNewPath := strings.ReplaceAll(path, srcPath, desPath)
if !f.IsDir() {
CopyFile(path, destNewPath)
} else {
if !FileIsExisted(destNewPath) {
return MakeDir(destNewPath)
if _, err = CopyFile(path, destNewPath); err != nil {
return err
}
} else if !FileIsExisted(destNewPath) {
return MakeDir(destNewPath)
}
return nil

@ -73,16 +73,17 @@ func (ce *customError) Format(s fmt.State, verb rune) {
case 'v':
if s.Flag('+') {
fmt.Fprintf(s, "%+v\n", ce.Cause())
io.WriteString(s, ce.msg)
_, _ = io.WriteString(s, ce.msg)
return
}
fallthrough
case 's', 'q':
io.WriteString(s, ce.Error())
_, _ = io.WriteString(s, ce.Error())
}
}
func WithStatus(err error, status int) *customError {
//nolint:errorlint
ee, ok := err.(*customError)
if ok {
return &customError{errorType: ee.errorType, cause: ee, httpStatus: status}
@ -91,6 +92,7 @@ func WithStatus(err error, status int) *customError {
}
func WithMsg(err error, msg string) *customError {
//nolint:errorlint
ee, ok := err.(*customError)
if ok {
return &customError{errorType: ee.errorType, cause: ee, httpStatus: -1, msg: msg}
@ -99,6 +101,7 @@ func WithMsg(err error, msg string) *customError {
}
func WithErrMsgf(err error, errMsg string, args ...interface{}) *customError {
//nolint:errorlint
ee, ok := err.(*customError)
if ok {
return &customError{errorType: ee.errorType, cause: err, httpStatus: -1, errMsg: fmt.Sprintf(errMsg, args...)}
@ -120,14 +123,16 @@ func (ce *customError) WithMsg(msg string) *customError {
// GetType returns the error type
func GetType(err error) ErrorType {
//nolint:errorlint
if ee, ok := err.(*customError); ok {
return ee.errorType
}
return NoType
}
func GetHttpStatus(err error) int {
func GetHTTPStatus(err error) int {
for err != nil {
//nolint:errorlint
if e, ok := err.(*customError); ok {
if e.httpStatus != -1 {
return e.httpStatus
@ -143,6 +148,7 @@ func GetHttpStatus(err error) int {
func GetMessage(err error) string {
for err != nil {
//nolint:errorlint
if e, ok := err.(*customError); ok {
if e.msg != "" {
return e.msg

@ -11,17 +11,20 @@ func RainbowPage(page, total, display int) []int {
if total < display {
length = total
}
//nolint:gosimple
result := make([]int, length, length)
if total >= display {
if page <= left {
switch {
case page <= left:
for i := 0; i < length; i++ {
result[i] = i + 1
}
} else if page > total-right {
case page > total-right:
for i := 0; i < length; i++ {
result[i] = i + total - display + 1
}
} else {
default:
for i := 0; i < length; i++ {
if isEven {
result[i] = i + page - length + 1

@ -73,16 +73,17 @@ func (ce *customError) Format(s fmt.State, verb rune) {
case 'v':
if s.Flag('+') {
fmt.Fprintf(s, "%+v\n", ce.Cause())
io.WriteString(s, ce.msg)
_, _ = io.WriteString(s, ce.msg)
return
}
fallthrough
case 's', 'q':
io.WriteString(s, ce.Error())
_, _ = io.WriteString(s, ce.Error())
}
}
func WithStatus(err error, status int) *customError {
//nolint:errorlint
ee, ok := err.(*customError)
if ok {
return &customError{errorType: ee.errorType, cause: ee, httpStatus: status}
@ -91,6 +92,7 @@ func WithStatus(err error, status int) *customError {
}
func WithMsg(err error, msg string) *customError {
//nolint:errorlint
ee, ok := err.(*customError)
if ok {
return &customError{errorType: ee.errorType, cause: ee, httpStatus: -1, msg: msg}
@ -99,6 +101,7 @@ func WithMsg(err error, msg string) *customError {
}
func WithErrMsgf(err error, errMsg string, args ...interface{}) *customError {
//nolint:errorlint
ee, ok := err.(*customError)
if ok {
return &customError{errorType: ee.errorType, cause: err, httpStatus: -1, errMsg: fmt.Sprintf(errMsg, args...)}
@ -120,14 +123,16 @@ func (ce *customError) WithMsg(msg string) *customError {
// GetType returns the error type
func GetType(err error) ErrorType {
//nolint:errorlint
if ee, ok := err.(*customError); ok {
return ee.errorType
}
return NoType
}
func GetHttpStatus(err error) int {
func GetHTTPStatus(err error) int {
for err != nil {
//nolint:errorlint
if e, ok := err.(*customError); ok {
if e.httpStatus != -1 {
return e.httpStatus
@ -143,6 +148,7 @@ func GetHttpStatus(err error) int {
func GetMessage(err error) string {
for err != nil {
//nolint:errorlint
if e, ok := err.(*customError); ok {
if e.msg != "" {
return e.msg

Loading…
Cancel
Save