-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
167 lines (134 loc) · 4.03 KB
/
Copy pathmain.go
File metadata and controls
167 lines (134 loc) · 4.03 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"sort"
"strconv"
"time"
)
type GitHubRepo struct {
Name string `json:"name"`
FullName string `json:"full_name"`
Description string `json:"description"`
HTMLURL string `json:"html_url"`
Language string `json:"language"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
PushedAt time.Time `json:"pushed_at"`
StarCount int `json:"stargazers_count"`
ForkCount int `json:"forks_count"`
Private bool `json:"private"`
Fork bool `json:"fork"`
Archived bool `json:"archived"`
}
type RepoResponse struct {
Repos []GitHubRepo `json:"repos"`
Total int `json:"total"`
}
type ErrorResponse struct {
Error string `json:"error"`
}
func fetchRepos(username, token string) ([]GitHubRepo, error) {
var allRepos []GitHubRepo
page := 1
client := &http.Client{Timeout: 15 * time.Second}
for {
url := fmt.Sprintf("https://api.github.com/users/%s/repos?per_page=100&page=%d&type=all", username, page)
if token != "" {
url = fmt.Sprintf("https://api.github.com/user/repos?per_page=100&page=%d&affiliation=owner", page)
}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Accept", "application/vnd.github.v3+json")
req.Header.Set("User-Agent", "github-timeline-app")
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to fetch repos: %w", err)
}
if resp.StatusCode == http.StatusUnauthorized {
resp.Body.Close()
return nil, fmt.Errorf("invalid token or unauthorized access")
}
if resp.StatusCode == http.StatusForbidden {
resp.Body.Close()
return nil, fmt.Errorf("rate limit exceeded or access forbidden")
}
if resp.StatusCode == http.StatusNotFound {
resp.Body.Close()
return nil, fmt.Errorf("user '%s' not found", username)
}
if resp.StatusCode != http.StatusOK {
resp.Body.Close()
return nil, fmt.Errorf("GitHub API returned status %d", resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return nil, fmt.Errorf("failed to read response: %w", err)
}
var repos []GitHubRepo
if err := json.Unmarshal(body, &repos); err != nil {
return nil, fmt.Errorf("failed to parse response: %w", err)
}
if len(repos) == 0 {
break
}
allRepos = append(allRepos, repos...)
remaining := resp.Header.Get("X-RateLimit-Remaining")
if remaining == "0" {
resetStr := resp.Header.Get("X-RateLimit-Reset")
resetUnix, _ := strconv.ParseInt(resetStr, 10, 64)
resetTime := time.Unix(resetUnix, 0)
return nil, fmt.Errorf("rate limit exceeded, resets at %s", resetTime.Format("15:04:05"))
}
if len(repos) < 100 {
break
}
page++
}
sort.Slice(allRepos, func(i, j int) bool {
return allRepos[i].CreatedAt.Before(allRepos[j].CreatedAt)
})
return allRepos, nil
}
func handleRepos(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
json.NewEncoder(w).Encode(ErrorResponse{Error: "Method not allowed"})
return
}
username := r.URL.Query().Get("username")
token := r.URL.Query().Get("token")
if username == "" && token == "" {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(ErrorResponse{Error: "Username is required"})
return
}
repos, err := fetchRepos(username, token)
if err != nil {
w.WriteHeader(http.StatusBadGateway)
json.NewEncoder(w).Encode(ErrorResponse{Error: err.Error()})
return
}
json.NewEncoder(w).Encode(RepoResponse{
Repos: repos,
Total: len(repos),
})
}
func main() {
fs := http.FileServer(http.Dir("static"))
http.Handle("/", fs)
http.HandleFunc("/api/repos", handleRepos)
port := ":3000"
log.Printf("Server starting on http://localhost%s", port)
log.Fatal(http.ListenAndServe(port, nil))
}