123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- package request
- import (
- "strings"
- "net/http"
- "net/url"
- "errors"
- "io/ioutil"
- "encoding/json"
- "fmt"
- )
- var client = &http.Client{}
- func Fetch(link *url.URL) (map[string]any, error) {
- const requiredContentType = `application/ld+json; profile="https://www.w3.org/ns/activitystreams"`
- const optionalContentType = "application/activity+json"
-
- url := link.String()
-
- req, err := http.NewRequest("GET", url, nil)
- if err != nil {
- return map[string]any{}, err
- }
-
-
- req.Header.Add("Accept", fmt.Sprintf("%s, %s", requiredContentType, optionalContentType))
-
- resp, err := client.Do(req)
- if err != nil {
- return map[string]any{}, err
- }
-
- if resp.StatusCode != 200 {
- return nil, errors.New("The server returned a status code of " + string(resp.StatusCode))
- }
-
- if contentType := resp.Header.Get("Content-Type"); contentType == "" {
- return nil, errors.New("The server's response did not contain a content type")
- } else if !strings.Contains(contentType, requiredContentType) && !strings.Contains(contentType, optionalContentType) {
- return nil, errors.New("The server responded with the invalid content type of " + contentType)
- }
-
- defer resp.Body.Close()
- body, err := ioutil.ReadAll(resp.Body)
- var object map[string]any
- if err := json.Unmarshal(body, &object); err != nil {
- return nil, err
- }
- return object, nil
- }
|