Sample code for 30+ languages & platforms
Zig

Manually Follow HTTP Redirects

See more HTTP Examples

Demonstrates how to manually follow redirects for an HTTP GET.

Chilkat Zig Downloads

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

    // This example requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    const http = try chilkat.Http.init();
    defer http.deinit();

    // The FollowRedirects property controls whether redirects
    // are automatically followed.  The default behavior is to
    // automatically follow redirects.

    // Explicitly set FollowRedirects so that redirects are NOT automatically taken:
    http.setFollowRedirects(false);

    const resp = try chilkat.HttpResponse.init();
    defer resp.deinit();
    http.httpNoBody("GET", "http://yandex.ru/", resp) catch {
        std.debug.print("{s}\n", .{try http.getLastErrorText(alloc)});
        return;
    };

    var status: i32 = resp.getStatusCode();
    std.debug.print("HTTP Response Status: {d}\n", .{status});

    // The FinalRedirectUrl property will contain the redirect URL
    // If FollowRedirects was equal to true, then all of the
    // intermediate redirects (if any) would be followed until
    // there were no more redirects.  However, because
    // FollowRedirects is not true, FinalRedirectUrl contains
    // the next redirect URL.

    var loop_count: i32 = 0;

    while (status == 302) {
        std.debug.print("Redirect URL: {s}\n", .{try http.getFinalRedirectUrl(alloc)});

        const next_url = try http.getFinalRedirectUrl(alloc);
        http.httpNoBody("GET", next_url, resp) catch {
            std.debug.print("{s}\n", .{try http.getLastErrorText(alloc)});
            return;
        };

        status = resp.getStatusCode();
        std.debug.print("HTTP Response Status: {d}\n", .{status});

        // For safety, prevent infinite loops by
        // keeping a loopCount and only allows following a max
        // of 10 redirects:
        loop_count = loop_count + 1;
        if (loop_count > 10) {
            std.debug.print("Too many redirects.\n", .{});
            return;
        }
    }
}