package main import ( "encoding/json" "fmt" "log" "net/http" "os" "time" ) // 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 difference and daily average func commitDifferenceHandler(w http.ResponseWriter, r *http.Request) { // Get usernames from query parameters username1 := r.URL.Query().Get("username1") username2 := r.URL.Query().Get("username2") if username1 == "" || username2 == "" { http.Error(w, "Both username1 and username2 parameters are required", http.StatusBadRequest) return } // Fetch commit counts for both users count1, err := getCommitCount(username1) if err != nil { http.Error(w, fmt.Sprintf("Error fetching commits for %s: %v", username1, err), http.StatusInternalServerError) return } count2, err := getCommitCount(username2) if err != nil { http.Error(w, fmt.Sprintf("Error fetching commits for %s: %v", username2, err), http.StatusInternalServerError) return } // Calculate the difference and remaining days difference := abs(count1 - count2) remainingDays := daysUntilEndOfYear() dailyAverage := difference / remainingDays // Return the results as JSON w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]interface{}{ "commit_count_user1": count1, "commit_count_user2": count2, "difference": difference, "remaining_days": remainingDays, "daily_average": dailyAverage, }) } // Utility function to calculate absolute value func abs(x int) int { if x < 0 { return -x } return x } // Utility function to calculate days remaining in the year func daysUntilEndOfYear() int { now := time.Now() endOfYear := time.Date(now.Year(), time.December, 31, 23, 59, 59, 0, time.UTC) return int(endOfYear.Sub(now).Hours() / 24) } func main() { // Set up the HTTP server http.HandleFunc("/commit-difference", commitDifferenceHandler) fmt.Println("Server is running on port 3001...") log.Fatal(http.ListenAndServe(":3001", nil)) }