relay/vendor/git.ptzo.gdn/feditools/go-lib/host_meta.go
Tyr Mactire 73e3f41856
use go-lib in git.ptzo.gdn (#163)
Reviewed-on: https://git.ptzo.gdn/feditools/relay/pulls/163
Co-authored-by: Tyr Mactire <tyr@pettingzoo.co>
Co-committed-by: Tyr Mactire <tyr@pettingzoo.co>
2022-11-27 00:23:47 +00:00

59 lines
1.3 KiB
Go

package lib
import (
"context"
"encoding/xml"
"net/http"
"net/url"
ihttp "git.ptzo.gdn/feditools/go-lib/http"
)
// HostMetaWebFingerTemplateRel matches a webfinger link relationship.
const HostMetaWebFingerTemplateRel = "lrdd"
type HostMeta struct {
XMLNS string `xml:"xmlns,attr"`
Links []Link `xml:"Link"`
}
func (h *HostMeta) WebFingerURI() WebFingerURI {
for _, link := range h.Links {
if link.Rel == HostMetaWebFingerTemplateRel {
return WebFingerURI(link.Template)
}
}
return ""
}
func FetchHostMeta(ctx context.Context, t *http.Client, domain string, config ...bool) (*HostMeta, error) {
hostMetaURI := &url.URL{
Scheme: "https",
Host: domain,
Path: "/.well-known/host-meta",
}
if len(config) > 0 && !config[0] {
hostMetaURI.Scheme = "http"
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, hostMetaURI.String(), nil)
if err != nil {
return nil, NewErrorf("req: %s", err.Error())
}
req.Header.Add("Accept", ihttp.MimeAppXML.String())
// do request
resp, err := t.Do(req)
if err != nil {
return nil, NewErrorf("get: %s", err.Error())
}
hostMeta := new(HostMeta)
if err := xml.NewDecoder(resp.Body).Decode(&hostMeta); err != nil {
return nil, NewErrorf("decode: %s", err.Error())
}
return hostMeta, nil
}