Spaces:
Sleeping
Sleeping
| import { NextRequest, NextResponse } from "next/server"; | |
| type Params = { path: string[] }; | |
| async function proxyRequest( | |
| req: NextRequest, | |
| { params }: { params: Params } | |
| ): Promise<NextResponse> { | |
| const golangUrl = process.env.GOLANG_SERVICE_URL; | |
| const testerToken = process.env.TESTER_TOKEN; | |
| if (!golangUrl) { | |
| return NextResponse.json( | |
| { message: "Golang service URL not configured" }, | |
| { status: 503 } | |
| ); | |
| } | |
| if (!testerToken) { | |
| return NextResponse.json( | |
| { message: "Golang service token not configured" }, | |
| { status: 503 } | |
| ); | |
| } | |
| const path = params.path.join("/"); | |
| const { search } = new URL(req.url); | |
| const targetUrl = `${golangUrl}/${path}${search}`; | |
| const authorization = testerToken.startsWith("Bearer ") | |
| ? testerToken | |
| : `Bearer ${testerToken}`; | |
| const forwardHeaders: HeadersInit = { authorization }; | |
| const contentType = req.headers.get("content-type"); | |
| if (contentType) forwardHeaders["content-type"] = contentType; | |
| const fetchInit: RequestInit & { duplex?: string } = { | |
| method: req.method, | |
| headers: forwardHeaders, | |
| }; | |
| if (req.method !== "GET" && req.method !== "HEAD") { | |
| fetchInit.body = req.body; | |
| fetchInit.duplex = "half"; | |
| } | |
| try { | |
| const upstream = await fetch(targetUrl, fetchInit); | |
| const body = await upstream.arrayBuffer(); | |
| return new NextResponse(body, { | |
| status: upstream.status, | |
| headers: { | |
| "content-type": | |
| upstream.headers.get("content-type") ?? "application/json", | |
| }, | |
| }); | |
| } catch { | |
| return NextResponse.json( | |
| { message: "Upstream service unavailable" }, | |
| { status: 502 } | |
| ); | |
| } | |
| } | |
| export async function GET(req: NextRequest, ctx: { params: Params }) { | |
| return proxyRequest(req, ctx); | |
| } | |
| export async function POST(req: NextRequest, ctx: { params: Params }) { | |
| return proxyRequest(req, ctx); | |
| } | |
| export async function PUT(req: NextRequest, ctx: { params: Params }) { | |
| return proxyRequest(req, ctx); | |
| } | |
| export async function PATCH(req: NextRequest, ctx: { params: Params }) { | |
| return proxyRequest(req, ctx); | |
| } | |
| export async function DELETE(req: NextRequest, ctx: { params: Params }) { | |
| return proxyRequest(req, ctx); | |
| } | |