github.com/ungtb10d/cli/v2@v2.0.0-20221110210412-98537dd9d6a1/pkg/cmd/gpg-key/list/http.go (about)

     1  package list
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  	"fmt"
     7  	"io"
     8  	"net/http"
     9  	"strings"
    10  	"time"
    11  
    12  	"github.com/ungtb10d/cli/v2/api"
    13  	"github.com/ungtb10d/cli/v2/internal/ghinstance"
    14  )
    15  
    16  var errScopes = errors.New("insufficient OAuth scopes")
    17  
    18  type emails []email
    19  
    20  type email struct {
    21  	Email string `json:"email"`
    22  }
    23  
    24  func (es emails) String() string {
    25  	s := []string{}
    26  	for _, e := range es {
    27  		s = append(s, e.Email)
    28  	}
    29  	return strings.Join(s, ", ")
    30  }
    31  
    32  type gpgKey struct {
    33  	KeyID     string    `json:"key_id"`
    34  	PublicKey string    `json:"public_key"`
    35  	Emails    emails    `json:"emails"`
    36  	CreatedAt time.Time `json:"created_at"`
    37  	ExpiresAt time.Time `json:"expires_at"`
    38  }
    39  
    40  func userKeys(httpClient *http.Client, host, userHandle string) ([]gpgKey, error) {
    41  	resource := "user/gpg_keys"
    42  	if userHandle != "" {
    43  		resource = fmt.Sprintf("users/%s/gpg_keys", userHandle)
    44  	}
    45  	url := fmt.Sprintf("%s%s?per_page=%d", ghinstance.RESTPrefix(host), resource, 100)
    46  	req, err := http.NewRequest("GET", url, nil)
    47  	if err != nil {
    48  		return nil, err
    49  	}
    50  
    51  	resp, err := httpClient.Do(req)
    52  	if err != nil {
    53  		return nil, err
    54  	}
    55  	defer resp.Body.Close()
    56  
    57  	if resp.StatusCode == 404 {
    58  		return nil, errScopes
    59  	} else if resp.StatusCode > 299 {
    60  		return nil, api.HandleHTTPError(resp)
    61  	}
    62  
    63  	b, err := io.ReadAll(resp.Body)
    64  	if err != nil {
    65  		return nil, err
    66  	}
    67  
    68  	var keys []gpgKey
    69  	err = json.Unmarshal(b, &keys)
    70  	if err != nil {
    71  		return nil, err
    72  	}
    73  
    74  	return keys, nil
    75  }