pancakeswapnft/profile.go

72 lines
1.4 KiB
Go
Raw Normal View History

2021-12-22 06:38:57 +00:00
package pancakeswapnft
import (
"bytes"
"encoding/json"
"fmt"
"github.com/pkg/errors"
2021-12-22 07:08:44 +00:00
"github.com/rs/zerolog/log"
2021-12-22 06:38:57 +00:00
"io"
"net/http"
"sync"
)
type Profile struct {
2021-12-22 06:49:02 +00:00
Address string `json:"address"`
Username string `json:"username"`
2021-12-22 06:38:57 +00:00
}
func getUsernameFromAddress(address string) (string, error) {
resp, err := http.Get(fmt.Sprintf("https://profile.pancakeswap.com/api/users/%s", address))
if err != nil {
return "", err
}
defer func(Body io.ReadCloser) {
_ = Body.Close()
}(resp.Body)
raw, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
if resp.StatusCode != http.StatusOK {
return "", errors.Errorf("non 200 http status : %d / raw : %s", resp.StatusCode, raw)
}
var profile Profile
err = json.NewDecoder(bytes.NewReader(raw)).Decode(&profile)
if err != nil {
return "", err
}
return profile.Username, nil
}
type ProfileService struct {
cache map[string]string
lock *sync.Mutex
}
func NewProfileService() *ProfileService {
return &ProfileService{
cache: make(map[string]string),
lock: &sync.Mutex{},
}
}
2021-12-22 06:56:26 +00:00
func (s *ProfileService) GetUsername(address string) string {
2021-12-22 06:38:57 +00:00
s.lock.Lock()
defer s.lock.Unlock()
if name, ok := s.cache[address]; ok {
2021-12-22 06:56:26 +00:00
return name
2021-12-22 06:38:57 +00:00
}
2021-12-22 06:56:26 +00:00
if name, err := getUsernameFromAddress(address); err != nil {
s.cache[address] = address
} else {
s.cache[address] = name
2021-12-22 06:38:57 +00:00
}
2021-12-22 07:08:44 +00:00
log.Debug().Msgf("[PROFILE] %s -> %s", address, s.cache[address])
2021-12-22 06:56:26 +00:00
return s.cache[address]
2021-12-22 06:38:57 +00:00
}