59 lines
1.3 KiB
Go
59 lines
1.3 KiB
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
"encoding/json"
|
||
|
"fmt"
|
||
|
"net/http"
|
||
|
)
|
||
|
|
||
|
type gtsClient struct {
|
||
|
authentication Authentication
|
||
|
httpClient http.Client
|
||
|
userAgent string
|
||
|
}
|
||
|
|
||
|
func newGtsClient(authentication Authentication) *gtsClient {
|
||
|
httpClient := http.Client{}
|
||
|
|
||
|
client := gtsClient{
|
||
|
authentication: authentication,
|
||
|
httpClient: httpClient,
|
||
|
userAgent: userAgent,
|
||
|
}
|
||
|
|
||
|
return &client
|
||
|
}
|
||
|
|
||
|
func (g *gtsClient) sendRequest(request *http.Request, object any) error {
|
||
|
request.Header.Set("Content-Type", "application/json; charset=utf-8")
|
||
|
request.Header.Set("Accept", "application/json; charset=utf-8")
|
||
|
request.Header.Set("User-Agent", g.userAgent)
|
||
|
|
||
|
if len(g.authentication.AccessToken) > 0 {
|
||
|
request.Header.Set("Authorization", fmt.Sprintf("Bearer %s", g.authentication.AccessToken))
|
||
|
}
|
||
|
|
||
|
response, err := g.httpClient.Do(request)
|
||
|
if err != nil {
|
||
|
return fmt.Errorf("received an error after sending the request; %w", err)
|
||
|
}
|
||
|
|
||
|
defer response.Body.Close()
|
||
|
|
||
|
if response.StatusCode < http.StatusOK || response.StatusCode >= http.StatusBadRequest {
|
||
|
return fmt.Errorf(
|
||
|
"did not receive an OK response from the GoToSocial server; got %d",
|
||
|
response.StatusCode,
|
||
|
)
|
||
|
}
|
||
|
|
||
|
if err := json.NewDecoder(response.Body).Decode(object); err != nil {
|
||
|
return fmt.Errorf(
|
||
|
"unable to decode the response from the GoToSocial server; %w",
|
||
|
err,
|
||
|
)
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|