-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
hui.wang
committed
Jan 25, 2022
1 parent
307bdf2
commit 5cec675
Showing
2 changed files
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} |