-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
69 lines (58 loc) · 1.52 KB
/
server.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
package mithril
import (
"fmt"
"net/http"
log "github.com/Sirupsen/logrus"
"github.com/modcloth/mithril/message"
"github.com/modcloth/mithril/store"
)
type Server struct {
amqp *AMQPPublisher
storage *store.Storage
}
func NewServer(storer *store.Storage, amqp *AMQPPublisher) *Server {
return &Server{
storage: storer,
amqp: amqp,
}
}
func (me *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" || r.Method == "PUT" {
me.processMessage(w, r)
} else if r.URL.Path == "/heartbeat" {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "pong\n")
} else {
me.respondErr(
fmt.Errorf(`Only "POST" and "PUT" are accepted, not %q`, r.Method),
http.StatusMethodNotAllowed,
w)
}
}
func (me *Server) processMessage(w http.ResponseWriter, r *http.Request) {
var (
msg *message.Message
err error
)
if msg, err = message.NewMessage(r); err != nil {
me.respondErr(err, http.StatusBadRequest, w)
return
}
log.Infof("Processing message: ", msg.MessageId)
if err = me.storage.Store(msg); err != nil {
me.respondErr(err, http.StatusBadRequest, w)
return
}
if err = me.amqp.Publish(msg); err != nil {
me.respondErr(err, http.StatusBadRequest, w)
return
}
w.WriteHeader(http.StatusNoContent)
w.Write([]byte(""))
}
func (me *Server) respondErr(err error, status int, w http.ResponseWriter) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(status)
fmt.Fprintf(w, "WOMP WOMP: %v\n", err)
}