/** * 服务端 API 客户端:Vike +data 在 Node 侧调用 Go API 用(仅 SSR 打包引用)。 * * - GO_API_URL 指向 Go 服务(dev 默认与 Vite proxy 一致;生产由环境变量给 :3001) * - 转发浏览器 cookie 以透传登录态 * - 转发 host / X-Forwarded-* 让 Go 推导正确的站点 base URL(canonical/og:url 等) * - 5s 超时;任何失败返回 null,调用方降级为 SPA 壳,不阻断渲染 */ const GO_API_URL = process.env.GO_API_URL || `http://127.0.0.1:${process.env.VITE_API_PORT || '3000'}`; export type ServerApiOptions = { /** 浏览器请求的 cookie 原样转发 */ cookie?: string; /** 额外转发给 Go 的请求头(host / x-forwarded-* 等) */ headers?: Record; timeoutMs?: number; }; export async function serverApi(path: string, opts?: ServerApiOptions): Promise { try { const res = await fetch(`${GO_API_URL}${path}`, { headers: { ...(opts?.cookie ? { cookie: opts.cookie } : {}), ...(opts?.headers ?? {}), }, signal: AbortSignal.timeout(opts?.timeoutMs ?? 5000), cache: 'no-store', }); if (!res.ok) return null; return (await res.json()) as T; } catch { return null; } }