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

     1  package delete
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"io"
     7  	"net/http"
     8  
     9  	"github.com/ungtb10d/cli/v2/api"
    10  	"github.com/ungtb10d/cli/v2/internal/ghinstance"
    11  )
    12  
    13  type gpgKey struct {
    14  	ID    int
    15  	KeyID string `json:"key_id"`
    16  }
    17  
    18  func deleteGPGKey(httpClient *http.Client, host, id string) error {
    19  	url := fmt.Sprintf("%suser/gpg_keys/%s", ghinstance.RESTPrefix(host), id)
    20  	req, err := http.NewRequest("DELETE", url, nil)
    21  	if err != nil {
    22  		return err
    23  	}
    24  
    25  	resp, err := httpClient.Do(req)
    26  	if err != nil {
    27  		return err
    28  	}
    29  	defer resp.Body.Close()
    30  
    31  	if resp.StatusCode > 299 {
    32  		return api.HandleHTTPError(resp)
    33  	}
    34  
    35  	return nil
    36  }
    37  
    38  func getGPGKeys(httpClient *http.Client, host string) ([]gpgKey, error) {
    39  	resource := "user/gpg_keys"
    40  	url := fmt.Sprintf("%s%s?per_page=%d", ghinstance.RESTPrefix(host), resource, 100)
    41  	req, err := http.NewRequest("GET", url, nil)
    42  	if err != nil {
    43  		return nil, err
    44  	}
    45  
    46  	resp, err := httpClient.Do(req)
    47  	if err != nil {
    48  		return nil, err
    49  	}
    50  	defer resp.Body.Close()
    51  
    52  	if resp.StatusCode > 299 {
    53  		return nil, api.HandleHTTPError(resp)
    54  	}
    55  
    56  	b, err := io.ReadAll(resp.Body)
    57  	if err != nil {
    58  		return nil, err
    59  	}
    60  
    61  	var keys []gpgKey
    62  	err = json.Unmarshal(b, &keys)
    63  	if err != nil {
    64  		return nil, err
    65  	}
    66  
    67  	return keys, nil
    68  }