first commit
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
package helpers
|
||||
|
||||
import (
|
||||
"CatsOfMastodonBotGo/models"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func GetPosts(ctx context.Context, tag string, instance string) (error, []models.Post) {
|
||||
var requestUrl = instance + "/api/v1/timelines/tag/" + tag + "?limit=40"
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", requestUrl, nil)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
return err, nil
|
||||
}
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
return err, nil
|
||||
}
|
||||
if resp.StatusCode != 200 || strings.Split(strings.ToLower(resp.Header.Get("Content-Type")), ";")[0] != "application/json" {
|
||||
log.Fatal("Status code:", resp.StatusCode, " Content-Type:", resp.Header.Get("Content-Type"))
|
||||
return err, nil
|
||||
}
|
||||
|
||||
var posts []models.Post = nil
|
||||
err = json.NewDecoder(resp.Body).Decode(&posts)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
return err, nil
|
||||
}
|
||||
// defer: it basically means "do this later when the function returns"
|
||||
defer resp.Body.Close()
|
||||
if posts == nil {
|
||||
return fmt.Errorf("no posts found for tag %s on instance %s", tag, instance), nil
|
||||
}
|
||||
return nil, posts
|
||||
}
|
||||
Reference in New Issue
Block a user