/
consumer.go
52 lines (48 loc) · 1.05 KB
/
consumer.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
package main
import (
"context"
"crypto/rand"
"encoding/hex"
"io/ioutil"
"log"
"net/http"
)
func Consumer(hanlder func(ctx context.Context, req Request) (Response, error)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
b, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
ctx, cancel := context.WithTimeout(r.Context(), waitTimeout)
defer cancel()
resp, err := hanlder(ctx, Request{
Method: r.Method,
URL: r.RequestURI,
Body: b,
Header: r.Header,
})
if err != nil {
if err.Error() == context.DeadlineExceeded.Error() {
w.WriteHeader(http.StatusRequestTimeout)
return
}
log.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
for k, vals := range resp.Header {
for _, v := range vals {
w.Header().Add(k, v)
}
}
w.WriteHeader(resp.Status)
w.Write(resp.Body)
}
}
func genRequestID() string {
uid := make([]byte, 16)
rand.Read(uid)
return hex.EncodeToString(uid)
}