tavern/fed/activity.go

54 lines
1.2 KiB
Go

package fed
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"go.uber.org/zap"
"github.com/ngerakines/tavern/g"
"github.com/ngerakines/tavern/storage"
)
type ActivityClient struct {
HTTPClient HTTPClient
Logger *zap.Logger
}
func (client ActivityClient) Get(location string) (string, storage.Payload, error) {
client.Logger.Debug("Sending activity request", zap.String("url", location))
return ldJsonGet(client.HTTPClient, location)
}
func ldJsonGet(client HTTPClient, location string) (string, storage.Payload, error) {
request, err := http.NewRequest("GET", location, nil)
if err != nil {
return "", nil, err
}
request.Header.Add("Accept", "application/ld+json")
request.Header.Set("User-Agent", g.UserAgent())
resp, err := client.Do(request)
if err != nil {
return "", nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
body, err := ioutil.ReadAll(io.LimitReader(resp.Body, 1*1024*1024))
if err != nil {
return "", nil, err
}
p, err := storage.PayloadFromBytes(body)
if err != nil {
return "", nil, err
}
return string(body), p, nil
}