import { MiddlewareHandlerContext } from "$fresh/server.ts"; export interface State { hostname: string; } function getIp(_req: Request, ctx: MiddlewareHandlerContext<State>) { ctx.state = {} if (ctx.remoteAddr.transport === "tcp") { ctx.state.hostname = ctx.remoteAddr.hostname; } else { ctx.state.hostname = "not tcp"; } ctx.state.data = "test data" console.log("getIp : " + ctx.state.hostname) return ctx.next(); } export const handler = [ getIp, ];
import { Head } from "$fresh/runtime.ts"; import type { HandlerContext } from "$fresh/server.ts"; import { State } from "./_middleware.ts" export default function Home(req: Request, ctx: HandlerContext<State>) { console.log("Home " + ctx.state) const hostname = ctx.state?.hostname || "no ip" return ( <> <Head> <title>fresh-show-ip</title> </Head> Visitor IP : {hostname} </> ); }
import { Head } from "$fresh/runtime.ts"; import { State } from "./_middleware.ts" import { HandlerContext, Handlers, PageProps } from "$fresh/server.ts"; export const handler: Handlers = { async GET(_req: Request, ctx: HandlerContext<State>) { console.log("GET Handler") console.log(ctx.state) const resp = await ctx.render(ctx.state); return resp; }, }; export default function Page({ data }: PageProps<State>) { const {hostname } = data; return ( <> <Head> <title>fresh-show-ip</title> </Head> Visitor IP : {hostname} </> ); }