找回密码
 立即注册
首页 资源区 代码 使用zig语言制作简单博客网站(一)项目搭建 ...

使用zig语言制作简单博客网站(一)项目搭建

卢莹洁 前天 13:50
zig环境搭建


  • zig安装:下载zig (我们使用稳定的0.13版本)并解压,把zig所在目录添加到系统环境变量,cmd输入zig version进行验证
  • zls(zig语言服务)安装:下载zls 并解压,把zls所在目录添加到系统环境变量,cmd输入zls --version进行验证
  • vscode安装zig语言插件
    1.png

创建zigblog项目

桌面新建一个空文件夹zigblog,打开该文件夹右键打开cmd(没有的请自行cd到该目录),cmd执行命令zig init初始化项目,结果如下图
2.png

添加项目依赖


  • 我们使用zig开源项目 httpz 写博客后端api,用vscode打开项目,我们把httpz依赖添加到项目依赖管理文件build.zig.zon中,添加后如下,httpz的url和hash我是从 jetzig 项目抄过来的(jetzig项目是一个全栈开发项目,它基于httpz)。
  1. .{
  2.     .name = "zigblog",
  3.     .version = "0.0.1",
  4.     .dependencies = .{
  5.         .httpz = .{
  6.             .url = "https://github.com/karlseguin/http.zig/archive/fbca868592dc83ee3ee3cad414c62afa266f4866.tar.gz",
  7.             .hash = "122089946af5ba1cdfae3f515f0fa1c96327f42a462515fbcecc719fe94fab38d9b8",
  8.         }
  9.     },
  10.     .paths = .{
  11.         "build.zig",
  12.         "build.zig.zon",
  13.         "src",
  14.         // For example...
  15.         //"LICENSE",
  16.         //"README.md",
  17.     },
  18. }
复制代码

  • 之后我们在build.zig文件中添加httpz模块,后如下
  1.     const exe = b.addExecutable(.{
  2.         .name = "zigblog",
  3.         .root_source_file = b.path("src/main.zig"),
  4.         .target = target,
  5.         .optimize = optimize,
  6.     });
  7.     // 添加httpz模块
  8.     const httpz_module = b.dependency("httpz", .{ .target = target, .optimize = optimize }).module("httpz");
  9.     exe.root_module.addImport("httpz", httpz_module);
  10.     b.installArtifact(exe);
复制代码

  • 之后我们删除项目src下 root.zig 文件,删除 build.zig 文件中默认生成的测试代码,具体删除代码如下
  1.     // 删除
  2.     const lib_unit_tests = b.addTest(.{
  3.         .root_source_file = b.path("src/root.zig"),
  4.         .target = target,
  5.         .optimize = optimize,
  6.     });
  7.     // 删除
  8.     const run_lib_unit_tests = b.addRunArtifact(lib_unit_tests);
  9.     // 删除
  10.     test_step.dependOn(&run_lib_unit_tests.step);
复制代码

  • 之后我们修改src下 main.zig 文件,如下
  1. const std = @import("std");
  2. const httpz = @import("httpz");
  3. pub fn main() !void {
  4.     var gpa = std.heap.GeneralPurposeAllocator(.{}){};
  5.     const allocator = gpa.allocator();
  6.     var server = try httpz.Server().init(allocator, .{ .port = 5882 });
  7.     server.notFound(notFound);
  8.     server.errorHandler(errorHandler);
  9.     var router = server.router();
  10.     router.get("/api/user/:id", &getUser);
  11.     std.log.info("Listening on  http://127.0.0.1:5882/", .{});
  12.     try server.listen();
  13. }
  14. fn getUser(req: *httpz.Request, res: *httpz.Response) !void {
  15.     // status code 200 is implicit.
  16.     // The json helper will automatically set the res.content_type = httpz.ContentType.JSON;
  17.     // Here we're passing an inferred anonymous structure, but you can pass anytype
  18.     // (so long as it can be serialized using std.json.stringify)
  19.     try res.json(.{ .id = req.param("id").?, .name = "Teg" }, .{});
  20. }
  21. fn notFound(_: *httpz.Request, res: *httpz.Response) !void {
  22.     res.status = 404;
  23.     // you can set the body directly to a []u8, but note that the memory
  24.     // must be valid beyond your handler. Use the res.arena if you need to allocate
  25.     // memory for the body.
  26.     res.body = "Not Found";
  27. }
  28. // note that the error handler return `void` and not `!void`
  29. fn errorHandler(req: *httpz.Request, res: *httpz.Response, err: anyerror) void {
  30.     res.status = 500;
  31.     res.body = "Internal Server Error";
  32.     std.log.warn("httpz: unhandled exception for request: {s}\nErr: {}", .{ req.url.raw, err });
  33. }
复制代码

  • 之后我们在项目根目录下打开cmd执行命令 zig build run 进行依赖下载(从github下载,可能需要科学.上网)、编译、运行,如图,我们打开浏览器访问 http://127.0.0.1:5882/api/user/123456可查看到api访问成功了。
    3.png

    4.png


来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
您需要登录后才可以回帖 登录 | 立即注册