refactor: improve client initialization logic and ensure thread safety

This commit is contained in:
krau
2025-10-06 23:32:20 +08:00
parent 0e989cc1a6
commit a7854afb2a

View File

@@ -3,28 +3,37 @@ package tphutil
import ( import (
"encoding/json" "encoding/json"
"strings" "strings"
"sync"
"github.com/krau/SaveAny-Bot/config" "github.com/krau/SaveAny-Bot/config"
"github.com/krau/SaveAny-Bot/pkg/telegraph" "github.com/krau/SaveAny-Bot/pkg/telegraph"
) )
var tphClient *telegraph.Client var (
tphClient *telegraph.Client
once sync.Once
)
func DefaultClient() *telegraph.Client { func DefaultClient() *telegraph.Client {
if tphClient != nil { once.Do(func() {
return tphClient tphClient = initDefault()
} })
return tphClient
}
func initDefault() *telegraph.Client {
var client *telegraph.Client
if config.C().Telegram.Proxy.Enable && config.C().Telegram.Proxy.URL != "" { if config.C().Telegram.Proxy.Enable && config.C().Telegram.Proxy.URL != "" {
proxyUrl := config.C().Telegram.Proxy.URL proxyUrl := config.C().Telegram.Proxy.URL
var err error var err error
tphClient, err = telegraph.NewClientWithProxy(proxyUrl) client, err = telegraph.NewClientWithProxy(proxyUrl)
if err != nil { if err != nil {
tphClient = telegraph.NewClient() client = telegraph.NewClient()
} }
} else { } else {
tphClient = telegraph.NewClient() client = telegraph.NewClient()
} }
return tphClient return client
} }
func GetNodeImages(node telegraph.Node) []string { func GetNodeImages(node telegraph.Node) []string {