working commit
This commit is contained in:
63
jwt.go
Normal file
63
jwt.go
Normal file
@@ -0,0 +1,63 @@
|
||||
package repocli
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
//"strconv"
|
||||
//"strings"
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
type JWT struct {
|
||||
Token string `json:"token"`
|
||||
AccessToken string `json:"access_token"`
|
||||
ExpiresIn int `json:"expires_in"`
|
||||
IssuedAt time.Time `json:"issued_at"`
|
||||
}
|
||||
|
||||
func (cli *Client) GetToken(ctx context.Context, uri string) (string, error) {
|
||||
var err error
|
||||
var token string
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, uri, nil)
|
||||
if err != nil {
|
||||
return token, err
|
||||
}
|
||||
req.Header.Set("User-Agent", cli.userAgent)
|
||||
req.Header.Set("Accept", "*/*")
|
||||
resp, err := cli.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return token, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode == http.StatusNotFound {
|
||||
return token, err
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
err := fmt.Errorf("Unxected response code %s", resp.Status)
|
||||
return token, err
|
||||
}
|
||||
mime := resp.Header.Get("Content-Type")
|
||||
if mime != "application/json" {
|
||||
err := fmt.Errorf("Empty MIME type declaration")
|
||||
return token, err
|
||||
}
|
||||
buffer := bytes.NewBuffer(nil)
|
||||
recSize, err := Copy(ctx, buffer, resp.Body)
|
||||
if recSize == 0 {
|
||||
err := fmt.Errorf("Zero actual body size")
|
||||
return token, err
|
||||
}
|
||||
tokenJson := buffer.Bytes()
|
||||
jwt := &JWT{}
|
||||
err = json.Unmarshal(tokenJson, jwt)
|
||||
if err != nil {
|
||||
return token, err
|
||||
}
|
||||
token = jwt.Token
|
||||
return token, err
|
||||
}
|
||||
Reference in New Issue
Block a user