diff --git a/_examples/disgo/bot.go b/_examples/disgo/bot.go index f3347a1..8326996 100644 --- a/_examples/disgo/bot.go +++ b/_examples/disgo/bot.go @@ -2,14 +2,13 @@ package main import ( "context" + "log/slog" "github.com/disgoorg/disgo/bot" "github.com/disgoorg/disgo/discord" "github.com/disgoorg/disgo/events" - "github.com/disgoorg/log" - "github.com/disgoorg/snowflake/v2" - "github.com/disgoorg/disgolink/v3/disgolink" + "github.com/disgoorg/snowflake/v2" ) func newBot() *Bot { @@ -32,11 +31,11 @@ func (b *Bot) onApplicationCommand(event *events.ApplicationCommandInteractionCr handler, ok := b.Handlers[data.CommandName()] if !ok { - log.Info("unknown command: ", data.CommandName()) + slog.Info("unknown command", slog.String("command", data.CommandName())) return } if err := handler(event, data); err != nil { - log.Error("error handling command: ", err) + slog.Error("error handling command", slog.Any("err", err)) } } diff --git a/_examples/disgo/commands.go b/_examples/disgo/commands.go index cfb1c39..a06f738 100644 --- a/_examples/disgo/commands.go +++ b/_examples/disgo/commands.go @@ -1,11 +1,12 @@ package main import ( + "log/slog" + "github.com/disgoorg/disgo/bot" "github.com/disgoorg/disgo/discord" "github.com/disgoorg/disgolink/v3/lavalink" "github.com/disgoorg/json" - "github.com/disgoorg/log" ) var commands = []discord.ApplicationCommandCreate{ @@ -152,6 +153,6 @@ var commands = []discord.ApplicationCommandCreate{ func registerCommands(client bot.Client) { if _, err := client.Rest().SetGuildCommands(client.ApplicationID(), GuildId, commands); err != nil { - log.Warn(err) + slog.Error("error while registering commands", slog.Any("err", err)) } } diff --git a/_examples/disgo/go.mod b/_examples/disgo/go.mod index 0198eea..a9de8b0 100644 --- a/_examples/disgo/go.mod +++ b/_examples/disgo/go.mod @@ -1,19 +1,19 @@ module github.com/disgoorg/disgolink/v3/_examples/disgo -go 1.18 +go 1.21 require ( - github.com/disgoorg/disgo v0.16.7 - github.com/disgoorg/disgolink/v3 v3.0.0-20230717123709-208f1c210164 + github.com/disgoorg/disgo v0.17.0 + github.com/disgoorg/disgolink/v3 v3.0.0-20230810103102-c572e085fba1 github.com/disgoorg/json v1.1.0 github.com/disgoorg/log v1.2.1 github.com/disgoorg/snowflake/v2 v2.0.1 ) require ( - github.com/gorilla/websocket v1.5.0 // indirect + github.com/gorilla/websocket v1.5.1 // indirect github.com/sasha-s/go-csync v0.0.0-20210812194225-61421b77c44b // indirect - golang.org/x/crypto v0.10.0 // indirect - golang.org/x/exp v0.0.0-20230626212559-97b1e661b5df // indirect - golang.org/x/sys v0.10.0 // indirect + golang.org/x/crypto v0.15.0 // indirect + golang.org/x/net v0.18.0 // indirect + golang.org/x/sys v0.14.0 // indirect ) diff --git a/_examples/disgo/go.sum b/_examples/disgo/go.sum index 3732b1e..6ff5d22 100644 --- a/_examples/disgo/go.sum +++ b/_examples/disgo/go.sum @@ -1,24 +1,28 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/disgoorg/disgo v0.16.7 h1:Y4cI+DpLXCMbHJcjIFs5dspKfn4Ous4lN/et2vKgcb8= -github.com/disgoorg/disgo v0.16.7/go.mod h1:wo61ZLPn6bxHVdUODjyZ3fZTnCT7giD3uknsDUwMGn8= -github.com/disgoorg/disgolink/v3 v3.0.0-20230717123709-208f1c210164 h1:9d8fAFJcpmMYz6Cp9szVKbbiWtSikBJ+1QNB1j1ZvAk= -github.com/disgoorg/disgolink/v3 v3.0.0-20230717123709-208f1c210164/go.mod h1:iaNDNaZTwgceZ9yFD/qwYN7eBl++riQte2VFascmPTY= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/disgoorg/disgo v0.17.0 h1:/LcgXgPDhzHt3GkQ4cpjmIJBim1/VYfS31VhGYif3Ms= +github.com/disgoorg/disgo v0.17.0/go.mod h1:AE2J/8oLR2PtYfqcARsk1mgBxQ5z3Z1OD6Lc2SA0gak= +github.com/disgoorg/disgolink/v3 v3.0.0-20230810103102-c572e085fba1 h1:vjQ80/lj2dAiRxE4Y+F1xOmDKs6Xgdt6Ua73IxTykxY= +github.com/disgoorg/disgolink/v3 v3.0.0-20230810103102-c572e085fba1/go.mod h1:iaNDNaZTwgceZ9yFD/qwYN7eBl++riQte2VFascmPTY= github.com/disgoorg/json v1.1.0 h1:7xigHvomlVA9PQw9bMGO02PHGJJPqvX5AnwlYg/Tnys= github.com/disgoorg/json v1.1.0/go.mod h1:BHDwdde0rpQFDVsRLKhma6Y7fTbQKub/zdGO5O9NqqA= github.com/disgoorg/log v1.2.1 h1:kZYAWkUBcGy4LbZcgYtgYu49xNVLy+xG5Uq3yz5VVQs= github.com/disgoorg/log v1.2.1/go.mod h1:hhQWYTFTnIGzAuFPZyXJEi11IBm9wq+/TVZt/FEwX0o= github.com/disgoorg/snowflake/v2 v2.0.1 h1:CuUxGLwggUxEswZOmZ+mZ5i0xSumQdXW9tXW7uGqe+0= github.com/disgoorg/snowflake/v2 v2.0.1/go.mod h1:SPU9c2CNn5DSyb86QcKtdZgix9osEtKrHLW4rMhfLCs= -github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= -github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/gorilla/websocket v1.5.1 h1:gmztn0JnHVt9JZquRuzLw3g4wouNVzKL15iLr/zn/QY= +github.com/gorilla/websocket v1.5.1/go.mod h1:x3kM2JMyaluk02fnUJpQuwD2dCS5NDG2ZHL0uE0tcaY= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/sasha-s/go-csync v0.0.0-20210812194225-61421b77c44b h1:qYTY2tN72LhgDj2rtWG+LI6TXFl2ygFQQ4YezfVaGQE= github.com/sasha-s/go-csync v0.0.0-20210812194225-61421b77c44b/go.mod h1:/pA7k3zsXKdjjAiUhB5CjuKib9KJGCaLvZwtxGC8U0s= -github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= -golang.org/x/crypto v0.10.0 h1:LKqV2xt9+kDzSTfOhx4FrkEBcMrAgHSYgzywV9zcGmM= -golang.org/x/crypto v0.10.0/go.mod h1:o4eNf7Ede1fv+hwOwZsTHl9EsPFO6q6ZvYR8vYfY45I= -golang.org/x/exp v0.0.0-20230626212559-97b1e661b5df h1:UA2aFVmmsIlefxMk29Dp2juaUSth8Pyn3Tq5Y5mJGME= -golang.org/x/exp v0.0.0-20230626212559-97b1e661b5df/go.mod h1:FXUEEKJgO7OQYeo8N01OfiKP8RXMtf6e8aTskBGqWdc= -golang.org/x/sys v0.10.0 h1:SqMFp9UcQJZa+pmYuAKjd9xq1f0j5rLcDIk0mj4qAsA= -golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +golang.org/x/crypto v0.15.0 h1:frVn1TEaCEaZcn3Tmd7Y2b5KKPaZ+I32Q2OA3kYp5TA= +golang.org/x/crypto v0.15.0/go.mod h1:4ChreQoLWfG3xLDer1WdlH5NdlQ3+mwnQq1YTKY+72g= +golang.org/x/net v0.18.0 h1:mIYleuAkSbHh0tCv7RvjL3F6ZVbLjq4+R7zbOn3Kokg= +golang.org/x/net v0.18.0/go.mod h1:/czyP5RqHAH4odGYxBJ1qz0+CE5WZ+2j1YgoEo8F2jQ= +golang.org/x/sys v0.14.0 h1:Vz7Qs629MkJkGyHxUlRHizWJRG2j8fbQKjELVSNhy7Q= +golang.org/x/sys v0.14.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/_examples/disgo/main.go b/_examples/disgo/main.go index 54dc42e..cae7cb5 100644 --- a/_examples/disgo/main.go +++ b/_examples/disgo/main.go @@ -2,6 +2,7 @@ package main import ( "context" + "log/slog" "os" "os/signal" "regexp" @@ -16,7 +17,6 @@ import ( "github.com/disgoorg/disgo/events" "github.com/disgoorg/disgo/gateway" "github.com/disgoorg/disgolink/v3/disgolink" - "github.com/disgoorg/log" "github.com/disgoorg/snowflake/v2" ) @@ -34,11 +34,9 @@ var ( ) func main() { - log.SetFlags(log.LstdFlags | log.Lshortfile) - log.SetLevel(log.LevelInfo) - log.Info("starting disgo example...") - log.Info("disgo version: ", disgo.Version) - log.Info("disgolink version: ", disgolink.Version) + slog.Info("starting disgo example...") + slog.Info("disgo version", slog.String("version", disgo.Version)) + slog.Info("disgolink version: ", slog.String("version", disgolink.Version)) b := newBot() @@ -54,7 +52,8 @@ func main() { bot.WithEventListenerFunc(b.onVoiceServerUpdate), ) if err != nil { - log.Fatal(err) + slog.Error("error while building disgo client", slog.Any("err", err)) + os.Exit(1) } b.Client = client @@ -89,7 +88,8 @@ func main() { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() if err = client.OpenGateway(ctx); err != nil { - log.Fatal(err) + slog.Error("failed to open gateway", slog.Any("err", err)) + os.Exit(1) } defer client.Close(context.TODO()) @@ -100,16 +100,16 @@ func main() { Secure: NodeSecure, }) if err != nil { - log.Fatal(err) + slog.Error("failed to add node", slog.Any("err", err)) + os.Exit(1) } version, err := node.Version(ctx) if err != nil { - log.Fatal(err) + slog.Error("failed to get node version", slog.Any("err", err)) + os.Exit(1) } - log.Infof("node version: %s", version) - log.Infof("node session id: %s", node.SessionID()) - log.Info("DisGo example is now running. Press CTRL-C to exit.") + slog.Info("DisGo example is now running. Press CTRL-C to exit.", slog.String("node_version", version), slog.String("node_session_id", node.SessionID())) s := make(chan os.Signal, 1) signal.Notify(s, syscall.SIGINT, syscall.SIGTERM, os.Interrupt) <-s diff --git a/_examples/disgo/player_handlers.go b/_examples/disgo/player_handlers.go index 91dc5a0..2009e09 100644 --- a/_examples/disgo/player_handlers.go +++ b/_examples/disgo/player_handlers.go @@ -2,24 +2,22 @@ package main import ( "context" - "fmt" - - "github.com/disgoorg/log" + "log/slog" "github.com/disgoorg/disgolink/v3/disgolink" "github.com/disgoorg/disgolink/v3/lavalink" ) func (b *Bot) onPlayerPause(player disgolink.Player, event lavalink.PlayerPauseEvent) { - fmt.Printf("onPlayerPause: %v\n", event) + slog.Info("player paused", slog.Any("event", event)) } func (b *Bot) onPlayerResume(player disgolink.Player, event lavalink.PlayerResumeEvent) { - fmt.Printf("onPlayerResume: %v\n", event) + slog.Info("player resumed", slog.Any("event", event)) } func (b *Bot) onTrackStart(player disgolink.Player, event lavalink.TrackStartEvent) { - fmt.Printf("onTrackStart: %v\n", event) + slog.Info("track started", slog.Any("event", event)) } func (b *Bot) onTrackEnd(player disgolink.Player, event lavalink.TrackEndEvent) { @@ -48,22 +46,22 @@ func (b *Bot) onTrackEnd(player disgolink.Player, event lavalink.TrackEndEvent) return } if err := player.Update(context.TODO(), lavalink.WithTrack(nextTrack)); err != nil { - log.Error("Failed to play next track: ", err) + slog.Error("Failed to play next track", slog.Any("err", err)) } } func (b *Bot) onTrackException(player disgolink.Player, event lavalink.TrackExceptionEvent) { - fmt.Printf("onTrackException: %v\n", event) + slog.Info("track exception", slog.Any("event", event)) } func (b *Bot) onTrackStuck(player disgolink.Player, event lavalink.TrackStuckEvent) { - fmt.Printf("onTrackStuck: %v\n", event) + slog.Info("track stuck", slog.Any("event", event)) } func (b *Bot) onWebSocketClosed(player disgolink.Player, event lavalink.WebSocketClosedEvent) { - fmt.Printf("onWebSocketClosed: %v\n", event) + slog.Info("websocket closed", slog.Any("event", event)) } func (b *Bot) onUnknownEvent(p disgolink.Player, e lavalink.UnknownEvent) { - fmt.Printf("onUnknownEvent event: %s, data: %s\n", e.Type_, string(e.Data)) + slog.Info("unknown event", slog.Any("event", e.Type()), slog.String("data", string(e.Data))) } diff --git a/disgolink/client.go b/disgolink/client.go index 440eb11..81d4ae0 100644 --- a/disgolink/client.go +++ b/disgolink/client.go @@ -2,19 +2,16 @@ package disgolink import ( "context" + "log/slog" "net/http" "runtime/debug" "sync" - "time" "github.com/disgoorg/disgolink/v3/lavalink" - "github.com/disgoorg/log" "github.com/disgoorg/snowflake/v2" ) type Client interface { - Logger() log.Logger - AddNode(ctx context.Context, config NodeConfig) (Node, error) ForNodes(nodeFunc func(node Node)) Node(name string) Node @@ -43,30 +40,25 @@ type Client interface { } func New(userID snowflake.ID, opts ...ConfigOpt) Client { - config := DefaultConfig() - config.Apply(opts) + cfg := DefaultConfig() + cfg.Apply(opts) + cfg.Logger = cfg.Logger.With(slog.String("name", "disgolink_client")) - if config.Logger == nil { - config.Logger = log.Default() - } - if config.HTTPClient == nil { - config.HTTPClient = &http.Client{Timeout: 20 * time.Second} - } return &clientImpl{ - logger: config.Logger, - httpClient: config.HTTPClient, + logger: cfg.Logger, + httpClient: cfg.HTTPClient, userID: userID, nodes: map[string]Node{}, players: map[snowflake.ID]Player{}, - listeners: config.Listeners, - plugins: config.Plugins, + listeners: cfg.Listeners, + plugins: cfg.Plugins, } } var _ Client = (*clientImpl)(nil) type clientImpl struct { - logger log.Logger + logger *slog.Logger httpClient *http.Client userID snowflake.ID @@ -83,17 +75,18 @@ type clientImpl struct { plugins []Plugin } -func (c *clientImpl) Logger() log.Logger { - return c.logger -} - func (c *clientImpl) AddNode(ctx context.Context, config NodeConfig) (Node, error) { node := &nodeImpl{ + logger: c.logger.With(slog.String("name", "disgolink_node"), slog.String("node_name", config.Name)), config: config, lavalink: c, status: StatusDisconnected, } - node.rest = newRestClientImpl(node, c.httpClient) + node.rest = &restClientImpl{ + logger: c.logger.With(slog.String("name", "disgolink_rest_client"), slog.String("node_name", config.Name)), + node: node, + httpClient: c.httpClient, + } if err := node.Open(ctx); err != nil { return nil, err } @@ -186,7 +179,7 @@ func (c *clientImpl) EmitEvent(player Player, event lavalink.Message) { defer func() { if r := recover(); r != nil { - c.Logger().Errorf("recovered from panic in event listener: %#v\nstack: %s", r, string(debug.Stack())) + c.logger.Error("recovered from panic in event listener", slog.Any("r", r), slog.String("stack", string(debug.Stack()))) return } }() diff --git a/disgolink/client_config.go b/disgolink/client_config.go index a7e9ba0..5fec8f3 100644 --- a/disgolink/client_config.go +++ b/disgolink/client_config.go @@ -1,22 +1,22 @@ package disgolink import ( + "log/slog" "net/http" "time" "github.com/disgoorg/disgolink/v3/lavalink" - "github.com/disgoorg/log" ) func DefaultConfig() *Config { return &Config{ - Logger: log.Default(), + Logger: slog.Default(), HTTPClient: &http.Client{Timeout: 10 * time.Second}, } } type Config struct { - Logger log.Logger + Logger *slog.Logger HTTPClient *http.Client Listeners []EventListener Plugins []Plugin @@ -31,7 +31,7 @@ func (c *Config) Apply(opts []ConfigOpt) { } // WithLogger lets you inject your own logger implementing log.Logger -func WithLogger(logger log.Logger) ConfigOpt { +func WithLogger(logger *slog.Logger) ConfigOpt { return func(config *Config) { config.Logger = logger } diff --git a/disgolink/node.go b/disgolink/node.go index 28225e9..9bec6f2 100644 --- a/disgolink/node.go +++ b/disgolink/node.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "log/slog" "net" "net/http" "sync" @@ -76,6 +77,7 @@ func (c NodeConfig) WsURL() string { } type nodeImpl struct { + logger *slog.Logger lavalink Client config NodeConfig rest RestClient @@ -187,7 +189,7 @@ func (n *nodeImpl) Open(ctx context.Context) error { } func (n *nodeImpl) open(ctx context.Context, reconnecting bool) error { - n.lavalink.Logger().Debug("opening connection to node...") + n.logger.Debug("opening connection to node...") n.connMu.Lock() defer n.connMu.Unlock() @@ -232,12 +234,12 @@ func (n *nodeImpl) open(ctx context.Context, reconnecting bool) error { n.sessionID = ready.SessionID if n.config.SessionID != "" { if ready.Resumed { - n.lavalink.Logger().Info("successfully resumed session: ", n.config.SessionID) + n.logger.InfoContext(ctx, "successfully resumed session", slog.String("session_id", n.config.SessionID)) if err = n.syncPlayers(ctx); err != nil { - n.lavalink.Logger().Warn("failed to sync players: ", err) + n.logger.Warn("failed to sync players: ", err) } } else { - n.lavalink.Logger().Warn("failed to resume session: ", n.config.SessionID) + n.logger.Warn("failed to resume session", slog.String("session_id", n.config.SessionID)) } } n.status = StatusConnected @@ -289,10 +291,10 @@ func (n *nodeImpl) reconnectTry(ctx context.Context, try int, reconnecting bool) } if err := n.open(ctx, reconnecting); err != nil { - if err == ErrNodeAlreadyConnected { + if errors.Is(err, ErrNodeAlreadyConnected) { return err } - n.lavalink.Logger().Error("failed to reconnect node. error: ", err) + n.logger.ErrorContext(ctx, "failed to reconnect node", slog.Any("err", err), slog.Int("try", try)) n.status = StatusDisconnected return n.reconnectTry(ctx, try+1, reconnecting) } @@ -301,12 +303,12 @@ func (n *nodeImpl) reconnectTry(ctx context.Context, try int, reconnecting bool) func (n *nodeImpl) reconnect() { if err := n.reconnectTry(context.Background(), 0, true); err != nil { - n.lavalink.Logger().Error("failed to reopen node. error: ", err) + n.logger.Error("failed to reopen node", slog.Any("err", err)) } } func (n *nodeImpl) listen(conn *websocket.Conn) { - defer n.lavalink.Logger().Debug("exiting listen goroutine...") + defer n.logger.Debug("exiting listen goroutine") loop: for { _, data, err := conn.ReadMessage() @@ -331,7 +333,7 @@ loop: break loop } - n.lavalink.Logger().Trace("received message: ", string(data)) + n.logger.Debug("received message", slog.String("data", string(data))) n.Lavalink().ForPlugins(func(plugin Plugin) { if pl, ok := plugin.(PluginEventHandler); ok { @@ -341,7 +343,7 @@ loop: m, err := lavalink.UnmarshalMessage(data) if err != nil { - n.lavalink.Logger().Errorf("error while unmarshalling ws data: %s", err) + n.logger.Error("error while unmarshalling ws data", slog.Any("err", err)) return } diff --git a/disgolink/player.go b/disgolink/player.go index 5348c4c..9d34dc4 100644 --- a/disgolink/player.go +++ b/disgolink/player.go @@ -3,6 +3,7 @@ package disgolink import ( "context" "errors" + "log/slog" "time" "github.com/disgoorg/disgolink/v3/lavalink" @@ -44,6 +45,10 @@ func NewPlayer(lavalink Client, node Node, guildID snowflake.ID) Player { } type playerImpl struct { + logger *slog.Logger + node Node + lavalink Client + guildID snowflake.ID channelID *snowflake.ID track *lavalink.Track @@ -52,9 +57,6 @@ type playerImpl struct { state lavalink.PlayerState voice lavalink.VoiceState filters lavalink.Filters - - node Node - lavalink Client } func (p *playerImpl) GuildID() snowflake.ID { @@ -246,7 +248,7 @@ func (p *playerImpl) OnVoiceServerUpdate(ctx context.Context, token string, endp SessionID: p.voice.SessionID, }, }); err != nil { - p.lavalink.Logger().Error("error while sending voice server update: ", err) + p.logger.ErrorContext(ctx, "error while sending voice server update", slog.Any("err", err)) } p.voice.Token = token p.voice.Endpoint = endpoint @@ -256,7 +258,7 @@ func (p *playerImpl) OnVoiceStateUpdate(ctx context.Context, channelID *snowflak if channelID == nil { p.channelID = nil if err := p.Destroy(ctx); err != nil { - p.lavalink.Logger().Error("error while destroying player: ", err) + p.logger.ErrorContext(ctx, "error while destroying player", slog.Any("err", err)) } p.lavalink.RemovePlayer(p.guildID) return diff --git a/disgolink/rest_client.go b/disgolink/rest_client.go index 0600844..dd0f5c9 100644 --- a/disgolink/rest_client.go +++ b/disgolink/rest_client.go @@ -6,6 +6,7 @@ import ( "encoding/json" "fmt" "io" + "log/slog" "net/http" "net/url" @@ -58,11 +59,8 @@ type RestClient interface { DecodeTracks(ctx context.Context, encodedTracks []string) ([]lavalink.Track, error) } -func newRestClientImpl(node Node, httpClient *http.Client) RestClient { - return &restClientImpl{node: node, httpClient: httpClient} -} - type restClientImpl struct { + logger *slog.Logger node Node httpClient *http.Client } @@ -136,16 +134,18 @@ func (c *restClientImpl) Do(rq *http.Request) (*http.Response, error) { return c.httpClient.Do(rq) } -func (c *restClientImpl) do(ctx context.Context, method string, path string, rqBody io.Reader) (int, []byte, error) { - rq, err := http.NewRequestWithContext(ctx, method, c.node.Config().RestURL()+path, rqBody) +func (c *restClientImpl) do(ctx context.Context, method string, path string, rqBody []byte) (int, []byte, error) { + rq, err := http.NewRequestWithContext(ctx, method, c.node.Config().RestURL()+path, bytes.NewReader(rqBody)) if err != nil { return 0, nil, err } rq.Header.Set("Authorization", c.node.Config().Password) - if rqBody != nil { + if len(rqBody) > 0 { rq.Header.Set("Content-Type", "application/json") } + c.logger.DebugContext(ctx, "sending request", slog.String("method", method), slog.String("path", path), slog.String("body", fmt.Sprintf("%v", rqBody))) + rs, err := c.httpClient.Do(rq) if err != nil { return 0, nil, err @@ -153,7 +153,7 @@ func (c *restClientImpl) do(ctx context.Context, method string, path string, rqB defer rs.Body.Close() rawBody, err := io.ReadAll(rs.Body) - c.node.Lavalink().Logger().Tracef("response from %s, code %d, body: %s", c.node.Config().RestURL()+path, rs.StatusCode, string(rawBody)) + c.logger.DebugContext(ctx, "received response", slog.String("path", path), slog.Int("status_code", rs.StatusCode), slog.String("body", string(rawBody))) if err != nil { return rs.StatusCode, nil, fmt.Errorf("failed to read response body: %w", err) } @@ -170,16 +170,15 @@ func (c *restClientImpl) do(ctx context.Context, method string, path string, rqB } func (c *restClientImpl) doJSON(ctx context.Context, method string, path string, rqBody any, rsBody any) error { - var rqBodyReader io.Reader + var rawRqBody []byte if rqBody != nil { var err error - rawRqBody, err := json.Marshal(rqBody) + rawRqBody, err = json.Marshal(rqBody) if err != nil { return fmt.Errorf("failed to marshal request body: %w", err) } - rqBodyReader = bytes.NewReader(rawRqBody) } - statusCode, rawBody, err := c.do(ctx, method, path, rqBodyReader) + statusCode, rawBody, err := c.do(ctx, method, path, rawRqBody) if err != nil { return err } diff --git a/go.mod b/go.mod index 9167079..4e6f034 100644 --- a/go.mod +++ b/go.mod @@ -1,17 +1,17 @@ module github.com/disgoorg/disgolink/v3 -go 1.18 +go 1.21 require ( github.com/disgoorg/json v1.1.0 - github.com/disgoorg/log v1.2.1 github.com/disgoorg/snowflake/v2 v2.0.1 - github.com/gorilla/websocket v1.5.0 - github.com/stretchr/testify v1.8.1 + github.com/gorilla/websocket v1.5.1 + github.com/stretchr/testify v1.8.4 ) require ( github.com/davecgh/go-spew v1.1.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.18.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index 0a11c1b..7e21bad 100644 --- a/go.sum +++ b/go.sum @@ -1,25 +1,18 @@ -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/disgoorg/json v1.1.0 h1:7xigHvomlVA9PQw9bMGO02PHGJJPqvX5AnwlYg/Tnys= github.com/disgoorg/json v1.1.0/go.mod h1:BHDwdde0rpQFDVsRLKhma6Y7fTbQKub/zdGO5O9NqqA= -github.com/disgoorg/log v1.2.1 h1:kZYAWkUBcGy4LbZcgYtgYu49xNVLy+xG5Uq3yz5VVQs= -github.com/disgoorg/log v1.2.1/go.mod h1:hhQWYTFTnIGzAuFPZyXJEi11IBm9wq+/TVZt/FEwX0o= github.com/disgoorg/snowflake/v2 v2.0.1 h1:CuUxGLwggUxEswZOmZ+mZ5i0xSumQdXW9tXW7uGqe+0= github.com/disgoorg/snowflake/v2 v2.0.1/go.mod h1:SPU9c2CNn5DSyb86QcKtdZgix9osEtKrHLW4rMhfLCs= -github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= -github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/gorilla/websocket v1.5.1 h1:gmztn0JnHVt9JZquRuzLw3g4wouNVzKL15iLr/zn/QY= +github.com/gorilla/websocket v1.5.1/go.mod h1:x3kM2JMyaluk02fnUJpQuwD2dCS5NDG2ZHL0uE0tcaY= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= -github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= -github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= -github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +golang.org/x/net v0.18.0 h1:mIYleuAkSbHh0tCv7RvjL3F6ZVbLjq4+R7zbOn3Kokg= +golang.org/x/net v0.18.0/go.mod h1:/czyP5RqHAH4odGYxBJ1qz0+CE5WZ+2j1YgoEo8F2jQ= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=