package main import ( "github.com/disgoorg/disgo" "github.com/disgoorg/disgo/bot" "github.com/disgoorg/disgo/cache" "github.com/disgoorg/log" "github.com/disgoorg/snowflake/v2" "golang.org/x/exp/slog" "io" "net/http" "os" "strings" ) var ( token = os.Getenv("disgo_token") avatarCache map[snowflake.ID][]byte ) func init() { avatarCache = make(map[snowflake.ID][]byte) } func main() { mux := http.NewServeMux() client, err := disgo.New(token, bot.WithCacheConfigOpts( cache.WithCaches( cache.FlagsAll, ), ), ) if err != nil { slog.Error(err.Error()) return } rest := client.Rest() mux.HandleFunc("/api/v1/discord/avatar/", func(w http.ResponseWriter, r *http.Request) { flake, err := snowflake.Parse(strings.TrimPrefix(r.URL.Path, "/api/v1/discord/avatar/")) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } avatar, ok := avatarCache[flake] if !ok { user, err := rest.GetUser(flake) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } avatarUrl := user.EffectiveAvatarURL() res, err := http.Get(avatarUrl) if err != nil || res.StatusCode != http.StatusOK { http.Error(w, err.Error(), http.StatusInternalServerError) return } // cache entry avatarCache[flake], err = io.ReadAll(res.Body) avatar = avatarCache[flake] if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } } w.WriteHeader(http.StatusOK) w.Header().Add("Content-Type", http.DetectContentType(avatar)) _, _ = w.Write(avatar) return }) log.Fatal(http.ListenAndServe(":8080", mux)) }