well-goknown/lnurlp/lnurlp.go
2024-02-24 19:29:17 -05:00

63 lines
1.4 KiB
Go

package lnurlp
import (
"context"
b64 "encoding/base64"
"encoding/json"
"fmt"
"net/http"
"strings"
"git.minhas.io/asara/well-goknown/logger"
"git.minhas.io/asara/well-goknown/redis"
)
type ErrorMessage struct {
Error string `json:"error"`
}
type Response struct {
Payload string `json:"request_key"`
}
func GetLnurlpUser(w http.ResponseWriter, r *http.Request) {
ctx := context.TODO()
l := logger.Get()
// connect to redis
redisCli := redis.LnurlpRedisConn.Client
// search for user@domain
search := getRkey("lnurlp", "asara", r.Host)
addr, err := redisCli.Get(ctx, search).Result()
if err != nil {
l.Info().Msg(fmt.Sprintf("get %s: not found", search))
w.WriteHeader(http.StatusNotFound)
json.NewEncoder(w).Encode(&ErrorMessage{
Error: "username not registered",
})
return
}
dec, err := b64.StdEncoding.DecodeString(addr)
if err != nil {
l.Error().Msg(fmt.Sprintf("get %s: unable to decode key", search))
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(&ErrorMessage{
Error: "internal server error",
})
return
}
l.Info().Msg(fmt.Sprintf("get %s: found and returned", search))
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(dec)
}
func getRkey(prefix string, user string, hostname string) string {
if strings.Contains(hostname, ":") {
hostname = strings.Split(hostname, ":")[0]
}
return fmt.Sprintf("%s:%s@%s", prefix, user, hostname)
}