From 4f92d7e0a4099b16045f823be71e7388879baa3b Mon Sep 17 00:00:00 2001 From: Sakurasan <26715255+Sakurasan@users.noreply.github.com> Date: Sat, 15 Aug 2026 17:01:45 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B8=A0=E9=81=93:=20=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E4=B8=BB=E9=A1=B5=E5=AD=97=E6=AE=B5=20+=20=E8=A1=A8=E6=A0=BC?= =?UTF-8?q?=E5=B1=95=E7=A4=BA=20favicon?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Channel 新增 homepage 字段(渠道主页) - 后端 /admin/channels/:id/favicon 代理抓取 {homepage}/favicon.ico, 内存缓存 1h; 服务端抓取可解析 localhost/内网主页, 避免浏览器跨域 - 前端渠道表单加"渠道主页"输入; 表格新增主页列(favicon + 域名), 加载失败回退灰色地球图标 - mock 上游提供 /favicon.ico 演示 Co-Authored-By: Claude --- scripts/mockupstream/main.go | 6 +++ server/internal/api/admin_channels.go | 76 ++++++++++++++++++++++----- server/internal/api/auth.go | 14 ++++- server/internal/api/router.go | 1 + server/internal/store/models.go | 1 + web/src/types.ts | 1 + web/src/views/admin/ChannelsView.vue | 38 +++++++++++++- 7 files changed, 122 insertions(+), 15 deletions(-) diff --git a/scripts/mockupstream/main.go b/scripts/mockupstream/main.go index 618f1ce..0d0a8aa 100644 --- a/scripts/mockupstream/main.go +++ b/scripts/mockupstream/main.go @@ -49,6 +49,12 @@ func main() { fmt.Fprint(w, `{"object":"list","data":[{"id":"gpt-4o-mini","object":"model"},{"id":"gpt-4o","object":"model"},{"id":"claude-sonnet-5","object":"model"}]}`) }) + // favicon(演示渠道主页图标) + http.HandleFunc("/favicon.ico", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "image/svg+xml") + fmt.Fprint(w, ``) + }) + // Anthropic Messages 端点(provider=anthropic 的渠道走这里) http.HandleFunc("/v1/messages", func(w http.ResponseWriter, r *http.Request) { body, _ := io.ReadAll(r.Body) diff --git a/server/internal/api/admin_channels.go b/server/internal/api/admin_channels.go index 83436bd..dfa2e78 100644 --- a/server/internal/api/admin_channels.go +++ b/server/internal/api/admin_channels.go @@ -33,7 +33,7 @@ func (h *Handler) AdminChannels(c *gin.Context) { masked = "****" } out = append(out, gin.H{ - "id": ch.ID, "name": ch.Name, "provider": ch.Provider, "formats": ch.FormatsEffective(), "base_url": ch.BaseURL, + "id": ch.ID, "name": ch.Name, "provider": ch.Provider, "formats": ch.FormatsEffective(), "homepage": ch.Homepage, "base_url": ch.BaseURL, "api_key_masked": masked, "weight": ch.Weight, "priority": ch.Priority, "timeout_ms": ch.TimeoutMS, "max_concurrency": ch.MaxConcurrency, "health_status": ch.HealthStatus, "enabled": ch.Enabled, @@ -47,6 +47,7 @@ type channelBody struct { Name string `json:"name" binding:"required,min=1,max=64"` Provider string `json:"provider"` // 可选:为空时按 formats 推断(兼容旧数据) Formats []string `json:"formats"` // 原生支持的协议 chat|responses|messages(主配置) + Homepage string `json:"homepage"` BaseURL string `json:"base_url" binding:"required"` APIKey string `json:"api_key"` Weight *int `json:"weight"` @@ -142,7 +143,7 @@ func (h *Handler) AdminCreateChannel(c *gin.Context) { return } ch := store.Channel{ - Name: req.Name, Provider: req.Provider, Formats: formats, BaseURL: strings.TrimRight(req.BaseURL, "/"), + Name: req.Name, Provider: req.Provider, Formats: formats, Homepage: req.Homepage, BaseURL: strings.TrimRight(req.BaseURL, "/"), APIKeyEnc: enc, Weight: intOr(req.Weight, 1), Priority: intOr(req.Priority, 0), TimeoutMS: intOr(req.TimeoutMS, 120000), MaxConcurrency: intOr(req.MaxConcurrency, 16), HealthStatus: store.ChannelHealthHealthy, Enabled: boolOr(req.Enabled, true), @@ -162,17 +163,18 @@ func (h *Handler) AdminUpdateChannel(c *gin.Context) { return } var body struct { - Name *string `json:"name"` - Provider *string `json:"provider"` + Name *string `json:"name"` + Provider *string `json:"provider"` Formats *[]string `json:"formats"` - BaseURL *string `json:"base_url"` - APIKey *string `json:"api_key"` - Weight *int `json:"weight"` - Priority *int `json:"priority"` - TimeoutMS *int `json:"timeout_ms"` - MaxConcurrency *int `json:"max_concurrency"` - HealthStatus *string `json:"health_status"` - Enabled *bool `json:"enabled"` + Homepage *string `json:"homepage"` + BaseURL *string `json:"base_url"` + APIKey *string `json:"api_key"` + Weight *int `json:"weight"` + Priority *int `json:"priority"` + TimeoutMS *int `json:"timeout_ms"` + MaxConcurrency *int `json:"max_concurrency"` + HealthStatus *string `json:"health_status"` + Enabled *bool `json:"enabled"` } if err := c.ShouldBindJSON(&body); err != nil { resp.Fail(c, http.StatusBadRequest, "invalid input") @@ -217,6 +219,9 @@ func (h *Handler) AdminUpdateChannel(c *gin.Context) { if body.MaxConcurrency != nil { updates["max_concurrency"] = *body.MaxConcurrency } + if body.Homepage != nil { + updates["homepage"] = *body.Homepage + } if body.HealthStatus != nil { updates["health_status"] = *body.HealthStatus } @@ -398,6 +403,53 @@ func (h *Handler) AdminImportChannelModels(c *gin.Context) { resp.OK(c, gin.H{"imported": imported}) } +// AdminChannelFavicon GET /api/v1/admin/channels/:id/favicon — 代理获取渠道主页 favicon(内存缓存 1h)。 +func (h *Handler) AdminChannelFavicon(c *gin.Context) { + id, err := strconv.ParseUint(c.Param("id"), 10, 64) + if err != nil { + c.Status(http.StatusBadRequest) + return + } + var ch store.Channel + if err := h.a.DB.First(&ch, id).Error; err != nil || ch.Homepage == "" { + c.Status(http.StatusNotFound) + return + } + + h.favMu.Lock() + if f, ok := h.favCache[id]; ok && time.Since(f.at) < time.Hour { + h.favMu.Unlock() + c.Data(http.StatusOK, f.ct, f.data) + return + } + h.favMu.Unlock() + + url := strings.TrimRight(ch.Homepage, "/") + "/favicon.ico" + client := &http.Client{Timeout: 5 * time.Second} + resp, err := client.Get(url) + if err != nil || resp.StatusCode != http.StatusOK { + if resp != nil { + resp.Body.Close() + } + c.Status(http.StatusNotFound) + return + } + defer resp.Body.Close() + data, err := io.ReadAll(io.LimitReader(resp.Body, 256*1024)) + if err != nil || len(data) == 0 { + c.Status(http.StatusNotFound) + return + } + ct := resp.Header.Get("Content-Type") + if ct == "" { + ct = "image/x-icon" + } + h.favMu.Lock() + h.favCache[id] = favEntry{data: data, ct: ct, at: time.Now()} + h.favMu.Unlock() + c.Data(http.StatusOK, ct, data) +} + var _ = clause.Assignments // 保留 gorm/clause 引用(后续定价批处理用) func intOr(p *int, def int) int { diff --git a/server/internal/api/auth.go b/server/internal/api/auth.go index 817a052..4c58a61 100644 --- a/server/internal/api/auth.go +++ b/server/internal/api/auth.go @@ -5,6 +5,7 @@ import ( "encoding/json" "net/http" "strings" + "sync" "time" "github.com/gin-gonic/gin" @@ -17,9 +18,20 @@ import ( // Handler 聚合所有管理 API。 type Handler struct { a *app.App + + favMu sync.Mutex + favCache map[uint64]favEntry // 渠道 favicon 内存缓存 } -func NewHandler(a *app.App) *Handler { return &Handler{a: a} } +type favEntry struct { + data []byte + ct string + at time.Time +} + +func NewHandler(a *app.App) *Handler { + return &Handler{a: a, favCache: map[uint64]favEntry{}} +} // --------------------------------------------------------------------------- // 认证 diff --git a/server/internal/api/router.go b/server/internal/api/router.go index 626f5fa..3af88b1 100644 --- a/server/internal/api/router.go +++ b/server/internal/api/router.go @@ -93,6 +93,7 @@ func NewRouter(a *app.App, gw *proxy.Gateway) *gin.Engine { admin.DELETE("/channels/:id", h.AdminDeleteChannel) admin.POST("/channels/:id/test", h.AdminTestChannel) admin.POST("/channels/:id/models/import", h.AdminImportChannelModels) + admin.GET("/channels/:id/favicon", h.AdminChannelFavicon) // 模型与定价 admin.GET("/models", h.AdminModels) admin.POST("/models", h.AdminCreateModel) diff --git a/server/internal/store/models.go b/server/internal/store/models.go index cf3fd9b..6201a40 100644 --- a/server/internal/store/models.go +++ b/server/internal/store/models.go @@ -81,6 +81,7 @@ type Channel struct { Name string `gorm:"uniqueIndex;size:64;not null" json:"name"` Provider string `gorm:"size:16;not null" json:"provider"` // openai|anthropic|compatible(供应商/默认格式) Formats []string `gorm:"type:jsonb;serializer:json" json:"formats,omitempty"` // 原生支持的协议格式 chat|responses|messages + Homepage string `gorm:"size:255" json:"homepage"` // 渠道主页,用于展示 favicon BaseURL string `gorm:"size:255;not null" json:"base_url"` APIKeyEnc string `gorm:"size:1024;not null" json:"-"` // AES-GCM 密文 Weight int `gorm:"not null;default:1" json:"weight"` diff --git a/web/src/types.ts b/web/src/types.ts index a654418..4cd821d 100644 --- a/web/src/types.ts +++ b/web/src/types.ts @@ -26,6 +26,7 @@ export interface Channel { name: string provider: 'openai' | 'anthropic' | 'compatible' formats: string[] // chat | responses | messages + homepage?: string base_url: string api_key_masked: string weight: number diff --git a/web/src/views/admin/ChannelsView.vue b/web/src/views/admin/ChannelsView.vue index 40074d2..5fb9022 100644 --- a/web/src/views/admin/ChannelsView.vue +++ b/web/src/views/admin/ChannelsView.vue @@ -19,6 +19,7 @@ const busyId = ref(null) const form = reactive({ name: '', formats: ['chat'] as string[], + homepage: '', base_url: '', api_key: '', weight: 1, @@ -28,6 +29,24 @@ const form = reactive({ enabled: true, }) +// favicon 兜底:灰色地球 +const FAV_FALLBACK = + 'data:image/svg+xml;utf8,' + + encodeURIComponent( + '', + ) +function onFavError(e: Event) { + ;(e.target as HTMLImageElement).src = FAV_FALLBACK +} +function hostOf(u?: string): string { + if (!u) return '-' + try { + return new URL(u).host + } catch { + return u + } +} + async function load() { try { const { data } = await http.get('/admin/channels') @@ -40,7 +59,7 @@ async function load() { function openCreate() { editing.value = null Object.assign(form, { - name: '', formats: ['chat'], base_url: '', api_key: '', + name: '', formats: ['chat'], homepage: '', base_url: '', api_key: '', weight: 1, priority: 0, timeout_ms: 120000, max_concurrency: 16, enabled: true, }) editOpen.value = true @@ -50,6 +69,7 @@ function openEdit(ch: Channel) { editing.value = ch Object.assign(form, { name: ch.name, formats: [...(ch.formats?.length ? ch.formats : ['chat'])], + homepage: ch.homepage || '', base_url: ch.base_url, api_key: '', weight: ch.weight, priority: ch.priority, timeout_ms: ch.timeout_ms, max_concurrency: ch.max_concurrency, enabled: ch.enabled, @@ -143,6 +163,7 @@ onMounted(load) 名称 API 格式 + 主页 Base URL Key 健康 @@ -162,6 +183,18 @@ onMounted(load) >{{ protocolName(f) }} + +
+ + {{ hostOf(ch.homepage) }} +
+ {{ ch.base_url }} {{ ch.api_key_masked || '****' }} @@ -182,7 +215,7 @@ onMounted(load) - 还没有渠道,点击「添加渠道」 + 还没有渠道,点击「添加渠道」 @@ -213,6 +246,7 @@ onMounted(load)

客户端协议不在其中时,网关自动转换为其支持的格式

+