From 8c774316aeec6b94c56d83739762bfc45bd821fd Mon Sep 17 00:00:00 2001 From: Cologler <10906962+Cologler@users.noreply.github.com> Date: Thu, 9 Mar 2023 22:41:48 +0800 Subject: [PATCH] refactor: build storage key (#1326) * refactor build storage key * sort imports * use gofmt to format code --- server/resource.go | 44 ++++++++++++++++++++++++++++++++------------ 1 file changed, 32 insertions(+), 12 deletions(-) diff --git a/server/resource.go b/server/resource.go index 484d7817..13dd8879 100644 --- a/server/resource.go +++ b/server/resource.go @@ -8,6 +8,7 @@ import ( "net/http" "net/url" "path" + "regexp" "strconv" "strings" "time" @@ -24,6 +25,8 @@ const ( maxFileSize = 32 << 20 ) +var fileKeyPattern = regexp.MustCompile(`\{[a-z]{1,9}\}`) + func (s *Server) registerResourceRoutes(g *echo.Group) { g.POST("/resource", func(c echo.Context) error { ctx := c.Request().Context() @@ -136,22 +139,39 @@ func (s *Server) registerResourceRoutes(g *echo.Group) { if storage.Type == api.StorageS3 { s3Config := storage.Config.S3Config t := time.Now() - s3FileKey := s3Config.Path + var s3FileKey string if s3Config.Path == "" { s3FileKey = filename - } else if !strings.Contains(s3Config.Path, "{filename}") { - s3FileKey = path.Join(s3Config.Path, filename) } else { - s3FileKey = strings.ReplaceAll(s3FileKey, "{filename}", filename) - s3FileKey = strings.ReplaceAll(s3FileKey, "{filetype}", filetype) - s3FileKey = strings.ReplaceAll(s3FileKey, "{timestamp}", fmt.Sprintf("%d", t.Unix())) - s3FileKey = strings.ReplaceAll(s3FileKey, "{year}", fmt.Sprintf("%d", t.Year())) - s3FileKey = strings.ReplaceAll(s3FileKey, "{month}", fmt.Sprintf("%02d", t.Month())) - s3FileKey = strings.ReplaceAll(s3FileKey, "{day}", fmt.Sprintf("%02d", t.Day())) - s3FileKey = strings.ReplaceAll(s3FileKey, "{hour}", fmt.Sprintf("%02d", t.Hour())) - s3FileKey = strings.ReplaceAll(s3FileKey, "{minute}", fmt.Sprintf("%02d", t.Minute())) - s3FileKey = strings.ReplaceAll(s3FileKey, "{second}", fmt.Sprintf("%02d", t.Second())) + s3FileKey = fileKeyPattern.ReplaceAllStringFunc(s3Config.Path, func(s string) string { + switch s { + case "{filename}": + return filename + case "{filetype}": + return filetype + case "{timestamp}": + return fmt.Sprintf("%d", t.Unix()) + case "{year}": + return fmt.Sprintf("%d", t.Year()) + case "{month}": + return fmt.Sprintf("%02d", t.Month()) + case "{day}": + return fmt.Sprintf("%02d", t.Day()) + case "{hour}": + return fmt.Sprintf("%02d", t.Hour()) + case "{minute}": + return fmt.Sprintf("%02d", t.Minute()) + case "{second}": + return fmt.Sprintf("%02d", t.Second()) + } + return s + }) + + if !strings.Contains(s3Config.Path, "{filename}") { + s3FileKey = path.Join(s3FileKey, filename) + } } + s3client, err := s3.NewClient(ctx, &s3.Config{ AccessKey: s3Config.AccessKey, SecretKey: s3Config.SecretKey,