refactor: build storage key (#1326)

* refactor build storage key

* sort imports

* use gofmt to format code
pull/1327/head
Cologler 2 years ago committed by GitHub
parent 25da3c073b
commit 8c774316ae
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -8,6 +8,7 @@ import (
"net/http" "net/http"
"net/url" "net/url"
"path" "path"
"regexp"
"strconv" "strconv"
"strings" "strings"
"time" "time"
@ -24,6 +25,8 @@ const (
maxFileSize = 32 << 20 maxFileSize = 32 << 20
) )
var fileKeyPattern = regexp.MustCompile(`\{[a-z]{1,9}\}`)
func (s *Server) registerResourceRoutes(g *echo.Group) { func (s *Server) registerResourceRoutes(g *echo.Group) {
g.POST("/resource", func(c echo.Context) error { g.POST("/resource", func(c echo.Context) error {
ctx := c.Request().Context() ctx := c.Request().Context()
@ -136,22 +139,39 @@ func (s *Server) registerResourceRoutes(g *echo.Group) {
if storage.Type == api.StorageS3 { if storage.Type == api.StorageS3 {
s3Config := storage.Config.S3Config s3Config := storage.Config.S3Config
t := time.Now() t := time.Now()
s3FileKey := s3Config.Path var s3FileKey string
if s3Config.Path == "" { if s3Config.Path == "" {
s3FileKey = filename s3FileKey = filename
} else if !strings.Contains(s3Config.Path, "{filename}") {
s3FileKey = path.Join(s3Config.Path, filename)
} else { } else {
s3FileKey = strings.ReplaceAll(s3FileKey, "{filename}", filename) s3FileKey = fileKeyPattern.ReplaceAllStringFunc(s3Config.Path, func(s string) string {
s3FileKey = strings.ReplaceAll(s3FileKey, "{filetype}", filetype) switch s {
s3FileKey = strings.ReplaceAll(s3FileKey, "{timestamp}", fmt.Sprintf("%d", t.Unix())) case "{filename}":
s3FileKey = strings.ReplaceAll(s3FileKey, "{year}", fmt.Sprintf("%d", t.Year())) return filename
s3FileKey = strings.ReplaceAll(s3FileKey, "{month}", fmt.Sprintf("%02d", t.Month())) case "{filetype}":
s3FileKey = strings.ReplaceAll(s3FileKey, "{day}", fmt.Sprintf("%02d", t.Day())) return filetype
s3FileKey = strings.ReplaceAll(s3FileKey, "{hour}", fmt.Sprintf("%02d", t.Hour())) case "{timestamp}":
s3FileKey = strings.ReplaceAll(s3FileKey, "{minute}", fmt.Sprintf("%02d", t.Minute())) return fmt.Sprintf("%d", t.Unix())
s3FileKey = strings.ReplaceAll(s3FileKey, "{second}", fmt.Sprintf("%02d", t.Second())) 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{ s3client, err := s3.NewClient(ctx, &s3.Config{
AccessKey: s3Config.AccessKey, AccessKey: s3Config.AccessKey,
SecretKey: s3Config.SecretKey, SecretKey: s3Config.SecretKey,

Loading…
Cancel
Save