Support authorization token

This commit is contained in:
Gabriel Garrido 2024-05-19 22:57:30 +02:00
parent 7504f5438a
commit 7886ec43f8
3 changed files with 28 additions and 5 deletions

View file

@ -36,7 +36,8 @@ func FetchAccount(baseURL string, handle string) (Account, error) {
handle, handle,
) )
err := Fetch(lookupUrl, &account) headers := make(map[string]string)
err := Fetch(lookupUrl, &account, headers)
if err != nil { if err != nil {
return account, err return account, err

View file

@ -6,8 +6,15 @@ import (
"net/http" "net/http"
) )
func Fetch(requestUrl string, variable interface{}) error { func Fetch(requestUrl string, variable interface{}, headers map[string]string) error {
res, err := http.Get(requestUrl) client := &http.Client{}
req, _ := http.NewRequest("GET", requestUrl, nil)
for key, val := range headers {
req.Header.Set(key, val)
}
res, err := client.Do(req)
if err != nil { if err != nil {
return err return err

View file

@ -3,6 +3,7 @@ package client
import ( import (
"fmt" "fmt"
"net/url" "net/url"
"os"
"strconv" "strconv"
"time" "time"
) )
@ -115,6 +116,7 @@ func (p Post) AllMedia() []MediaAttachment {
func FetchPosts(baseURL string, accountId string, filters PostsFilter) ([]Post, error) { func FetchPosts(baseURL string, accountId string, filters PostsFilter) ([]Post, error) {
var posts []Post var posts []Post
headers := make(map[string]string)
queryValues := url.Values{} queryValues := url.Values{}
@ -160,8 +162,10 @@ func FetchPosts(baseURL string, accountId string, filters PostsFilter) ([]Post,
accountId, accountId,
query, query,
) )
setAuthTokenIfPassed(&headers)
if err := Fetch(postsUrl, &posts); err != nil {
if err := Fetch(postsUrl, &posts, headers); err != nil {
return posts, err return posts, err
} }
@ -170,15 +174,26 @@ func FetchPosts(baseURL string, accountId string, filters PostsFilter) ([]Post,
func FetchStatusContext(baseURL, postId string) (StatusContext, error) { func FetchStatusContext(baseURL, postId string) (StatusContext, error) {
var status StatusContext var status StatusContext
headers := make(map[string]string)
statusUrl := fmt.Sprintf( statusUrl := fmt.Sprintf(
"%s/api/v1/statuses/%s/context", "%s/api/v1/statuses/%s/context",
baseURL, baseURL,
postId, postId,
) )
if err := Fetch(statusUrl, &status); err != nil { setAuthTokenIfPassed(&headers)
if err := Fetch(statusUrl, &status, headers); err != nil {
return status, err return status, err
} }
return status, nil return status, nil
} }
func setAuthTokenIfPassed(headers *map[string]string) {
token, ok := os.LookupEnv("MASTODON_AUTH_TOKEN")
if ok {
(*headers)["Authorization"] = fmt.Sprintf("Bearer %s", token)
}
}