-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhttp.go
More file actions
90 lines (73 loc) · 2.05 KB
/
http.go
File metadata and controls
90 lines (73 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// Copyright (c) Codesphere Inc.
// SPDX-License-Identifier: Apache-2.0
package portal
import (
"fmt"
"io"
"log"
"net/http"
)
type Http interface {
Request(url string, method string, body io.Reader) (responseBody []byte, err error)
Get(url string) (responseBody []byte, err error)
Download(url string, file io.Writer, quiet bool) error
}
type HttpWrapper struct {
HttpClient HttpClient
}
func NewHttpWrapper() *HttpWrapper {
return &HttpWrapper{
HttpClient: NewConfiguredHttpClient(),
}
}
func (c *HttpWrapper) Request(url string, method string, body io.Reader) (responseBody []byte, err error) {
req, err := http.NewRequest(method, url, body)
if err != nil {
log.Fatalf("Error creating request: %v", err)
return
}
resp, err := c.HttpClient.Do(req)
if err != nil {
return []byte{}, fmt.Errorf("failed to send request: %w", err)
}
defer func() {
_ = resp.Body.Close()
}()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return []byte{}, fmt.Errorf("failed request with status: %d", resp.StatusCode)
}
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return []byte{}, fmt.Errorf("failed to read response body: %w", err)
}
return respBody, nil
}
func (c *HttpWrapper) Get(url string) (responseBody []byte, err error) {
return c.Request(url, http.MethodGet, nil)
}
func (c *HttpWrapper) Download(url string, file io.Writer, quiet bool) error {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
resp, err := c.HttpClient.Do(req)
if err != nil {
return fmt.Errorf("failed to send request: %w", err)
}
defer func() {
_ = resp.Body.Close()
}()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return fmt.Errorf("failed to get body: %d", resp.StatusCode)
}
counter := file
if !quiet {
counter = NewWriteCounterWithTotal(file, resp.ContentLength, 0)
}
_, err = io.Copy(counter, resp.Body)
if err != nil {
return fmt.Errorf("failed to copy response body to file: %w", err)
}
log.Println("Download finished successfully.")
return nil
}