summaryrefslogtreecommitdiff
path: root/input/http/http.go
blob: 87ec0f9a0ac0cfd7b7a42546ec7a5c2184957805 (plain)
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
package http

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"strings"

	"github.com/Shugyousha/stasher/input"
	"github.com/Shugyousha/stasher/registry"
	"github.com/Shugyousha/stasher/work"
)

func init() {
	registry.Inputregistry["http"] = New
}

type HTTPInput struct {
	retchan chan *work.Work
	prefix  string
	port    string
}

func New(conf map[string]string) input.Input {
	prefix := conf["prefix"]
	if prefix == "" {
		fmt.Fprintf(os.Stderr, "Need a prefix when setting up http input. Exiting.\n")
		os.Exit(1)
	}
	prefix = strings.Replace(prefix, "\"", "", -1)

	port := conf["port"]
	if port == "" {
		fmt.Fprintf(os.Stderr, "Need a port number when setting up http input. Exiting.\n")
		os.Exit(1)
	}
	port = strings.Replace(port, "\"", "", -1)

	if port[0] != ':' {
		port = ":" + port
	}

	return &HTTPInput{prefix: prefix, port: port}
}

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
	}
	all, err := ioutil.ReadAll(r.Body)
	if err != nil {
		fmt.Printf("Error when reading HTTP request body: %q\n", err)
	}
	hi.retchan <- &work.Work{Data: all, Err: err}
}

func (hi *HTTPInput) Start() chan *work.Work {
	hi.retchan = make(chan *work.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
}