well-goknown/nostr/nostr.go

77 lines
1.6 KiB
Go
Raw Normal View History

package nostr
import (
"fmt"
"net/http"
"strings"
"github.com/go-redis/redis"
)
type nostrWellKnown struct {
Names map[string]string `json:"names"`
Relays map[string][]string `json:"relays,omitempty"`
}
type NostrRequest struct {
Name string `json:"name"`
Key string `json:"key"`
Hostname string
Relays []string `json:"relays"`
}
/*
func AddNostrAddr(n NostrRequest) {
// transform request to well known struct
names := map[string]string{n.Name: n.Key}
relays := map[string][]string{n.Key: n.Relays}
user := nostrWellKnown{Names: names, Relays: relays}
jsonUser, _ := json.Marshal(user)
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "",
DB: 0,
})
nameKey := fmt.Sprintf("%s@%s", n.Name, n.Hostname)
err := client.Set(nameKey, jsonUser, 0).Err()
if err != nil {
fmt.Println("FAILED")
}
}
*/
func GetNostrAddr(w http.ResponseWriter, req *http.Request) {
// get query string for username
req.ParseForm()
// connect to redis
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "",
DB: 0,
})
requestedName := req.FormValue("name")
hostname := getHostname(req.Host)
// search for user@domain
search := fmt.Sprintf("%s@%s", requestedName, hostname)
addr, err := client.Get(search).Result()
if err != nil {
w.WriteHeader(http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, addr)
}
func getHostname(hostname string) string {
// remove port for local testing
if strings.Contains(hostname, ":") {
hostname = strings.Split(hostname, ":")[0]
}
return hostname
}