diff options
author | Silvan Jegen <s.jegen@gmail.com> | 2016-12-04 20:29:41 +0100 |
---|---|---|
committer | Silvan Jegen <s.jegen@gmail.com> | 2016-12-04 20:29:41 +0100 |
commit | 6474565d976da6d980e7a91a133d45bca10e2412 (patch) | |
tree | 41c98c3463e1d5816e8c6b158b8a85193ed99df6 | |
parent | d32f32aee9c2b5dad954c09c1c9bab0d11f12600 (diff) |
Add HTTPInput
-rw-r--r-- | manager.go | 47 |
1 files changed, 46 insertions, 1 deletions
@@ -6,6 +6,7 @@ import ( "encoding/json" "fmt" "io" + "net/http" "os" "strings" "sync" @@ -25,6 +26,12 @@ type StdinInput struct { retchan chan *Work } +type HTTPInput struct { + retchan chan *Work + prefix string + port string +} + type Filter interface { Filter(*Work) *Work } @@ -71,10 +78,48 @@ func (i *StdinInput) Start() chan *Work { return i.retchan } +func (hi *HTTPInput) httphandler(w http.ResponseWriter, r *http.Request) { + if r.Method != "POST" { + fmt.Printf("Expected POST method was: %q\n", r.Method) + return + } + err := r.ParseForm() + if err != nil { + fmt.Printf("Error when parsing HTTP request form values: %q\n", err) + return + } + workdata := r.PostForm["work"] + fmt.Printf("Form %#v\n", r.Form) + if workdata == nil { + fmt.Printf("Work form field was empty.\n") + return + } + + fmt.Printf("Work form field was: %q\n", workdata) + hi.retchan <- &Work{data: []byte(workdata[0])} +} + +func (hi *HTTPInput) Start() chan *Work { + hi.retchan = make(chan *Work, 100) + + go func() { + http.HandleFunc("/"+hi.prefix, hi.httphandler) + err := http.ListenAndServe(hi.port, nil) + fmt.Printf("Error when serving HTTP: %q\n", err) + close(hi.retchan) + }() + + return hi.retchan +} + func NewStringFilter(ffmap map[string]func(string) string) *StringFilter { return &StringFilter{FilterFuncMap: ffmap} } +func NewHTTPInput(prefix, port string) *HTTPInput { + return &HTTPInput{prefix: prefix, port: port} +} + func (f *StringFilter) Filter(w *Work) *Work { dec := json.NewDecoder(bytes.NewReader(w.data)) jm := make(map[string]string, 10) @@ -144,7 +189,7 @@ func main() { ffmap["F"] = func(s string) string { return strings.ToUpper(s) } m := Manager{ - Input: &StdinInput{}, + Input: NewHTTPInput("", ":8080"), Filter: NewStringFilter(ffmap), Output: &StdoutOutput{}, } |