-
Notifications
You must be signed in to change notification settings - Fork 0
/
server_initializer.go
93 lines (76 loc) · 2.13 KB
/
server_initializer.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package main
import (
"encoding/json"
"io/ioutil"
"net/http"
"example/internal"
"github.com/garyburd/redigo/redis"
"github.com/go-nacelle/httpbase"
"github.com/go-nacelle/nacelle"
)
type ServerInitializer struct {
Logger nacelle.Logger `service:"logger"`
Redis redis.Conn `service:"redis"`
}
func NewServerInitializer() httpbase.ServerInitializer {
return &ServerInitializer{}
}
func (si *ServerInitializer) Init(config nacelle.Config, server *http.Server) error {
server.Handler = http.HandlerFunc(si.handle)
return nil
}
func (si *ServerInitializer) handle(w http.ResponseWriter, r *http.Request) {
if id := r.URL.Path[1:]; id != "" && r.Method == "GET" {
si.handleGet(w, r, id)
return
}
if id := r.URL.Path[1:]; id == "" && r.Method == "POST" {
si.handlePost(w, r)
return
}
w.WriteHeader(http.StatusMethodNotAllowed)
}
func (si *ServerInitializer) handleGet(w http.ResponseWriter, r *http.Request, id string) {
response, err := internal.GetResult(si.Redis, id)
if err != nil {
si.error(w, "Failed to read request body (%s)", err)
return
}
if response == nil {
w.WriteHeader(http.StatusNotFound)
return
}
serialized, err := json.Marshal(response)
if err != nil {
si.error(w, "Failed to serialize response (%s)", err)
return
}
si.Logger.Debug("Retrieved key %s", id)
w.WriteHeader(http.StatusOK)
w.Write(serialized)
}
func (si *ServerInitializer) handlePost(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
content, err := ioutil.ReadAll(r.Body)
if err != nil {
si.error(w, "Failed to read request body (%s)", err)
return
}
id, err := internal.PublishWork(si.Redis, string(content))
if err != nil {
si.error(w, "Failed to publish work (%s)", err)
return
}
serialized, err := json.Marshal(map[string]string{"id": id})
if err != nil {
si.error(w, "Failed to serialize response (%s)", err)
return
}
si.Logger.Debug("Published work with id %s", id)
w.WriteHeader(http.StatusAccepted)
w.Write(serialized)
}
func (si *ServerInitializer) error(w http.ResponseWriter, format string, err error) {
si.Logger.Error(format, err.Error())
w.WriteHeader(http.StatusInternalServerError)
}