v / vlib / net / s3 / http_bridge.v
51 lines · 47 sloc · 1.42 KB · 4142432483c4e8de44ab7b0d6ac944f3251e03c8
Raw
1// Copyright (c) 2019-2026 Alexander Medvednikov. All rights reserved.
2// Use of this source code is governed by an MIT license
3// that can be found in the LICENSE file.
4module s3
5
6import net.http
7
8// init registers an `s3://` scheme handler with `net.http` so that
9// `http.fetch(url: 's3://...')` and friends route here transparently. Only
10// active when this module is imported.
11fn init() {
12 http.register_scheme('s3', http_fetch_handler)
13}
14
15// http_fetch_handler bridges `http.fetch` into `s3.fetch`. Credentials are
16// pulled from the environment (`S3_*`, `AWS_*`, `CELLAR_ADDON_*`, …); for
17// explicit credentials, callers should use `s3.fetch` directly.
18fn http_fetch_handler(config http.FetchConfig) !http.Response {
19 resp := fetch(config.url,
20 method: config.method
21 body: config.data.bytes()
22 credentials: Credentials.from_env()
23 content_type: config.header.get(.content_type) or { '' }
24 )!
25 mut header := http.new_header()
26 for k, v in resp.headers {
27 header.add_custom(k, v) or {}
28 }
29 if resp.content_type != '' {
30 header.set(.content_type, resp.content_type)
31 }
32 if resp.etag != '' {
33 header.set(.etag, resp.etag)
34 }
35 return http.Response{
36 status_code: resp.status_code
37 body: resp.body.bytestr()
38 header: header
39 }
40}
41
42fn http_method_to_string(m http.Method) string {
43 return match m {
44 .get { 'GET' }
45 .put { 'PUT' }
46 .post { 'POST' }
47 .delete { 'DELETE' }
48 .head { 'HEAD' }
49 else { 'GET' }
50 }
51}
52