Files
Blog/app/internal/utils/content.go
2025-10-26 09:38:54 +08:00

40 lines
1.1 KiB
Go

package utils
import (
"encoding/json"
)
// ExtractImageKeysFromContent parses the rich text JSON and extracts all image fileKey values
func ExtractImageKeysFromContent(content string) ([]string, error) {
var contentData map[string]interface{}
if err := json.Unmarshal([]byte(content), &contentData); err != nil {
return nil, err
}
var imageKeys []string
extractImageKeys(contentData, &imageKeys)
return imageKeys, nil
}
// extractImageKeys recursively searches for image nodes and collects their fileKey values
func extractImageKeys(data interface{}, keys *[]string) {
switch v := data.(type) {
case map[string]interface{}:
// Check if this is an image node
if nodeType, ok := v["type"].(string); ok && nodeType == "image" {
if fileKey, ok := v["fileKey"].(string); ok && fileKey != "" {
*keys = append(*keys, fileKey)
}
}
// Recurse into all map values
for _, value := range v {
extractImageKeys(value, keys)
}
case []interface{}:
// Recurse into all array elements
for _, item := range v {
extractImageKeys(item, keys)
}
}
}