-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflusher.go
73 lines (62 loc) · 1.89 KB
/
flusher.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package main
import (
"fmt"
"net/http"
"time"
"github.com/pkg/errors"
"github.com/qeesung/asciiplayer/pkg/player"
"github.com/qeesung/asciiplayer/pkg/util"
)
// FlushHandler define the basic oprations that flush image to remote server
type FlushHandler interface {
Init() error
HandlerFunc() func(w http.ResponseWriter, r *http.Request)
}
// supportedFlushHandlerMatchers register the supported flush handler
// and if the Match function is return true, just call the constructor
// function to build the flusher handler.
var supportedFlushHandlerMatchers = []struct {
Match func(string) bool
Constructor func(string, *Options) FlushHandler
}{
{
Match: util.IsGif,
Constructor: NewGifFlushHandler,
},
}
// NewFlushHandler is factory method to create flush handler
func NewFlushHandler(filename string, options *Options) (handler FlushHandler, supported bool) {
for _, matcher := range supportedFlushHandlerMatchers {
if matcher.Match(filename) {
return matcher.Constructor(filename, options), true
}
}
return nil, false
}
// BaseFlushHandler is a basic flush handler that define some basic opration
type BaseFlushHandler struct {
}
// Init doing nothing in base flush handler
func (handler *BaseFlushHandler) Init() error {
return nil
}
// HandlerFunc return a empty hadnler function
func (handler *BaseFlushHandler) HandlerFunc() func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
}
}
// Flush flush the string to remote client immediately
func (handler *BaseFlushHandler) Flush(w http.ResponseWriter, s string) error {
_, err := fmt.Fprintf(w, s)
if err != nil {
return err
}
time.Sleep(time.Duration(100) * time.Millisecond)
fmt.Fprintf(w, player.ClearScreen)
// flush to the remote immediately
if flusher, ok := w.(http.Flusher); ok {
flusher.Flush()
return nil
}
return errors.New("can not flush to invalid writer")
}