frostfs-http-gw/internal/handler/browse.go
Nikita Zinkevich 6b35eb4527
All checks were successful
/ DCO (pull_request) Successful in 53s
/ Vulncheck (pull_request) Successful in 1m11s
/ Builds (pull_request) Successful in 1m6s
/ Lint (pull_request) Successful in 2m25s
/ Tests (pull_request) Successful in 1m4s
[#137] Add index page support
Signed-off-by: Nikita Zinkevich <n.zinkevich@yadro.com>
2024-09-10 14:46:57 +03:00

93 lines
1.9 KiB
Go

package handler
import (
_ "embed"
"encoding/json"
"strconv"
"strings"
"text/template"
"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"`
}
)
//go:embed templates/browse.gotmpl
var browseTemplate string
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
}
tmpl, err := template.New("browse").Funcs(template.FuncMap{
"formatDate": formatDate,
}).Parse(browseTemplate)
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
}
}