|
1 | 1 | # `@miniflare/http-server` |
2 | 2 |
|
3 | 3 | HTTP server module for [Miniflare](https://github.com/cloudflare/miniflare): a |
4 | | -fun, full-featured, fully-local simulator for Cloudflare Workers |
| 4 | +fun, full-featured, fully-local simulator for Cloudflare Workers. See |
| 5 | +[🧰 Using the API](https://miniflare.dev/api.html) for more details. |
| 6 | + |
| 7 | +## Example |
| 8 | + |
| 9 | +```js |
| 10 | +import { CorePlugin, MiniflareCore } from "@miniflare/core"; |
| 11 | +import { |
| 12 | + HTTPPlugin, |
| 13 | + convertNodeRequest, |
| 14 | + createServer, |
| 15 | + startServer, |
| 16 | +} from "@miniflare/http-server"; |
| 17 | +import { VMScriptRunner } from "@miniflare/runner-vm"; |
| 18 | +import { Log, LogLevel } from "@miniflare/shared"; |
| 19 | +import { MemoryStorage } from "@miniflare/storage-memory"; |
| 20 | +import http from "http"; |
| 21 | + |
| 22 | +// Converting Node.js http.IncomingMessage to Miniflare's Request |
| 23 | +http.createServer(async (nodeReq, nodeRes) => { |
| 24 | + const req = await convertNodeRequest(nodeReq, "http://upstream", { |
| 25 | + forwardedProto: "http", |
| 26 | + realIp: "127.0.0.1", |
| 27 | + cf: { colo: "SFO" }, |
| 28 | + }); |
| 29 | + nodeRes.end(await req.text()); |
| 30 | +}); |
| 31 | + |
| 32 | +// Creating and starting HTTP servers |
| 33 | +export class BadStorageFactory { |
| 34 | + storage() { |
| 35 | + throw new Error("This example shouldn't need storage!"); |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +const plugins = { CorePlugin, HTTPPlugin }; |
| 40 | +const ctx = { |
| 41 | + log: new Log(LogLevel.INFO), |
| 42 | + storageFactory: new BadStorageFactory(), |
| 43 | + scriptRunner: new VMScriptRunner(), |
| 44 | +}; |
| 45 | + |
| 46 | +const mf = new MiniflareCore(plugins, ctx, { |
| 47 | + modules: true, |
| 48 | + script: `export default { |
| 49 | + async fetch(request, env) { |
| 50 | + return new Response("body"); |
| 51 | + } |
| 52 | + }`, |
| 53 | + port: 5000, |
| 54 | +}); |
| 55 | + |
| 56 | +// Start the server yourself... |
| 57 | +const server = await createServer(mf); |
| 58 | +// ...or get Miniflare to start it for you, logging to port |
| 59 | +const server2 = await startServer(mf); |
| 60 | +``` |
0 commit comments