Skip to content

Commit

Permalink
refactor(xconf): add kv reader
Browse files Browse the repository at this point in the history
  • Loading branch information
hui.wang committed Jan 25, 2022
1 parent 307bdf2 commit 5cec675
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
5 changes: 5 additions & 0 deletions kv/loader.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ import (
"sync"
)

// Getter 主动获取指定confPath的数据
type Getter interface {
Get(ctx context.Context, confPath string) ([]byte, error)
}

// Loader kv加载基础接口
// todo Loder实现Reader接口完全对接到io.Reader,将远程的首次加载流程直接对接到xconf的WithReader
type Loader interface {
Expand Down
42 changes: 42 additions & 0 deletions kv/reader.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package kv

import (
"bytes"
"context"
"io"
"time"
)

type reader struct {
Getter
p string
timeout time.Duration
reader io.Reader
}

// NewReader 返回一个kv reader
func NewReader(getter Getter, path string, timeout time.Duration) io.Reader {
return &reader{Getter: getter, p: path, timeout: timeout}
}

func (r *reader) do() error {
ctx, cancel := context.WithTimeout(context.Background(), r.timeout)
defer cancel()
bb, err := r.Getter.Get(ctx, r.p)
if err != nil {
return err
}
r.reader = bytes.NewReader(bb)
return nil
}

// Read 实现io.Reader接口
func (r *reader) Read(p []byte) (n int, err error) {
if r.reader == nil {
err = r.do()
if err != nil {
return 0, err
}
}
return r.reader.Read(p)
}

0 comments on commit 5cec675

Please sign in to comment.