Skip to content

Instantly share code, notes, and snippets.

@draveness
Last active March 8, 2019 08:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save draveness/eacf0cca88148cc38e2c446f69a51dad to your computer and use it in GitHub Desktop.
Save draveness/eacf0cca88148cc38e2c446f69a51dad to your computer and use it in GitHub Desktop.
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)
}
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