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