Passed
Push — main ( a0a36f...588928 )
by Clive
03:45
created

githubapi.*Timestamp.UnmarshalJSON   B

Complexity

Conditions 6

Size

Total Lines 22
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 15
nop 1
dl 0
loc 22
rs 8.6666
c 0
b 0
f 0
1
package githubapi
2
3
import (
4
	"encoding/json"
5
	"fmt"
6
	"net/http"
7
	"time"
8
)
9
10
var (
11
	APIURL       = "https://api.github.com/rate_limit"
12
	AuthHeader   = "Authorization"
13
	TokenEnvName = "GITHUB_TOKEN"
14
)
15
16
type Rate struct {
17
	Limit     int       `json:"limit"`
18
	Remaining int       `json:"remaining"`
19
	Reset     Timestamp `json:"reset"`
20
}
21
22
type Timestamp struct {
23
	time.Time
24
}
25
26
func (t *Timestamp) UnmarshalJSON(data []byte) error {
27
	var timestamp interface{}
28
	if err := json.Unmarshal(data, &timestamp); err != nil {
29
		return err
30
	}
31
32
	switch v := timestamp.(type) {
33
	case string:
34
		// Handle string representation of Unix timestamp
35
		parsedTime, err := time.Parse(time.RFC3339Nano, v)
36
		if err != nil {
37
			return err
38
		}
39
		t.Time = parsedTime
40
	case float64:
41
		// Handle numeric representation of Unix timestamp
42
		t.Time = time.Unix(int64(v), 0)
43
	default:
44
		return fmt.Errorf("unexpected type for timestamp: %T", v)
45
	}
46
47
	return nil
48
}
49
50
type RateLimit struct {
51
	Core Rate `json:"core"`
52
}
53
54
type RateLimitResponse struct {
55
	Resources RateLimit `json:"resources"`
56
}
57
58
func FetchRateLimit(client *http.Client, token string) (RateLimitResponse, error) {
59
	req, err := http.NewRequest("GET", APIURL, nil)
60
	if err != nil {
61
		return RateLimitResponse{}, err
62
	}
63
64
	if token != "" {
65
		req.Header.Set(AuthHeader, fmt.Sprintf("token %s", token))
66
	}
67
68
	resp, err := client.Do(req)
69
	if err != nil {
70
		return RateLimitResponse{}, err
71
	}
72
	defer resp.Body.Close()
73
74
	if resp.StatusCode != http.StatusOK {
75
		return RateLimitResponse{}, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
76
	}
77
78
	var rateLimitResponse RateLimitResponse
79
	if err := json.NewDecoder(resp.Body).Decode(&rateLimitResponse); err != nil {
80
		return RateLimitResponse{}, err
81
	}
82
83
	return rateLimitResponse, nil
84
}
85