hts/apps/blogai/lib/http/get-base-url.ts

105 lines
2.7 KiB
TypeScript

// import { getRuntimeEnv } from "@/lib/ipconfig";
// export async function getBaseUrl() {
// let ip = await getRuntimeEnv("SUPABASE_URL");
// if (!ip) throw new Error("SUPABASE_URL 获取失败,无法构建 baseUrl");
// let protocol = "http";
// if (
// typeof window !== "undefined" &&
// window.location &&
// window.location.protocol === "https:"
// ) {
// protocol = "https";
// ip = window.location.hostname;
// }
// return `${protocol}://${ip}`;
// }
// import { getRuntimeEnv } from "@/lib/ipconfig";
// import { headers } from 'next/headers'
// export async function getBaseUrl() {
// let ip = await getRuntimeEnv("SUPABASE_URL");
// if (!ip) throw new Error("SUPABASE_URL 获取失败,无法构建 baseUrl");
// let protocol = "http";
// let port = 80;
// if (
// typeof window !== "undefined" &&
// window.location &&
// window.location.protocol === "https:"
// ) {
// protocol = "https";
// ip = window.location.hostname;
// port = 443;
// }
// return `${protocol}://${ip}:${port}`;
// }
import { getRuntimeEnv } from "@/lib/ipconfig";
// export async function getBaseUrl() {
// let ip = await getRuntimeEnv("SUPABASE_URL");
// if (!ip) throw new Error("SUPABASE_URL 获取失败,无法构建 baseUrl");
// let protocol = "http";
// let port = 80;
// if (typeof window !== "undefined") {
// // ✅ CSR 模式
// if (window.location.protocol === "https:") {
// protocol = "https";
// ip = window.location.hostname;
// port = 443;
// }
// } else {
// // ✅ SSR 模式,补充逻辑
// const hdrs = headers();
// const forwardedProto = hdrs.get("x-forwarded-proto");
// const hostHeader = hdrs.get("host");
// if (forwardedProto) {
// protocol = forwardedProto;
// }
// if (hostHeader) {
// ip = hostHeader;
// if (hostHeader.includes(":")) {
// const parts = hostHeader.split(":");
// ip = parts[0];
// port = parseInt(parts[1]);
// } else {
// port = (protocol === "https") ? 443 : 80;
// }
// }
// }
// return `${protocol}://${ip}:${port}`;
// }
export async function getBaseUrl() {
let ip = await getRuntimeEnv("SUPABASE_URL");
if (!ip) throw new Error("SUPABASE_URL 获取失败");
if (typeof window === "undefined") {
// ✅ 只在服务端导入(避免构建失败)
const { getServerBaseUrl } = await import("./getServerBaseUrl");
return getServerBaseUrl(ip);
}
// ✅ 客户端逻辑
let protocol = window.location.protocol.replace(":", "");
let hostname = window.location.hostname;
let port = protocol === "https" ? 443 : 80;
return `${protocol}://${hostname}:${port}`;
}