diff options
-rw-r--r-- | main.go | 94 |
1 files changed, 94 insertions, 0 deletions
@@ -0,0 +1,94 @@ +package main + +import ( + "encoding/json" + "fmt" + "log" + "net/http" + "os" + "time" +) + +// Define the structure for GitHub commit activity response +type CommitActivity struct { + Total int `json:"total"` +} + +// Function to fetch the user's commit count +func getCommitCount(username string) (int, error) { + // Set up the request URL + currentYear := time.Now().Year() + url := fmt.Sprintf("https://api.github.com/search/commits?q=author:%s+committer-date:%d-01-01..%d-12-31", username, currentYear, currentYear) + + // Retrieve the GitHub token from environment variables + githubToken := os.Getenv("GITHUB_TOKEN") + if githubToken == "" { + return 0, fmt.Errorf("GITHUB_TOKEN environment variable is not set") + } + + // Create a new HTTP request + req, err := http.NewRequest("GET", url, nil) + if err != nil { + return 0, err + } + + // Add necessary headers + req.Header.Add("Accept", "application/vnd.github.cloak-preview") + req.Header.Add("Authorization", "Bearer "+githubToken) + + // Perform the request + client := &http.Client{} + resp, err := client.Do(req) + if err != nil { + return 0, err + } + defer resp.Body.Close() + + // Check if the response status code is 200 OK + if resp.StatusCode != http.StatusOK { + return 0, fmt.Errorf("GitHub API returned status: %s", resp.Status) + } + + // Parse the response body + var result map[string]interface{} + if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { + return 0, err + } + + // Extract total count of commits + totalCommits, ok := result["total_count"].(float64) + if !ok { + return 0, fmt.Errorf("could not parse total count") + } + + return int(totalCommits), nil +} + +// API handler for fetching commit count +func commitCountHandler(w http.ResponseWriter, r *http.Request) { + // Get the username from query parameters + username := r.URL.Query().Get("username") + if username == "" { + http.Error(w, "username parameter is required", http.StatusBadRequest) + return + } + + // Fetch the commit count + count, err := getCommitCount(username) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + // Return the commit count as JSON + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]int{"commit_count": count}) +} + +func main() { + // Set up the HTTP server + http.HandleFunc("/commit-count", commitCountHandler) + fmt.Println("Server is running on port 8080...") + log.Fatal(http.ListenAndServe(":8080", nil)) +} + |