Zap is the zig replacement for the REST APIs I used to write in python with Flask and mongodb, etc. It can be considered to be a microframework for web applications.
What I needed as a replacement was a blazingly fast and robust HTTP server that I could use with Zig, and I chose to wrap the superb evented networking C library facil.io. Zap wraps and patches facil.io - the C web application framework.
After having used ZAP in production for a year, I can confidently assert that it proved to be:
Exactly the goals I set out to achieve!
have to keep up with frequent breaking changes. It's an "LTS feature". If you
want to use zig master, use the zig-master
branch but be aware that I don't
provide build.zig.zon
snippets or tagged releases for it for the time being.
If you know what you are doing, that shouldn't stop you from using it with zig
master though.
zig build run-docserver
to serve them locally.-Dopenssl
flag or the environment variable ZAP_USE_OPENSSL=true
:
.openssl = true,
(in dependent projects' build.zig,
b.dependency("zap" .{...})
)ZAP_USE_OPENSSL=true zig build https
zig build -Dopenssl=true https
I recommend checking out Endpoint-based examples for more realistic use cases. Most of the examples are super stripped down to only include what's necessary to show a feature.
NOTE: To see API docs, run zig build run-docserver
. To specify a custom
port and docs dir: zig build docserver && zig-out/bin/docserver --port=8989 --docs=path/to/docs
.
build.zig
now uses the new Zig package
manager for its C-dependencies, no git submodules anymore.
/users
endpoint for performing PUT/DELETE/GET/POST operations and listing
users, together with a simple frontend to play with. It also introduces a
/stop
endpoint that shuts down Zap, so memory leak detection can be
performed in main().
GeneralPurposeAllocator
to report memory leaks when ZAP is shut down.
The StopEndpoint just stops ZAP when
receiving a request on the /stop
route.zap.Middleware.EndpointHandler
. Mixing endpoints
in your middleware chain allows for usage of Zap's authenticated endpoints and
your custom endpoints. Since Endpoints use a simpler API, you have to use
r.setUserContext()
and r.getUserContext()
with the request if you want to
access the middleware context from a wrapped endpoint. Since this mechanism
uses an *anyopaque
pointer underneath (to not break the Endpoint API), it is
less type-safe than zap.Middleware
's use of contexts.setUserContext()
and getUserContext()
, you can, of course use those two in
projects that don't use zap.Endpoint
or zap.Middleware
, too, if you
really, really, absolutely don't find another way to solve your context
problem. We recommend using a zap.Endpoint
inside of a struct that
can provide all the context you need instead. You get access to your
struct in the callbacks via the @fieldParentPtr()
trick that is used
extensively in Zap's examples, like the endpoint
example.r.sendError(err, status_code)
when you catch an error and a stack trace
will be returned to the client / browser.-Dopenssl=true
or the environment
variable ZAP_USE_OPENSSL
set to true
and requires openssl dev dependencies
(headers, lib) to be installed on the system.
ZAP_USE_OPENSSL=true zig build run-https
zig build -Dopenssl=true run-https
zap.Router
to dispatch to handlers by HTTP path.I'll continue wrapping more of facil.io's functionality and adding stuff to zap to a point where I can use it as the JSON REST API backend for real research projects, serving thousands of concurrent clients.
Claiming to be blazingly fast is the new black. At least, Zap doesn't slow you down and if your server performs poorly, it's probably not exactly Zap's fault. Zap relies on the facil.io framework and so it can't really claim any performance fame for itself. In this initial implementation of Zap, I didn't care about optimizations at all.
But, how fast is it? Being blazingly fast is relative. When compared with a simple GO HTTP server, a simple Zig Zap HTTP server performed really good on my machine (x86_64-linux):
Update: Thanks to @felipetrz, I got to test against more realistic Python
and Rust examples. Both python sanic
and rust axum
were easy enough to
integrate.
Update: I have automated the benchmarks. See blazingly-fast.md for more information. Also, thanks to @alexpyattaev, the benchmarks are fairer now, pinning server and client to specific CPU cores.
Update: I have consolidated the benchmarks to one good representative per language. See more details in blazingly-fast.md. It contains rust implementations that come pretty close to Zap's performance in the simplistic testing scenario.
So, being somewhere in the ballpark of basic GO performance, zig zap seems to be ... of reasonable performance 😎.
I can rest my case that developing ZAP was a good idea because it's faster than both alternatives: a) staying with Python, and b) creating a GO + Zig hybrid.
See more details in blazingly-fast.md.
ZAP is very robust. In fact, it is so robust that I was confidently able to only work with in-memory data (RAM) in all my ZAP projects so far: over 5 large online research experiments. No database, no file persistence, until I hit "save" at the end 😊.
So I was able to postpone my cunning data persistence strategy that's similar to a mark-and-sweep garbage collector and would only persist "dirty" data when traffic is low, in favor of getting stuff online more quickly. But even if implemented, such a persistence strategy is risky because when traffic is not low, it means the system is under (heavy) load. Would you confidently NOT save data when load is high and the data changes most frequently -> the potential data loss is maximized?
To answer that question, I just skipped it. I skipped saving any data until receiving a "save" signal via API. And it worked. ZAP just kept on zapping. When traffic calmed down or all experiment participants had finished, I hit "save" and went on analyzing the data.
Handling all errors does pay off after all. No hidden control flow, no hidden errors or exceptions is one of Zig's strengths.
To be honest: There are still pitfalls. E.g. if you request large stack sizes for worker threads, Zig won't like that and panic. So make sure you don't have local variables that require tens of megabytes of stack space.
See the StopEndpoint in the
endpoint example. That example uses ZIG's awesome
GeneralPurposeAllocator
to report memory leaks when ZAP is shut down. The
StopEndpoint
just stops ZAP when receiving a request on the /stop
route.
You can use the same strategy in your debug builds and tests to check if your code leaks memory.
Make sure you have zig 0.13.0 installed. Fetch it from here.
$ git clone https://github.com/zigzap/zap.git $ cd zap $ zig build run-hello $ # open http://localhost:3000 in your browser
... and open http://localhost:3000 in your browser.
Make sure you have the latest zig release (0.13.0) installed. Fetch it from here.
If you don't have an existing zig project, create one like this:
$ mkdir zaptest && cd zaptest $ zig init $ git init ## (optional)
Note: Nix/NixOS users are lucky; you can use the existing flake.nix
and run
nix develop
to get a development shell providing zig and all
dependencies to build and run the GO, python, and rust examples for the
wrk
performance tests. For the mere building of zap projects,
nix develop .#build
will only fetch zig 0.11.0. TODO: upgrade to latest zig.
With an existing Zig project, adding Zap to it is easy:
build.zig.zon
build.zig
To add zap to build.zig.zon
:
<!-- INSERT_DEP_END -->.{ .name = "My example project", .version = "0.0.1", .dependencies = .{ // zap v0.8.0 .zap = .{ .url = "https://github.com/zigzap/zap/archive/v0.8.0.tar.gz", .hash = "12209936c3333b53b53edcf453b1670babb9ae8c2197b1ca627c01e72670e20c1a21", }, }, .paths = .{ "", }, }
Then, in your build.zig
's build
function, add the following before
b.installArtifact(exe)
:
const zap = b.dependency("zap", .{ .target = target, .optimize = optimize, .openssl = false, // set to true to enable TLS support }); exe.root_module.addImport("zap", zap.module("zap"));
From then on, you can use the Zap package in your project. Check out the examples to see how to use Zap.
You can change the URL to Zap in your build.zig.zon
0.0.9
zap
Go to the release page. Every release
will state its version number and also provide instructions for changing
build.zig.zon
and build.zig
.
See here.
At the current time, I can only add to zap what I need for my personal and professional projects. While this happens blazingly fast, some if not all nice-to-have additions will have to wait. You are very welcome to help make the world a blazingly fast place by providing patches or pull requests, add documentation or examples, or interesting issues and bug reports - you'll know what to do when you receive your calling 👼.
Check out CONTRIBUTING.md for more details.
See also introducing.md for more on the state and progress of this project.
We now have our own ZAP discord server!!!
You can also reach me on the zig showtime discord server under the handle renerocksai (renerocksai#1894).
Being blazingly fast requires a constant feed of caffeine. I usually manage to provide that to myself for myself. However, to support keeping the juices flowing and putting a smile on my face and that warm and cozy feeling into my heart, you can always [buy me a
字节跳动发布的AI编程神器IDE
Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。
AI小说写作助手,一站式润色、改写、扩写
蛙蛙写作—国内先进的AI写作平台,涵盖小说、学术、社交媒体等多场景。提供续写、改写、润色等功能,助力创作者高效优化写作流程。界面简洁,功能全面,适合各类写作者提升内容品质和工作效率。
全能AI智能助手,随时解答生活与工作的多样问题
问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。
实时语音翻译/同声传译工具
Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。
一键生成PPT和Word,让学习生活更轻松
讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。
深度推理能力全新升级,全面对标OpenAI o1
科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。
一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型
Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。 用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。
AI助力,做PPT更简单!
咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。
选题、配图、成文,一站式创作,让内容运营更高效
讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。
专业的AI公文写作平台,公文写作神器
AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。
最新AI工具、AI资讯
独家AI资源、AI项目落地
微信扫一扫关注公众号