Last active
July 25, 2022 21:11
-
-
Save juanesech/3b984e777f30def986d50f5d690ce69f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package gitlab | |
import ( | |
"io/ioutil" | |
"log" | |
"net/http" | |
) | |
const ( | |
timeout = 30 | |
) | |
// Gitlab holds state relevant to an external API | |
type Gitlab struct { | |
Url string | |
Client *http.Client | |
} | |
func (provider *Gitlab) request(req *http.Request) (response *http.Response, err error) { | |
clonedReq := req.Clone(req.Context()) | |
if req.Body != nil { | |
clonedReq.Body, err = req.GetBody() | |
if err != nil { | |
log.Println(err) | |
return nil, err | |
} | |
} | |
defer func() { | |
if clonedReq.Body != nil { | |
clonedReq.Body.Close() | |
} | |
}() | |
// set headers common to all requests | |
req.Header.Set("Content-Type", "application/json") | |
response, err = provider.Client.Do(req) | |
if err != nil { | |
log.Println("request: ", err) | |
return nil, err | |
} | |
if response.StatusCode == http.StatusUnauthorized { | |
bodyBytes, err := ioutil.ReadAll(response.Body) | |
if err != nil { | |
log.Println(err) | |
} else { | |
log.Println(string(bodyBytes)) | |
} | |
// ask for a new refresh token | |
response.Body.Close() | |
response, err = provider.request(clonedReq) | |
} | |
return response, err | |
} | |
func (provider *Gitlab) Get(path string) { | |
req, err := http.NewRequest(http.MethodGet, provider.Url+path, nil) | |
if err != nil { | |
return | |
} | |
response, err := provider.request(req) | |
if err != nil { | |
log.Println("callExternalAPI: ", err) | |
return | |
} | |
defer response.Body.Close() | |
// do something with the response | |
catFact, err := ioutil.ReadAll(response.Body) | |
if err != nil { | |
log.Println(err) | |
} else { | |
log.Println(string(catFact)) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package gitlab | |
import ( | |
"net/http" | |
"time" | |
) | |
type Project struct { | |
name string `json:"name"` | |
url string `json:"http_url_to_repo"` | |
} | |
func ListProjects() { | |
client := Gitlab{ | |
Url: "https://gitlab.com", | |
Client: &http.Client{ | |
Timeout: time.Duration(30 * time.Second), | |
}, | |
} | |
client.Get("/api/v4/projects") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment