request.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package request
  2. import (
  3. "strings"
  4. "net/http"
  5. "net/url"
  6. "errors"
  7. "io/ioutil"
  8. "encoding/json"
  9. "fmt"
  10. )
  11. var client = &http.Client{}
  12. //var cache = TODO
  13. func Fetch(link *url.URL) (map[string]any, error) {
  14. const requiredContentType = `application/ld+json; profile="https://www.w3.org/ns/activitystreams"`
  15. const optionalContentType = "application/activity+json"
  16. // convert URL to string
  17. url := link.String()
  18. // create the get request
  19. req, err := http.NewRequest("GET", url, nil)
  20. if err != nil {
  21. return map[string]any{}, err
  22. }
  23. // add the accept header
  24. // § 3.2
  25. req.Header.Add("Accept", fmt.Sprintf("%s, %s", requiredContentType, optionalContentType))
  26. // send the request
  27. resp, err := client.Do(req)
  28. if err != nil {
  29. return map[string]any{}, err
  30. }
  31. // check the status code
  32. if resp.StatusCode != 200 {
  33. return nil, errors.New("The server returned a status code of " + string(resp.StatusCode))
  34. }
  35. // check the response content type
  36. if contentType := resp.Header.Get("Content-Type"); contentType == "" {
  37. return nil, errors.New("The server's response did not contain a content type")
  38. } else if !strings.Contains(contentType, requiredContentType) && !strings.Contains(contentType, optionalContentType) {
  39. return nil, errors.New("The server responded with the invalid content type of " + contentType)
  40. }
  41. // read the body into a map
  42. defer resp.Body.Close()
  43. body, err := ioutil.ReadAll(resp.Body)
  44. var object map[string]any
  45. if err := json.Unmarshal(body, &object); err != nil {
  46. return nil, err
  47. }
  48. return object, nil
  49. }