Added basic HTTP 1.1 server primer

Author Mitja Felicijan <mitja.felicijan@gmail.com> 2024-09-16 18:44:51 +0200
Committer Mitja Felicijan <mitja.felicijan@gmail.com> 2024-09-16 18:44:51 +0200
Commit 135321620a433778be784ed8811af40a8cfb2875 (patch)
-rw-r--r-- zig-http/Makefile 2
-rw-r--r-- zig-http/main.zig 31
2 files changed, 33 insertions, 0 deletions
diff --git a/zig-http/Makefile b/zig-http/Makefile
  
1
default:
  
2
	zig run main.zig
diff --git a/zig-http/main.zig b/zig-http/main.zig
  
1
// https://www.rfc-editor.org/rfc/rfc2616
  
2
  
  
3
// NOTE: This is just a barebones example and it has a bunch of bugs there
  
4
//       so do not use this for anything seriously.
  
5
  
  
6
const std = @import("std");
  
7
  
  
8
pub fn main() anyerror!void {
  
9
    const self_addr = try std.net.Address.resolveIp("127.0.0.1", 6969);
  
10
    var listener = std.net.StreamServer.init(.{});
  
11
    try (&listener).listen(self_addr);
  
12
  
  
13
    std.log.info("Listening on {}; press Ctrl-C to exit...", .{self_addr});
  
14
  
  
15
    while ((&listener).accept()) |conn| {
  
16
        std.log.info("Accepted Connection from: {}", .{conn.address});
  
17
  
  
18
        // Basic HTTP 1.1 header.
  
19
        _ = try conn.stream.write("HTTP/1.1 200 OK\r\n");
  
20
        _ = try conn.stream.write("Connection: close\r\n");
  
21
        _ = try conn.stream.write("Content-Type: text/html; charset=utf-8\r\n");
  
22
        _ = try conn.stream.write("\r\n");
  
23
  
  
24
        // Actual response.
  
25
        _ = try conn.stream.write("<h1>Oh, hi Mark!</h1><p>It’s not true! It’s bullshit! I did not hit her! I did not!</p>\r\n");
  
26
  
  
27
        conn.stream.close();
  
28
    } else |err| {
  
29
        return err;
  
30
    }
  
31
}