🙄

【C 言語】【Zig】cURL で HTTP/2 リクエスト

2024/04/25に公開

以前書いたコードが動くか確認

#include <stdio.h>
#include <curl/curl.h>
 
int main(void)
{
  CURL *curl;
  CURLcode res;

  curl = curl_easy_init();

  if (curl) {
    curl_easy_setopt(curl, CURLOPT_URL,
      "https://nghttp2.org/httpbin/get");
    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
    curl_easy_setopt(curl, CURLOPT_HTTP_VERSION,
      CURL_HTTP_VERSION_2_0);

    res = curl_easy_perform(curl);
    curl_easy_cleanup(curl);
  }

  return 0;
}

Zig の場合は次のとおり

const std = @import("std");
const cURL = @cImport({
    @cInclude("curl/curl.h");
});

pub fn main() !void {
  const handle = cURL.curl_easy_init();
  defer cURL.curl_easy_cleanup(handle);

  _ = cURL.curl_easy_setopt(handle, cURL.CURLOPT_URL,
        "https://nghttp2.org/httpbin/get");
  _ = cURL.curl_easy_setopt(handle, cURL.CURLOPT_HTTP_VERSION,
        cURL.CURL_HTTP_VERSION_2_0);
  _ = cURL.curl_easy_setopt(handle, cURL.CURLOPT_VERBOSE,
        @as(c_long, 1));

  _ = cURL.curl_easy_perform(handle);
}

実行結果は次のとおり

zig run test.c -lc -lcurl
zig run test.zig -lc -lcurl
*   Trying [2400:8902::f03c:91ff:fe69:a454]:443...
*   Trying 139.162.123.134:443...
* Connected to nghttp2.org (139.162.123.134) port 443 (#0)
* ALPN: offers h2,http/1.1
* SSL connection using TLSv1.3 / TLS_AES_256_GCM_SHA384
* ALPN: server accepted h2
* Server certificate:
*  subject: CN=nghttp2.org
*  start date: Apr 20 00:00:04 2024 GMT
*  expire date: Jul 19 00:00:03 2024 GMT
*  issuer: C=US; O=Let's Encrypt; CN=R3
*  SSL certificate verify result: unable to get local issuer certificate (20), continuing anyway.
* using HTTP/2
* h2h3 [:method: GET]
* h2h3 [:path: /httpbin/get]
* h2h3 [:scheme: https]
* h2h3 [:authority: nghttp2.org]
* h2h3 [accept: */*]
* Using Stream ID: 1 (easy handle 0x2249f30)
> GET /httpbin/get HTTP/2
Host: nghttp2.org
accept: */*

* old SSL session ID is stale, removing
< HTTP/2 200 
< date: Thu, 25 Apr 2024 06:40:35 GMT
< content-type: application/json
< content-length: 163
< access-control-allow-origin: *
< access-control-allow-credentials: true
< x-backend-header-rtt: 0.003203
< strict-transport-security: max-age=31536000
< server: nghttpx
< alt-svc: h3=":443"; ma=3600, h3-29=":443"; ma=3600
< via: 1.1 nghttpx
< x-frame-options: SAMEORIGIN
< x-xss-protection: 1; mode=block
< x-content-type-options: nosniff
< 
{
  "args": {}, 
  "headers": {
    "Accept": "*/*", 
    "Host": "nghttp2.org"
  }, 
  "origin": "115.162.203.179", 
  "url": "https://nghttp2.org/httpbin/get"
}
* Connection #0 to host nghttp2.org left intact

Discussion