/
main.go
69 lines (55 loc) · 1.25 KB
/
main.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 main
import (
"flag"
"log"
"net/http"
"os"
"github.com/hairqles/queue-proxy/queue"
)
// Queue storage.
var q queue.QueueStorageInterface
// Client endpoint.
var clientUrl string
func init() {
clientUrl = os.Getenv("QUEUE_PROXY_CLIENT_URL")
flag.StringVar(&clientUrl, "client-url", "", "Client url enpoint")
if clientUrl == "" {
log.Fatal("Missing client endpoint configuration.")
}
q = queue.New()
}
func main() {
http.HandleFunc("/enqueue", EnqueueHandler)
http.HandleFunc("/dequeue", DequeueHandler)
err := http.ListenAndServe(":80", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
// Enqueue a new request into the queue.
func EnqueueHandler(rw http.ResponseWriter, req *http.Request) {
if err := q.Enqueue(req); err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
rw.WriteHeader(http.StatusOK)
return
}
// Dequeue a request from the queue and send it to the client.
func DequeueHandler(rw http.ResponseWriter, req *http.Request) {
req, err := q.Dequeue()
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return
}
if resp.StatusCode <= 300 {
return
}
rw.WriteHeader(http.StatusOK)
return
}