Last active
March 8, 2019 08:18
-
-
Save draveness/eacf0cca88148cc38e2c446f69a51dad to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| package main | |
| import ( | |
| "context" | |
| "errors" | |
| "fmt" | |
| "math/rand" | |
| "time" | |
| ) | |
| // Handler handles stream request with context | |
| type Handler interface { | |
| Get(context.Context, string) (string, error) | |
| } | |
| // NextOrFailure constructs plugins in a chain | |
| func NextOrFailure(ctx context.Context, next Handler, streamID string) (string, error) { | |
| if next != nil { | |
| return next.Get(ctx, streamID) | |
| } | |
| return "", errors.New("Handler chain terminated") | |
| } | |
| // redisHandler | |
| type redisHandler struct { | |
| } | |
| func (s *redisHandler) Get(ctx context.Context, streamID string) (string, error) { | |
| result := rand.Intn(10) | |
| if result < 5 { | |
| return "", errors.New("redis error") | |
| } | |
| return "https://redis.url/" + streamID, nil | |
| } | |
| // cacheHandler | |
| type cacheHandler struct { | |
| Next Handler | |
| } | |
| func (cache *cacheHandler) Get(ctx context.Context, streamID string) (string, error) { | |
| result := rand.Intn(10) | |
| if result < 2 { | |
| return "", errors.New("Unknown Error") | |
| } | |
| if result < 6 { | |
| return NextOrFailure(ctx, cache.Next, streamID) | |
| } | |
| return "https://random.url/" + streamID, nil | |
| } | |
| func init() { | |
| rand.Seed(time.Now().UTC().UnixNano()) | |
| } | |
| func main() { | |
| redis := &redisHandler{} | |
| cache := cacheHandler{ | |
| Next: redis, | |
| } | |
| result, err := cache.Get(context.Background(), "3210830919510") | |
| fmt.Println(result, err) | |
| } |
This file contains hidden or 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
| package main | |
| import ( | |
| "context" | |
| "fmt" | |
| "testing" | |
| ) | |
| func TestCacheHandler(t *testing.T) { | |
| h := cacheHandler{} | |
| result, err := h.Get(context.Background(), "23131") | |
| fmt.Println(result, err) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.