2023-01-31 11:48:48 -05:00
|
|
|
package nip11
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
"time"
|
2024-03-10 18:44:56 -03:00
|
|
|
|
|
|
|
"github.com/nbd-wtf/go-nostr"
|
2023-01-31 11:48:48 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
// Fetch fetches the NIP-11 RelayInformationDocument.
|
|
|
|
func Fetch(ctx context.Context, u string) (info *RelayInformationDocument, err error) {
|
|
|
|
if _, ok := ctx.Deadline(); !ok {
|
|
|
|
// if no timeout is set, force it to 7 seconds
|
|
|
|
var cancel context.CancelFunc
|
|
|
|
ctx, cancel = context.WithTimeout(ctx, 7*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
}
|
|
|
|
|
2024-03-09 19:48:25 +01:00
|
|
|
// normalize URL to start with http://, https:// or without protocol
|
2024-03-10 18:44:56 -03:00
|
|
|
u = "http" + nostr.NormalizeURL(u)[2:]
|
2023-01-31 11:48:48 -05:00
|
|
|
|
2024-03-10 18:44:56 -03:00
|
|
|
// make request
|
2024-01-13 12:46:59 -03:00
|
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
|
2023-01-31 11:48:48 -05:00
|
|
|
|
|
|
|
// add the NIP-11 header
|
|
|
|
req.Header.Add("Accept", "application/nostr+json")
|
|
|
|
|
|
|
|
// send the request
|
|
|
|
resp, err := http.DefaultClient.Do(req)
|
|
|
|
if err != nil {
|
2023-11-20 14:59:12 -03:00
|
|
|
return nil, fmt.Errorf("request failed: %w", err)
|
2023-01-31 11:48:48 -05:00
|
|
|
}
|
2023-08-21 20:17:25 +08:00
|
|
|
defer resp.Body.Close()
|
2023-11-20 14:59:12 -03:00
|
|
|
|
2023-01-31 11:48:48 -05:00
|
|
|
info = &RelayInformationDocument{}
|
2023-11-20 14:59:12 -03:00
|
|
|
if err := json.NewDecoder(resp.Body).Decode(info); err != nil {
|
|
|
|
return nil, fmt.Errorf("invalid json: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return info, nil
|
2023-01-31 11:48:48 -05:00
|
|
|
}
|