From 6474565d976da6d980e7a91a133d45bca10e2412 Mon Sep 17 00:00:00 2001 From: Silvan Jegen Date: Sun, 4 Dec 2016 20:29:41 +0100 Subject: Add HTTPInput --- manager.go | 47 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/manager.go b/manager.go index 3122b67..086740e 100644 --- a/manager.go +++ b/manager.go @@ -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{}, } -- cgit v1.2.3