|
| 1 | +package github_provider |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "io/ioutil" |
| 7 | + "log" |
| 8 | + "net/http" |
| 9 | + |
| 10 | + "github.com/aditya43/golang_github_microservice/src/api/clients/restclient" |
| 11 | + "github.com/aditya43/golang_github_microservice/src/api/domain/github" |
| 12 | +) |
| 13 | + |
| 14 | +const ( |
| 15 | + headerAuthorization = "Authorization" |
| 16 | + headerAuthorizationFormat = "token %s" |
| 17 | + |
| 18 | + urlCreateRepo = "https://api.github.com/user/repos" |
| 19 | +) |
| 20 | + |
| 21 | +func getAuthorizationHeader(accessToken string) string { |
| 22 | + return fmt.Sprintf(headerAuthorizationFormat, accessToken) |
| 23 | +} |
| 24 | + |
| 25 | +func CreateRepo(accessToken string, request github.CreateRepoRequest) (*github.CreateRepoResponse, *github.GithubErrorResponse) { |
| 26 | + headers := http.Header{} |
| 27 | + headers.Set(headerAuthorization, getAuthorizationHeader(accessToken)) |
| 28 | + |
| 29 | + response, err := restclient.Post(urlCreateRepo, request, headers) |
| 30 | + if err != nil { |
| 31 | + log.Println(fmt.Sprintf("error when trying to create new repo in github: %s", err.Error())) |
| 32 | + return nil, &github.GithubErrorResponse{StatusCode: http.StatusInternalServerError, Message: err.Error()} |
| 33 | + } |
| 34 | + |
| 35 | + bytes, err := ioutil.ReadAll(response.Body) |
| 36 | + if err != nil { |
| 37 | + return nil, &github.GithubErrorResponse{StatusCode: http.StatusInternalServerError, Message: "invalid response body"} |
| 38 | + } |
| 39 | + defer response.Body.Close() |
| 40 | + |
| 41 | + if response.StatusCode > 299 { |
| 42 | + var errResponse github.GithubErrorResponse |
| 43 | + if err := json.Unmarshal(bytes, &errResponse); err != nil { |
| 44 | + return nil, &github.GithubErrorResponse{StatusCode: http.StatusInternalServerError, Message: "invalid json response body"} |
| 45 | + } |
| 46 | + errResponse.StatusCode = response.StatusCode |
| 47 | + return nil, &errResponse |
| 48 | + } |
| 49 | + |
| 50 | + var result github.CreateRepoResponse |
| 51 | + if err := json.Unmarshal(bytes, &result); err != nil { |
| 52 | + log.Println(fmt.Sprintf("error when trying to unmarshal create repo successful response: %s", err.Error())) |
| 53 | + return nil, &github.GithubErrorResponse{StatusCode: http.StatusInternalServerError, Message: "error when trying to unmarshal github create repo response"} |
| 54 | + } |
| 55 | + return &result, nil |
| 56 | +} |
0 commit comments