Skip to content

Commit

Permalink
fix: github token getter (#205)
Browse files Browse the repository at this point in the history
This pull request includes several changes to the
`change-insight/lib/github/common.go` file to enhance security and
improve error handling. The most important changes include the addition
of environment variable support for GitHub tokens and improved error
handling for API calls.

Enhancements to security:

*
[`change-insight/lib/github/common.go`](diffhunk://#diff-5251738818d44ec5f50892200dc833237918634443d53426422f57f0a4ea14a9L28-R57):
Replaced the hardcoded GitHub token with a function that retrieves the
token from the environment variable `GITHUB_TOKEN`.

Improvements to error handling:

*
[`change-insight/lib/github/common.go`](diffhunk://#diff-5251738818d44ec5f50892200dc833237918634443d53426422f57f0a4ea14a9L28-R57):
Added error handling for unexpected status codes in the `apiCall`
function, logging the status code and returning an error if it is not
`http.StatusOK`.

Currently, the sub app that changed in this PR is planed to be
deprecated.
  • Loading branch information
wuhuizuo authored Nov 16, 2024
1 parent 8676f4b commit fe2191b
Showing 1 changed file with 22 additions and 5 deletions.
27 changes: 22 additions & 5 deletions change-insight/lib/github/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ package github
import (
"log"
"net/http"
"os"
)

type Repo struct {
Org string // eg: pingcap
Repo string // eg: tidb
}

type UserInfo struct {
Login string `json:"login"`
Id int `json:"id"`
Expand All @@ -25,17 +27,32 @@ type labelInfo struct {
Description string `json:"description"`
}

var token string = "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"
var apiURL string = "https://api.github.com/repos/"

func getGitHubToken() string {
return os.Getenv("GITHUB_TOKEN")
}

func apiCall(apiUrl string) (*http.Response, error) {
req, err := http.NewRequest("GET", apiUrl, nil)
if err != nil {
log.Printf("request init error : %s \n", err.Error())
log.Printf("request init error: %s\n", err.Error())
return nil, err
}

req.Header.Set("Accept", "application/vnd.github+json")
req.Header.Set("Authorization", "token "+token)
//log.Printf("req: %+v \n", req)
return http.DefaultClient.Do(req)
req.Header.Set("Authorization", "token " + getGitHubToken())

resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Printf("request error: %s\n", err.Error())
return nil, err
}

if resp.StatusCode != http.StatusOK {
log.Printf("unexpected status code: %d\n", resp.StatusCode)
return resp, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}

return resp, nil
}

0 comments on commit fe2191b

Please sign in to comment.