如何使用Go语言提取GitHub API中仓库的stargazers_count(含openebs示例)
Got it, let's walk through how to pull the stargazers_count from GitHub's API using Go. We'll use the openebs/openebs repo endpoint as our example—super straightforward once you get the hang of it.
Step 1: Define a Struct to Match the JSON Data
Go relies on static typing, so we need a struct that maps to the specific field we want from the API response. Since we only care about stargazers_count, we can keep it minimal:
package main import ( "encoding/json" "fmt" "log" "net/http" ) // GitHubRepo maps the relevant field from the GitHub API response type GitHubRepo struct { StargazersCount int `json:"stargazers_count"` }
- The struct field
StargazersCountis capitalized so it's exported (required for the JSON decoder to access it). - The
json:"stargazers_count"tag tells the decoder to map the JSON's snake_case field to our struct's CamelCase field.
Step 2: Make the API Request
Next, we'll send a GET request to the GitHub API endpoint. We need to handle errors and ensure we close the response body to avoid resource leaks:
func main() { // Send GET request to the GitHub API resp, err := http.Get("https://api.github.com/repos/openebs/openebs") if err != nil { log.Fatalf("Failed to send request to GitHub API: %v", err) } defer resp.Body.Close() // Always close the response body when done // Check if the request was successful (status code 200 OK) if resp.StatusCode != http.StatusOK { log.Fatalf("API returned non-success status: %s", resp.Status) }
Step 3: Decode the JSON Response
Now we'll decode the JSON response body into our GitHubRepo struct. Using json.NewDecoder is more efficient than reading the entire body into a byte slice first:
// Decode JSON response into our struct var repo GitHubRepo err = json.NewDecoder(resp.Body).Decode(&repo) if err != nil { log.Fatalf("Failed to decode JSON response: %v", err) }
Step 4: Access the stargazers_count Value
Finally, we can access the StargazersCount field from our struct and use it however we want:
// Print out the star count fmt.Printf("The openebs/openebs repository has %d stars\n", repo.StargazersCount) }
Full Working Code
Putting it all together, here's the complete script you can run:
package main import ( "encoding/json" "fmt" "log" "net/http" ) type GitHubRepo struct { StargazersCount int `json:"stargazers_count"` } func main() { resp, err := http.Get("https://api.github.com/repos/openebs/openebs") if err != nil { log.Fatalf("Failed to send request: %v", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { log.Fatalf("Request failed with status: %s", resp.Status) } var repo GitHubRepo err = json.NewDecoder(resp.Body).Decode(&repo) if err != nil { log.Fatalf("Failed to decode JSON: %v", err) } fmt.Printf("openebs/openebs has %d stars\n", repo.StargazersCount) }
Quick Notes
- Rate Limiting: GitHub's API has rate limits for unauthenticated requests (60 requests per hour). If you need more calls, add an
Authorizationheader with a personal access token. - Extending the Struct: If you want more fields (like
name,description), just add them to theGitHubRepostruct with the corresponding JSON tags.
内容的提问来源于stack exchange,提问作者faruq

