first commit
This commit is contained in:
77
internal/pkg/utils/url.go
Normal file
77
internal/pkg/utils/url.go
Normal file
@@ -0,0 +1,77 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"cardverse/config"
|
||||
)
|
||||
|
||||
// getBaseURL mengambil Base URL dari config (APP_BASE_URL) atau environment variable dengan fallback ke http://localhost:PORT
|
||||
func getBaseURL() string {
|
||||
if config.Cfg != nil && config.Cfg.AppBaseURL != "" {
|
||||
return strings.TrimRight(config.Cfg.AppBaseURL, "/")
|
||||
}
|
||||
|
||||
if envURL := os.Getenv("APP_BASE_URL"); envURL != "" {
|
||||
return strings.TrimRight(envURL, "/")
|
||||
}
|
||||
|
||||
port := os.Getenv("APP_PORT")
|
||||
if port == "" {
|
||||
port = "8080"
|
||||
}
|
||||
|
||||
return "http://localhost:" + port
|
||||
}
|
||||
|
||||
// FormatMediaURL mengubah path relatif gambar (seperti /images/...) menjadi URL lengkap menggunakan APP_BASE_URL
|
||||
func FormatMediaURL(urlStr string) string {
|
||||
if urlStr == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
// Jika sudah berupa URL lengkap (http:// atau https://), kembalikan langsung
|
||||
if strings.HasPrefix(urlStr, "http://") || strings.HasPrefix(urlStr, "https://") {
|
||||
return urlStr
|
||||
}
|
||||
|
||||
baseURL := getBaseURL()
|
||||
|
||||
if !strings.HasPrefix(urlStr, "/") {
|
||||
urlStr = "/" + urlStr
|
||||
}
|
||||
|
||||
return baseURL + urlStr
|
||||
}
|
||||
|
||||
// FormatMediaURLPtr mengubah pointer path relatif gambar menjadi pointer URL lengkap
|
||||
func FormatMediaURLPtr(urlPtr *string) *string {
|
||||
if urlPtr == nil || *urlPtr == "" {
|
||||
return urlPtr
|
||||
}
|
||||
formatted := FormatMediaURL(*urlPtr)
|
||||
return &formatted
|
||||
}
|
||||
|
||||
// FormatJSONBMediaURLs mengubah seluruh path relatif gambar (/images/... atau /public/...) di dalam data byte JSONB menjadi URL lengkap
|
||||
func FormatJSONBMediaURLs(data []byte) []byte {
|
||||
if len(data) == 0 {
|
||||
return data
|
||||
}
|
||||
|
||||
baseURL := getBaseURL()
|
||||
s := string(data)
|
||||
|
||||
// Replace "/images/" dengan "APP_BASE_URL/images/"
|
||||
targetImages := `"/images/`
|
||||
replaceImages := `"` + baseURL + `/images/`
|
||||
s = strings.ReplaceAll(s, targetImages, replaceImages)
|
||||
|
||||
// Replace "/public/" dengan "APP_BASE_URL/public/"
|
||||
targetPublic := `"/public/`
|
||||
replacePublic := `"` + baseURL + `/public/`
|
||||
s = strings.ReplaceAll(s, targetPublic, replacePublic)
|
||||
|
||||
return []byte(s)
|
||||
}
|
||||
Reference in New Issue
Block a user