Conditions | 6 |
Total Lines | 54 |
Code Lines | 32 |
Lines | 0 |
Ratio | 0 % |
Changes | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
1 | package oauth |
||
16 | func GetGithubAccessToken(code string) (string, error) { |
||
17 | // Set us the request body as JSON |
||
18 | requestBodyMap := map[string]string{ |
||
19 | "client_id": infrastructures.GetAppConfig().GithubConfig.ClientID, |
||
20 | "client_secret": infrastructures.GetAppConfig().GithubConfig.ClientSecret, |
||
21 | "code": code, |
||
22 | } |
||
23 | requestJSON, _ := config.JSONHelper.Marshal(requestBodyMap) |
||
24 | |||
25 | // POST request to set URL |
||
26 | req, reqerr := http.NewRequestWithContext(context.Background(), |
||
27 | http.MethodPost, |
||
28 | "https://github.com/login/oauth/access_token", |
||
29 | bytes.NewBuffer(requestJSON), |
||
30 | ) |
||
31 | if reqerr != nil { |
||
32 | log.Info().Msg("Request failed") |
||
33 | } |
||
34 | req.Header.Set("Content-Type", "application/json") |
||
35 | req.Header.Set("Accept", "application/json") |
||
36 | |||
37 | // Get the response |
||
38 | resp, resperr := http.DefaultClient.Do(req) |
||
39 | if resperr != nil { |
||
40 | log.Info().Msg("Response failed") |
||
41 | } |
||
42 | |||
43 | defer func(Body io.ReadCloser) { |
||
44 | err := Body.Close() |
||
45 | if err != nil { |
||
46 | log.Info().Msg("Body close failed") |
||
47 | } |
||
48 | }(resp.Body) |
||
49 | |||
50 | // Response body converted to stringified JSON |
||
51 | respbody, _ := io.ReadAll(resp.Body) |
||
52 | |||
53 | // Represents the response received from Github |
||
54 | type githubAccessTokenResponse struct { |
||
55 | AccessToken string `json:"access_token"` |
||
56 | TokenType string `json:"token_type"` |
||
57 | Scope string `json:"scope"` |
||
58 | } |
||
59 | |||
60 | // Convert stringified JSON to a struct object of type githubAccessTokenResponse |
||
61 | var ghresp githubAccessTokenResponse |
||
62 | err := config.JSONHelper.Unmarshal(respbody, &ghresp) |
||
63 | if err != nil { |
||
64 | return "", err |
||
65 | } |
||
66 | |||
67 | // Return the access token (as the rest of the |
||
68 | // details are relatively unnecessary for us) |
||
69 | return ghresp.AccessToken, nil |
||
70 | } |
||
110 |