Skip to content
This repository has been archived by the owner on Aug 19, 2022. It is now read-only.

Implement json.Marshaler interface for LimitConfig #67

Merged
merged 1 commit into from
Jul 7, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions limit_config_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package rcmgr

import (
"bytes"
"encoding/json"
"os"
"testing"

Expand Down Expand Up @@ -50,4 +52,11 @@ func TestLimitConfigParser(t *testing.T) {
require.NoError(t, err)
require.Contains(t, cfg.Peer, peerID)
require.Equal(t, int64(4097), cfg.Peer[peerID].Memory)

// Roundtrip
jsonBytes, err := json.Marshal(&cfg)
require.NoError(t, err)
cfgAfterRoundTrip, err := readLimiterConfigFromJSON(bytes.NewReader(jsonBytes), defaults)
require.NoError(t, err)
require.Equal(t, cfg, cfgAfterRoundTrip)
}
18 changes: 18 additions & 0 deletions limit_defaults.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package rcmgr

import (
"encoding/json"
"math"

"github.com/libp2p/go-libp2p-core/peer"
Expand Down Expand Up @@ -136,6 +137,23 @@ type LimitConfig struct {
Stream BaseLimit `json:",omitempty"`
}

func (cfg *LimitConfig) MarshalJSON() ([]byte, error) {
// we want to marshal the encoded peer id
encodedPeerMap := make(map[string]BaseLimit, len(cfg.Peer))
for p, v := range cfg.Peer {
encodedPeerMap[peer.Encode(p)] = v
}

type Alias LimitConfig
return json.Marshal(&struct {
*Alias
Peer map[string]BaseLimit `json:",omitempty"`
}{
Alias: (*Alias)(cfg),
Peer: encodedPeerMap,
})
}

func (cfg *LimitConfig) Apply(c LimitConfig) {
cfg.System.Apply(c.System)
cfg.Transient.Apply(c.Transient)
Expand Down