Search code examples
zig

Expected type '*http.Client.Request', found '*const http.Client.Request'


Trying to make http GET request as:

const std = @import("std");

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    const allocator = gpa.allocator();
    _ = gpa.deinit();

    var client: std.http.Client = .{ .allocator = allocator };
    defer client.deinit();

    // Parse the URI.
    const uri = std.Uri.parse("http://httpbin.org/get") catch unreachable;

    // Create the headers that will be sent to the server.
    var headers = std.http.Headers{ .allocator = allocator };
    defer headers.deinit();

    // Accept anything.
    try headers.append("accept", "*/*");
    try headers.append("accept", "application/json");

    if (client.request(.GET, uri, headers, .{})) |req| {
        defer req.deinit();
        try req.start();
        try req.wait();

        std.log.debug("status: {}", .{req.response.status});
    } else |err| {
        std.log.err("{any}", .{err});
    }

    //  try std.testing.expect(req.response.status == .ok);
}

But got the error:

main.zig:24:16: error: expected type '*http.Client.Request', found '*const http.Client.Request'
        try req.start();
            ~~~^~~~~~
main.zig:24:16: note: cast discards const qualifier
/usr/lib/zig/std/http/Client.zig:538:23: note: parameter type declared here
    pub fn start(req: *Request) StartError!void {
                      ^~~~~~~~

Solution

  • I found the correct answer, just need to copy it to a variable, now my running code is:

    const std = @import("std");
    
    pub fn main() !void {
        var gpa = std.heap.GeneralPurposeAllocator(.{}){};
        const allocator = gpa.allocator();
        defer if (gpa.deinit() != .ok) {
            // oh no, we've got a leak
            std.log.err("We got a leack", .{});
        } else {
            std.log.debug("memory managed correctly", .{});
        };
    
        var client: std.http.Client = .{ .allocator = allocator };
        defer client.deinit();
    
        // Parse the URI.
        const uri = std.Uri.parse("http://httpbin1.org/get") catch unreachable;
    
        // Create the headers that will be sent to the server.
        var headers = std.http.Headers{ .allocator = allocator };
        defer headers.deinit();
    
        // Accept anything.
        try headers.append("accept", "*/*");
        try headers.append("accept", "application/json");
    
        if (client.request(.GET, uri, headers, .{})) |const_req| {
            var req = const_req;
            defer req.deinit();
            try req.start();
            try req.wait();
    
            std.log.debug("status: {}", .{req.response.status});
    
        } else |err| {
            std.log.err("error: {}", .{err});
        }
    }
    

    And I got correctly the below output:

    error: error: error.UnknownHostName
    debug: memory managed correctly