Files
request/github/github.go
Matheus Sampaio Queiroga 520d37c408
All checks were successful
Golang test / go-test (push) Successful in 26s
Add Gitea and Github basic clients
2025-04-02 22:31:24 -03:00

104 lines
2.4 KiB
Go

// Client to Github APIs
package github
import (
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"time"
"sirherobrine23.com.br/go-bds/request/v2"
)
var (
GithubAPI = &url.URL{Scheme: "https", Host: "api.github.com", Path: "/"} // Defaut github api
ErrToken error = errors.New("require Token to request")
err500 = request.RequestStatusFunction(func(res *http.Response) (*http.Response, error) {
buffLog, _ := io.ReadAll(res.Body)
if res.Body != nil {
res.Body.Close()
}
if len(buffLog) == 0 {
buffLog = []byte("not body response")
}
return nil, fmt.Errorf("cannot process request (%s), github api is down: %s", res.Request.URL.String(), buffLog)
})
processCodes = request.MapCode{
500: err500,
501: err500,
401: func(res *http.Response) (*http.Response, error) {
if res.Body != nil {
res.Body.Close()
}
return nil, ErrToken
},
403: func(res *http.Response) (*http.Response, error) {
if res.Body != nil {
res.Body.Close()
}
return nil, errors.New("cannot process request, authorization or not have permission")
},
429: func(res *http.Response) (*http.Response, error) {
if res.Body != nil {
res.Body.Close()
}
// x-ratelimit-reset
if window, err := strconv.Atoi(res.Header.Get("x-ratelimit-reset")); err == nil {
<-time.After(time.Duration(window))
}
return request.ReRequest(res)
},
}
)
// Create new Github Client with Github.com API host
func NewClient(Username, Repository, Token string) *Github {
return &Github{
Host: GithubAPI,
Repository: Repository,
Username: Username,
Token: Token,
}
}
// Create new Github Client
func NewClientHost(apiHost, Username, Repository, Token string) (*Github, error) {
hostUrl, err := url.Parse(apiHost)
if err != nil {
return nil, err
}
return &Github{
Host: hostUrl,
Repository: Repository,
Username: Username,
Token: Token,
}, nil
}
// Basic client to Github APIs
type Github struct {
Host *url.URL // Github API host
Token string // Github Token
// User and Repository name
Username, Repository string
}
// Return escapated Owner+/+Repository
func (client Github) repoPath() string {
return fmt.Sprintf("%s/%s", url.PathEscape(client.Username), url.PathEscape(client.Repository))
}
// Set token to header
func (client Github) authHeader(header *request.Header) {
if client.Token != "" {
(*header)["Authorization"] = fmt.Sprintf("Bearer %s", client.Token)
}
}