Sandbox 可通过 出站处理程序 访问 Workers 绑定(binding) —— KV、R2、D1、Durable Objects 等。出站处理程序会拦截来自 sandbox 的 HTTP 请求,并在 Workers 运行时内执行,在那里你配置的所有绑定都可用。
sandbox 向虚拟主机名(例如 http://my.kv/some-key)发出普通 HTTP 请求,出站处理程序使用已绑定的资源解析该请求。sandbox 内部不需要 SDK 或客户端库。
为每个虚拟主机名定义 outboundByHost 处理程序。env 参数可让你访问 Wrangler 配置中声明的每个绑定(binding)。
export class MySandbox extends Sandbox {}
MySandbox.outboundByHost = {
"my.kv": async (request, env, ctx) => {
const url = new URL(request.url);
const key = url.pathname.slice(1);
const value = await env.KV.get(key);
return new Response(value ?? "", { status: value ? 200 : 404 });
},
"my.r2": async (request, env, ctx) => {
const url = new URL(request.url);
// Scope access to this sandbox's ID
const path = `${ctx.containerId}${url.pathname}`;
const object = await env.R2.get(path);
return new Response(object?.body ?? null, { status: object ? 200 : 404 });
},
};export class MySandbox extends Sandbox {}
MySandbox.outboundByHost = {
"my.kv": async (request: Request, env: Env, ctx: OutboundHandlerContext) => {
const url = new URL(request.url);
const key = url.pathname.slice(1);
const value = await env.KV.get(key);
return new Response(value ?? "", { status: value ? 200 : 404 });
},
"my.r2": async (request: Request, env: Env, ctx: OutboundHandlerContext) => {
const url = new URL(request.url);
// Scope access to this sandbox's ID
const path = `${ctx.containerId}${url.pathname}`;
const object = await env.R2.get(path);
return new Response(object?.body ?? null, { status: object ? 200 : 404 });
},
};sandbox 调用 http://my.kv/some-key,处理程序使用 KV 绑定解析它。调用 http://my.r2/file.png 会从 R2 读取,并限定到当前 sandbox 实例。
ctx 参数暴露 containerId,可让你从出站处理程序与 sandbox 自身的 Durable Object 交互。
export class MySandbox extends Sandbox {}
MySandbox.outboundByHost = {
"get-state.do": async (request, env, ctx) => {
const id = env.MY_SANDBOX.idFromString(ctx.containerId);
const stub = env.MY_SANDBOX.get(id);
// Assumes getStateForKey is defined on your DO
return stub.getStateForKey(request.body);
},
};export class MySandbox extends Sandbox {}
MySandbox.outboundByHost = {
"get-state.do": async (
request: Request,
env: Env,
ctx: { containerId: string },
) => {
const id = env.MY_SANDBOX.idFromString(ctx.containerId);
const stub = env.MY_SANDBOX.get(id);
// Assumes getStateForKey is defined on your DO
return stub.getStateForKey(request.body);
},
};- 处理出站流量 — 阻止、允许并拦截来自 sandbox 的所有出站 HTTP
- Sandbox 选项 — 配置 sandbox 行为
- 环境变量 — 配置 secrets 与环境变量