Skip to content

Instantly share code, notes, and snippets.

@michidk
Last active April 21, 2025 16:29
Show Gist options
  • Save michidk/380c36827b3ef8f5452bc16471fea968 to your computer and use it in GitHub Desktop.
Save michidk/380c36827b3ef8f5452bc16471fea968 to your computer and use it in GitHub Desktop.
Simple Zig Webserver
const std = @import("std");
const net = std.net;
const io = std.io;
const Response = struct {
status: []const u8,
headers: []const u8,
body: []const u8,
};
pub fn main() !void {
const ipv4 = try net.Ip4Address.parse("127.0.0.1", 8080);
const localhost = net.Address{ .in = ipv4 };
var server = try localhost.listen();
defer server.deinit();
std.debug.print("Server gestartet auf http://127.0.0.1:8080\n", .{});
while (true) {
const client = try server.accept();
defer client.stream.close();
var buf: [1024]u8 = undefined;
const bytes_read = try client.stream.read(&buf);
const request_bytes = buf[0..bytes_read];
std.debug.print("Neue Anfrage erhalten:\n{s}\n", .{request_bytes});
var response = Response{
.status = "200 OK",
.headers = "Content-Type: text/html\r\n",
.body = "<html><body><h1>Hallo von Zig!</h1></body></html>",
};
try sendResponse(client.stream, &response);
}
}
fn sendResponse(stream: net.Stream, response: *Response) !void {
const writer = stream.writer();
try writer.print("HTTP/1.1 {s}\r\n", .{response.status});
try writer.writeAll(response.headers);
try writer.writeAll("\r\n");
try writer.writeAll(response.body);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment