{"id":13470715,"url":"https://github.com/zigzap/zap","last_synced_at":"2025-05-14T01:07:53.224Z","repository":{"id":65256481,"uuid":"588329504","full_name":"zigzap/zap","owner":"zigzap","description":"blazingly fast backends in zig","archived":false,"fork":false,"pushed_at":"2025-04-02T12:36:22.000Z","size":11364,"stargazers_count":2818,"open_issues_count":17,"forks_count":91,"subscribers_count":33,"default_branch":"master","last_synced_at":"2025-04-03T09:41:25.519Z","etag":null,"topics":["api","blazingly","fast","http","rest","zig","zig-package"],"latest_commit_sha":null,"homepage":"","language":"C","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/zigzap.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":"renerocksai","patreon":null,"open_collective":null,"ko_fi":null,"tidelift":null,"community_bridge":null,"liberapay":null,"issuehunt":null,"otechie":null,"lfx_crowdfunding":null,"custom":"https://buymeacoffee.com/renerocksai"}},"created_at":"2023-01-12T21:36:31.000Z","updated_at":"2025-04-03T08:34:26.000Z","dependencies_parsed_at":"2023-02-14T09:02:07.717Z","dependency_job_id":"3da38527-fddf-4d04-a93f-c9d1552749ce","html_url":"https://github.com/zigzap/zap","commit_stats":{"total_commits":608,"total_committers":33,"mean_commits":"18.424242424242426","dds":"0.24013157894736847","last_synced_commit":"29b923f96ee09d855b603866d2e149d506f72679"},"previous_names":[],"tags_count":71,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zigzap%2Fzap","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zigzap%2Fzap/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zigzap%2Fzap/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zigzap%2Fzap/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/zigzap","download_url":"https://codeload.github.com/zigzap/zap/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248228895,"owners_count":21068771,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","blazingly","fast","http","rest","zig","zig-package"],"created_at":"2024-07-31T16:00:34.934Z","updated_at":"2025-05-14T01:07:53.208Z","avatar_url":"https://github.com/zigzap.png","language":"C","readme":"# ⚡zap⚡ - blazingly fast backends in zig\n\n![](https://github.com/zigzap/zap/actions/workflows/build-current-zig.yml/badge.svg) ![](https://github.com/zigzap/zap/actions/workflows/mastercheck.yml/badge.svg) [![Discord](https://img.shields.io/discord/1107835896356675706?label=chat\u0026logo=discord\u0026style=plastic)](https://discord.gg/jQAAN6Ubyj)\n\nZap is the [zig](https://ziglang.org) replacement for the REST APIs I used to\nwrite in [python](https://python.org) with\n[Flask](https://flask.palletsprojects.com) and\n[mongodb](https://www.mongodb.com), etc. It can be considered to be a\nmicroframework for web applications.\n\nWhat I needed as a replacement was a blazingly fast and robust HTTP server that\nI could use with Zig, and I chose to wrap the superb evented networking C\nlibrary [facil.io](https://facil.io). Zap wraps and patches [facil.io - the C\nweb application framework](https://facil.io).\n\n## **⚡ZAP⚡ IS FAST, ROBUST, AND STABLE**\n\n\nAfter having used ZAP in production for years, I can confidently assert that it\nproved to be:\n\n- ⚡ **blazingly fast** ⚡\n- 💪 **extremely robust** 💪\n\n## FAQ:\n\n- Q: **What version of Zig does Zap support?**\n    - Zap uses the latest stable zig release (0.14.0), so you don't have to keep\n      up with frequent breaking changes. It's an \"LTS feature\".\n- Q: **Can Zap build with Zig's master branch?**\n    - See the `zig-master` branch. Please note that the zig-master branch is not\n      the official master branch of ZAP. Be aware that I don't provide tagged\n      releases for it. If you know what you are doing, that shouldn't stop you\n      from using it with zig master though.\n- Q: **Where is the API documentation?**\n    - Docs are a work in progress. You can check them out\n      [here](https://zigzap.org/zap).\n    - Run `zig build run-docserver` to serve them locally.\n- Q: **Does ZAP work on Windows?**\n    - No. This is due to the underlying facil.io C library. Future versions\n      of facil.io might support Windows but there is no timeline yet. Your best\n      options on Windows are **WSL2 or a docker container**.\n- Q: **Does ZAP support TLS / HTTPS?**\n    - Yes, ZAP supports using the system's openssl. See the\n      [https](./examples/https/https.zig) example and make sure to build with\n      the `-Dopenssl` flag or the environment variable `ZAP_USE_OPENSSL=true`:\n      - `.openssl = true,` (in dependent projects' build.zig,\n        `b.dependency(\"zap\" .{...})`)\n      - `ZAP_USE_OPENSSL=true zig build https`\n      - `zig build -Dopenssl=true https`\n\n## Here's what works\n\nI recommend checking out **the new App-based** or the Endpoint-based\nexamples, as they reflect how I intended Zap to be used.\n\nMost of the examples are super stripped down to only include what's necessary to\nshow a feature.\n\n**To see API docs, run `zig build run-docserver`.** To specify a custom\nport and docs dir: `zig build docserver \u0026\u0026 zig-out/bin/docserver --port=8989\n--docs=path/to/docs`.\n\n### New App-Based Examples\n\n- **[app_basic](examples/app/basic.zig)**: Shows how to use zap.App with a\nsimple Endpoint.\n- **[app_auth](examples/app/auth.zig)**: Shows how to use zap.App with an\nEndpoint using an Authenticator.\n\nSee the other examples for specific uses of Zap.\n\nBenefits of using `zap.App`:\n\n- Provides a global, user-defined \"Application Context\" to all endpoints.\n- Made to work with \"Endpoints\": an endpoint is a struct that covers a `/slug`\n  of the requested URL and provides a callback for each supported request method\n  (get, put, delete, options, post, head, patch).\n- Each request callback receives:\n  - a per-thread arena allocator you can use for throwaway allocations without\n    worrying about freeing them.\n  - the global \"Application Context\" of your app's choice\n- Endpoint request callbacks are allowed to return errors:\n  - you can use `try`.\n  - the endpoint's ErrorStrategy defines if runtime errors should be reported to\n    the console, to the response (=browser for debugging), or if the error\n    should be returned.\n\n### Legacy Endpoint-based examples\n\n- **[endpoint](examples/endpoint/)**: a simple JSON REST API example featuring a\n  `/users` endpoint for performing PUT/DELETE/GET/POST operations and listing\n  users, together with a simple frontend to play with. **It also introduces a\n  `/stop` endpoint** that shuts down Zap, so **memory leak detection** can be\n  performed in main().\n    - Check out how [main.zig](examples/endpoint/main.zig) uses ZIG's awesome\n      `GeneralPurposeAllocator` to report memory leaks when ZAP is shut down.\n      The [StopEndpoint](examples/endpoint/stopendpoint.zig) just stops ZAP when\n      receiving a request on the `/stop` route.\n- **[endpoint authentication](examples/endpoint_auth/endpoint_auth.zig)**: a\n  simple authenticated endpoint. Read more about authentication\n  [here](./doc/authentication.md).\n\n\n### Legacy Middleware-Style examples\n\n- **[MIDDLEWARE support](examples/middleware/middleware.zig)**: chain together\n  request handlers in middleware style. Provide custom context structs, totally\n  type-safe. If you come from GO this might appeal to you.\n- **[MIDDLEWARE with endpoint\n  support](examples/middleware_with_endpoint/middleware_with_endpoint.zig)**:\n  Same as the example above, but this time we use an endpoint at the end of the\n  chain, by wrapping it via `zap.Middleware.EndpointHandler`. Mixing endpoints\n  in your middleware chain allows for usage of Zap's authenticated endpoints and\n  your custom endpoints. Since Endpoints use a simpler API, you have to use\n  `r.setUserContext()` and `r.getUserContext()` with the request if you want to\n  access the middleware context from a wrapped endpoint. Since this mechanism\n  uses an `*anyopaque` pointer underneath (to not break the Endpoint API), it is\n  less type-safe than `zap.Middleware`'s use of contexts.\n- [**Per Request Contexts**](./src/zap.zig#L102) : With the introduction of\n  `setUserContext()` and `getUserContext()`, you can, of course use those two in\n  projects that don't use `zap.Endpoint` or `zap.Middleware`, too, if you\n  really, really, absolutely don't find another way to solve your context\n  problem. **We recommend using a `zap.Endpoint`** inside of a struct that\n  can provide all the context you need **instead**. You get access to your\n  struct in the callbacks via the `@fieldParentPtr()` trick that is used\n  extensively in Zap's examples, like the [endpoint\n  example](examples/endpoint/endpoint.zig).\n\n### Specific and Very Basic Examples\n\n- **[hello](examples/hello/hello.zig)**: welcomes you with some static HTML\n- **[routes](examples/routes/routes.zig)**: a super easy example dispatching on\n  the HTTP path. **NOTE**: The dispatch in the example is a super-basic\n  DIY-style dispatch. See endpoint-based examples for more realistic use cases.\n- [**simple_router**](examples/simple_router/simple_router.zig): See how you\n  can use `zap.Router` to dispatch to handlers by HTTP path.\n- **[serve](examples/serve/serve.zig)**: the traditional static web server with\n  optional dynamic request handling\n- **[sendfile](examples/sendfile/sendfile.zig)**: simple example of how to send\n  a file, honoring compression headers, etc.\n- **[bindataformpost](examples/bindataformpost/bindataformpost.zig)**: example\n  to receive binary files via form post.\n- **[hello_json](examples/hello_json/hello_json.zig)**: serves you json\n  dependent on HTTP path\n- **[mustache](examples/mustache/mustache.zig)**: a simple example using\n  [mustache](https://mustache.github.io/) templating.\n- **[http parameters](examples/http_params/http_params.zig)**: a simple example\n  sending itself query parameters of all supported types.\n- **[cookies](examples/cookies/cookies.zig)**: a simple example sending itself a\n  cookie and responding with a session cookie.\n- **[websockets](examples/websockets/)**: a simple websockets chat for the\n  browser.\n- **[Username/Password Session\n  Authentication](./examples/userpass_session_auth/)**: A convenience\n  authenticator that redirects un-authenticated requests to a login page and\n  sends cookies containing session tokens based on username/password pairs\n  received via POST request.\n- [**Error Trace Responses**](./examples/senderror/senderror.zig): You can now\n  call `r.sendError(err, status_code)` when you catch an error and a stack trace\n  will be returned to the client / browser.\n- [**HTTPS**](examples/https/https.zig): Shows how easy it is to use facil.io's\n  openssl support. Must be compiled with `-Dopenssl=true` or the environment\n  variable `ZAP_USE_OPENSSL` set to `true` and requires openssl dev dependencies\n  (headers, lib) to be installed on the system.\n  - run it like this: `ZAP_USE_OPENSSL=true zig build run-https`\n    OR like this: `zig build -Dopenssl=true run-https`\n  - it will tell you how to generate certificates\n\n\n## ⚡blazingly fast⚡\n\nClaiming to be blazingly fast is the new black. At least, Zap doesn't slow you\ndown and if your server performs poorly, it's probably not exactly Zap's fault.\nZap relies on the [facil.io](https://facil.io) framework and so it can't really\nclaim any performance fame for itself. In this initial implementation of Zap,\nI didn't care about optimizations at all.\n\nBut, how fast is it? Being blazingly fast is relative. When compared with a\nsimple GO HTTP server, a simple Zig Zap HTTP server performed really well on my\nmachine (x86_64-linux):\n\n- Zig Zap was nearly 30% faster than GO\n- Zig Zap had over 50% more throughput than GO\n- **YMMV!!!**\n\nSo, being somewhere in the ballpark of basic GO performance, zig zap seems to be\n... of reasonable performance 😎.\n\nI can rest my case that developing ZAP was a good idea because it's faster than\nboth alternatives: a) staying with Python, and b) creating a GO + Zig hybrid.\n\n### On (now missing) Micro-Benchmarks\n\nI used to have some micro-benchmarks in this repo, showing that Zap beat all the\nother things I tried, and eventually got tired of the meaningless discussions\nthey provoked, the endless issues and PRs that followed, wanting me to add and\nmaintain even more contestants, do more justice to beloved other frameworks,\netc.\n\nCase in point, even for me the micro-benchmarks became meaningless. They were\njust some rough indicator to me confirming that I didn't do anything terribly\nwrong to facil.io, and that facil.io proved to be a reasonable choice, also from\na performance perspective.\n\nHowever, none of the projects I use Zap for, ever even remotely resembled\nanything close to a static HTTP response micro-benchmark.\n\nFor my more CPU-heavy than IO-heavy use-cases, a thread-based microframework\nthat's super robust is still my preferred choice, to this day.\n\nHaving said that, I would **still love** for other, pure-zig HTTP frameworks to\neventually make Zap obsolete. Now, in 2025, the list of candidates is looking\nreally promising.\n\n### 📣 Shout-Outs\n\n- [http.zig](https://github.com/karlseguin/http.zig) : Pure Zig! Close to Zap's\n  model. Performance = good!\n- [jetzig](https://github.com/jetzig-framework/jetzig) : Comfortably develop\n  modern web applications quickly, using http.zig under the hood\n- [zzz](https://github.com/tardy-org/zzz) : Super promising, super-fast,\n  especially for IO-heavy tasks, io_uring support - need I say more?\n\n\n## 💪 Robust\n\nZAP is **very robust**. In fact, it is so robust that I was confidently able to\nonly work with in-memory data (RAM) in all my ZAP projects so far: over 5 large\nonline research experiments. No database, no file persistence, until I hit\n\"save\" at the end 😊.\n\nSo I was able to postpone my cunning data persistence strategy that's similar to\na mark-and-sweep garbage collector and would only persist \"dirty\" data when\ntraffic is low, in favor of getting stuff online more quickly. But even if\nimplemented, such a persistence strategy is risky because when traffic is not\nlow, it means the system is under (heavy) load. Would you confidently NOT save\ndata when load is high and the data changes most frequently -\u003e the potential\ndata loss is maximized?\n\nTo answer that question, I just skipped it. I skipped saving any data until\nreceiving a \"save\" signal via API. And it worked. ZAP just kept on zapping. When\ntraffic calmed down or all experiment participants had finished, I hit \"save\"\nand went on analyzing the data.\n\nHandling all errors does pay off after all. No hidden control flow, no hidden\nerrors or exceptions is one of Zig's strengths.\n\nTo be honest: There are still pitfalls. E.g. if you request large stack sizes\nfor worker threads, Zig won't like that and panic. So make sure you don't have\nlocal variables that require tens of megabytes of stack space.\n\n\n### 🛡️ Memory-safe\n\nSee the [StopEndpoint](examples/endpoint/stopendpoint.zig) in the\n[endpoint](examples/endpoint) example. The `StopEndpoint` just stops ZAP when\nreceiving a request on the `/stop` route. That example uses ZIG's awesome\n`GeneralPurposeAllocator` in [main.zig](examples/endpoint/main.zig) to report\nmemory leaks when ZAP is shut down.\n\nYou can use the same strategy in your debug builds and tests to check if your\ncode leaks memory.\n\n\n\n## Getting started\n\nMake sure you have **zig 0.14.0** installed. Fetch it from\n[here](https://ziglang.org/download).\n\n```shell\n$ git clone https://github.com/zigzap/zap.git\n$ cd zap\n$ zig build run-hello\n$ # open http://localhost:3000 in your browser\n```\n... and open [http://localhost:3000](http://localhost:3000) in your browser.\n\n## Using ⚡zap⚡ in your own projects\n\nMake sure you have **the latest zig release (0.14.0)** installed. Fetch it from\n[here](https://ziglang.org/download).\n\nIf you don't have an existing zig project, create one like this:\n\n```shell\n$ mkdir zaptest \u0026\u0026 cd zaptest\n$ zig init\n```\n\nWith an existing Zig project, adding Zap to it is easy:\n\n1. Zig fetch zap\n2. Add zap to your `build.zig`\n\nIn your zig project folder (where `build.zig` is located), run:\n\n\u003c!-- INSERT_DEP_BEGIN --\u003e\n```\nzig fetch --save \"git+https://github.com/zigzap/zap#v0.10.1\"\n```\n\u003c!-- INSERT_DEP_END --\u003e\n\nThen, in your `build.zig`'s `build` function, add the following before\n`b.installArtifact(exe)`:\n\n```zig\n    const zap = b.dependency(\"zap\", .{\n        .target = target,\n        .optimize = optimize,\n        .openssl = false, // set to true to enable TLS support\n    });\n\n    exe.root_module.addImport(\"zap\", zap.module(\"zap\"));\n```\n\nFrom then on, you can use the Zap package in your project via `const zap =\n@import(\"zap\");`. Check out the examples to see how to use Zap.\n\n\n## Contribute to ⚡zap⚡ - blazingly fast\n\nAt the current time, I can only add to zap what I need for my personal and\nprofessional projects. While this happens **blazingly fast**, some if not all\nnice-to-have additions will have to wait. You are very welcome to help make the\nworld a blazingly fast place by providing patches or pull requests, add\ndocumentation or examples, or interesting issues and bug reports - you'll know\nwhat to do when you receive your calling 👼.\n\n**We have our own [ZAP discord](https://discord.gg/jQAAN6Ubyj) server!!!**\n\n## Support ⚡zap⚡\n\nBeing blazingly fast requires a constant feed of caffeine. I usually manage to\nprovide that to myself for myself. However, to support keeping the juices\nflowing and putting a smile on my face and that warm and cozy feeling into my\nheart, you can always [buy me a coffee](https://buymeacoffee.com/renerocksai)\n☕. All donations are welcomed 🙏 blazingly fast! That being said, just saying\n\"hi\" also works wonders with the smiles, warmth, and coziness 😊.\n\n## Examples\n\nYou build and run the examples via:\n\n```shell\n$ zig build [EXAMPLE]\n$ ./zig-out/bin/[EXAMPLE]\n```\n\n... where `[EXAMPLE]` is one of `hello`, `routes`, `serve`, ... see the [list of\nexamples above](#heres-what-works).\n\nExample: building and running the hello example:\n\n```shell\n$ zig build hello\n$ ./zig-out/bin/hello\n```\n\nTo just run an example, like `routes`, without generating an executable, run:\n\n```shell\n$ zig build run-[EXAMPLE]\n```\n\nExample: building and running the routes example:\n\n```shell\n$ zig build run-routes\n```\n\n### [hello](examples/hello/hello.zig)\n\n```zig\nconst std = @import(\"std\");\nconst zap = @import(\"zap\");\n\nfn on_request(r: zap.Request) !void {\n    if (r.path) |the_path| {\n        std.debug.print(\"PATH: {s}\\n\", .{the_path});\n    }\n\n    if (r.query) |the_query| {\n        std.debug.print(\"QUERY: {s}\\n\", .{the_query});\n    }\n    r.sendBody(\"\u003chtml\u003e\u003cbody\u003e\u003ch1\u003eHello from ZAP!!!\u003c/h1\u003e\u003c/body\u003e\u003c/html\u003e\") catch return;\n}\n\npub fn main() !void {\n    var listener = zap.HttpListener.init(.{\n        .port = 3000,\n        .on_request = on_request,\n        .log = true,\n    });\n    try listener.listen();\n\n    std.debug.print(\"Listening on 0.0.0.0:3000\\n\", .{});\n\n    // start worker threads\n    zap.start(.{\n        .threads = 2,\n        .workers = 2,\n    });\n}\n```\n\n\n\n\n\n","funding_links":["https://github.com/sponsors/renerocksai","https://buymeacoffee.com/renerocksai"],"categories":["C","Web, Networking \u0026 APIs","Zig","api","Network \u0026 Web","\u003ca name=\"C\"\u003e\u003c/a\u003eC"],"sub_categories":["Web Framework"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzigzap%2Fzap","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fzigzap%2Fzap","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzigzap%2Fzap/lists"}