RezinaLMS-BackEnd/internal/web_server/fileurls/walk.go
Yared Yemane f457589f4a feat: auto-resolve MinIO file URLs in API responses
Presign minio:// references on outbound /api/v1 JSON so clients get usable URLs from resource GETs without calling the refresh endpoint.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-03 06:37:10 -07:00

117 lines
2.8 KiB
Go

package fileurls
import (
"context"
"strings"
"github.com/bytedance/sonic"
)
var resolveFieldKeys = map[string]struct{}{
"profile_picture_url": {},
"profile_picture": {},
"image_url": {},
"thumbnail": {},
"thumbnail_url": {},
"voice_prompt": {},
"sample_answer_voice_prompt": {},
"audio_url": {},
"banner_image": {},
"image": {},
"icon": {},
"url": {},
"value": {},
}
var skipFieldKeys = map[string]struct{}{
"reference": {},
"object_key": {},
"upload_url": {},
"payment_url": {},
"checkout_url": {},
"callback_url": {},
"return_url": {},
"cancel_url": {},
"success_url": {},
"error_url": {},
"notify_url": {},
"notification_url": {},
"notificationUrl": {},
"embed_url": {},
"store_url": {},
"intro_video_url": {},
"video_url": {},
"link": {},
"vimeo_id": {},
"previewUrl": {},
"preview_url": {},
}
func shouldResolveField(fieldKey, value string) bool {
if _, skip := skipFieldKeys[fieldKey]; skip {
return false
}
if _, ok := resolveFieldKeys[fieldKey]; !ok {
return false
}
return NeedsResolution(value)
}
// ResolveInJSON walks a decoded JSON value and presigns known file-reference fields.
func (r *Resolver) ResolveInJSON(ctx context.Context, raw []byte) ([]byte, bool) {
if r == nil || r.provider == nil || len(raw) == 0 {
return raw, false
}
var root interface{}
if err := sonic.Unmarshal(raw, &root); err != nil {
return raw, false
}
resolved := resolveValue(ctx, r, root, "")
out, err := sonic.Marshal(resolved)
if err != nil {
return raw, false
}
return out, true
}
func resolveValue(ctx context.Context, r *Resolver, value interface{}, fieldKey string) interface{} {
switch typed := value.(type) {
case map[string]interface{}:
out := make(map[string]interface{}, len(typed))
for k, child := range typed {
out[k] = resolveValue(ctx, r, child, k)
}
return out
case []interface{}:
out := make([]interface{}, len(typed))
for i, child := range typed {
out[i] = resolveValue(ctx, r, child, fieldKey)
}
return out
case string:
if shouldResolveField(fieldKey, typed) {
return r.Resolve(ctx, typed)
}
return typed
default:
return value
}
}
// ResolvePtr returns a pointer to a resolved URL when the input is non-nil and resolvable.
func (r *Resolver) ResolvePtr(ctx context.Context, ref *string) *string {
if ref == nil {
return nil
}
trimmed := strings.TrimSpace(*ref)
if trimmed == "" {
return ref
}
resolved := r.Resolve(ctx, trimmed)
if resolved == trimmed {
return ref
}
out := resolved
return &out
}