github.com/ungtb10d/cli/v2@v2.0.0-20221110210412-98537dd9d6a1/pkg/cmd/repo/deploy-key/add/http.go (about) 1 package add 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "fmt" 7 "io" 8 "net/http" 9 10 "github.com/ungtb10d/cli/v2/api" 11 "github.com/ungtb10d/cli/v2/internal/ghinstance" 12 "github.com/ungtb10d/cli/v2/internal/ghrepo" 13 ) 14 15 func uploadDeployKey(httpClient *http.Client, repo ghrepo.Interface, keyFile io.Reader, title string, isWritable bool) error { 16 path := fmt.Sprintf("repos/%s/%s/keys", repo.RepoOwner(), repo.RepoName()) 17 url := ghinstance.RESTPrefix(repo.RepoHost()) + path 18 19 keyBytes, err := io.ReadAll(keyFile) 20 if err != nil { 21 return err 22 } 23 24 payload := map[string]interface{}{ 25 "title": title, 26 "key": string(keyBytes), 27 "read_only": !isWritable, 28 } 29 30 payloadBytes, err := json.Marshal(payload) 31 if err != nil { 32 return err 33 } 34 35 req, err := http.NewRequest("POST", url, bytes.NewBuffer(payloadBytes)) 36 if err != nil { 37 return err 38 } 39 40 resp, err := httpClient.Do(req) 41 if err != nil { 42 return err 43 } 44 defer resp.Body.Close() 45 46 if resp.StatusCode > 299 { 47 return api.HandleHTTPError(resp) 48 } 49 50 _, err = io.Copy(io.Discard, resp.Body) 51 if err != nil { 52 return err 53 } 54 55 return nil 56 }