frostfs-http-gw/internal/handler/browse.go
Nikita Zinkevich 31b838f86a
All checks were successful
/ DCO (pull_request) Successful in 1m23s
/ Vulncheck (pull_request) Successful in 1m48s
/ Builds (pull_request) Successful in 2m3s
/ Lint (pull_request) Successful in 2m45s
/ Tests (pull_request) Successful in 1m39s
[#137] Add index page support
Signed-off-by: Nikita Zinkevich <n.zinkevich@yadro.com>
2024-09-11 16:42:16 +03:00

91 lines
1.9 KiB
Go

package handler
import (
"encoding/json"
"html/template"
"path"
"strconv"
"strings"
"time"
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/utils"
"github.com/valyala/fasthttp"
"go.uber.org/zap"
)
const dateFormat = "02-01-2006 15:04"
type (
timestamp time.Time
BrowsePageData struct {
BucketName,
Prefix string
Objects []ResponseObject
}
ResponseObject struct {
OID string `json:"OID"`
Created timestamp `json:"Created"`
FileName string `json:"FileName"`
Size string `json:"Size"`
}
)
func (t *timestamp) UnmarshalJSON(b []byte) error {
var strMillis string
err := json.Unmarshal(b, &strMillis)
if err != nil {
return err
}
millis, err := strconv.ParseInt(strMillis, 10, 64)
if err != nil {
return err
}
*t = timestamp(time.UnixMilli(millis))
return nil
}
func formatDate(date timestamp) string {
if time.Time(date).IsZero() {
return ""
}
return time.Time(date).Format(dateFormat)
}
func (h *Handler) browseObjects(c *fasthttp.RequestCtx, bucketName, prefix string) {
var log = h.log.With(zap.String("bucket", bucketName))
ctx := utils.GetContextFromRequest(c)
nodes, err := h.listObjects(ctx, bucketName, prefix)
if err != nil {
logAndSendBucketError(c, log, err)
return
}
jsonNodes, err := json.Marshal(nodes)
if err != nil {
logAndSendBucketError(c, log, err)
return
}
respObjects := make([]ResponseObject, len(nodes))
if err = json.Unmarshal(jsonNodes, &respObjects); err != nil {
logAndSendBucketError(c, log, err)
return
}
templatePath := h.config.IndexPageTemplatePath()
tmpl, err := template.New(path.Base(templatePath)).Funcs(template.FuncMap{
"formatDate": formatDate,
}).ParseFiles(templatePath)
if err != nil {
logAndSendBucketError(c, log, err)
return
}
if err = tmpl.Execute(c, &BrowsePageData{
BucketName: bucketName,
Prefix: strings.TrimRight(prefix, "/"),
Objects: respObjects,
}); err != nil {
logAndSendBucketError(c, log, err)
return
}
}