cli/pkg/cmd/repo/deploy-key/add/http.go
Nilesh Singh 47a6aff54a
Add repo deploy key commands (#4302)
Co-authored-by: Mislav Marohnić <mislav@github.com>
2022-01-25 17:48:24 +00:00

57 lines
1.1 KiB
Go

package add
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/ghinstance"
"github.com/cli/cli/v2/internal/ghrepo"
)
func uploadDeployKey(httpClient *http.Client, repo ghrepo.Interface, keyFile io.Reader, title string, isWritable bool) error {
path := fmt.Sprintf("repos/%s/%s/keys", repo.RepoOwner(), repo.RepoName())
url := ghinstance.RESTPrefix(repo.RepoHost()) + path
keyBytes, err := ioutil.ReadAll(keyFile)
if err != nil {
return err
}
payload := map[string]interface{}{
"title": title,
"key": string(keyBytes),
"read_only": !isWritable,
}
payloadBytes, err := json.Marshal(payload)
if err != nil {
return err
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(payloadBytes))
if err != nil {
return err
}
resp, err := httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode > 299 {
return api.HandleHTTPError(resp)
}
_, err = io.Copy(ioutil.Discard, resp.Body)
if err != nil {
return err
}
return nil
}