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

87 lines
2.1 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";
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") {
// ✅ 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}`;
}