github.com/secman-team/gh-api@v1.8.2/pkg/cmd/ssh-key/add/http.go (about) 1 package add 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "errors" 7 "io" 8 "io/ioutil" 9 "net/http" 10 11 "github.com/secman-team/gh-api/api" 12 "github.com/secman-team/gh-api/core/ghinstance" 13 ) 14 15 var scopesError = errors.New("insufficient OAuth scopes") 16 17 func SSHKeyUpload(httpClient *http.Client, hostname string, keyFile io.Reader, title string) error { 18 url := ghinstance.RESTPrefix(hostname) + "user/keys" 19 20 keyBytes, err := ioutil.ReadAll(keyFile) 21 if err != nil { 22 return err 23 } 24 25 payload := map[string]string{ 26 "title": title, 27 "key": string(keyBytes), 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 == 404 { 47 return scopesError 48 } else if resp.StatusCode > 299 { 49 var httpError api.HTTPError 50 err := api.HandleHTTPError(resp) 51 if errors.As(err, &httpError) && isDuplicateError(&httpError) { 52 return nil 53 } 54 return err 55 } 56 57 _, err = io.Copy(ioutil.Discard, resp.Body) 58 if err != nil { 59 return err 60 } 61 62 return nil 63 } 64 65 func isDuplicateError(err *api.HTTPError) bool { 66 return err.StatusCode == 422 && len(err.Errors) == 1 && 67 err.Errors[0].Field == "key" && err.Errors[0].Message == "key is already in use" 68 }