-
Notifications
You must be signed in to change notification settings - Fork 0
/
topics_controller.go
83 lines (60 loc) · 2.09 KB
/
topics_controller.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
package rest
import (
"encoding/base64"
"net/http"
"strconv"
"github.com/dgraph-io/badger"
"goji.io/pat"
)
type TopicsController struct {
}
func (c *TopicsController) Register(mux *CtxMux) {
mux.Handle(pat.Get("/topics/:topic/partitions/:partition/offset/:offset"), c.FetchMessage)
mux.Handle(pat.Get("/topics/:topic/partitions/:partition/offset/:offset/download"), c.DownloadMessage)
}
func (c *TopicsController) DownloadMessage(ctx *WebContext, w http.ResponseWriter, req *http.Request) (interface{}, int, error) {
topic := pat.Param(req, "topic")
partition, err := Int32Param("partition", req)
if err != nil {
return nil, http.StatusBadRequest, nil
}
offset, err := Int64Param("offset", req)
if err != nil {
return nil, http.StatusBadRequest, nil
}
msg, err := ctx.engine.Db.FindMessage(topic, partition, offset)
if err == nil {
ext := ".json"
content := msg.Value.Value
if msg.Value.Type == "binary" {
ext = ".bin"
content = []byte(base64.StdEncoding.EncodeToString(msg.Value.Value))
}
filename := msg.Topic + "-" + strconv.FormatInt(int64(msg.Partition), 10) + "-" + strconv.FormatInt(int64(msg.Offset), 10) + ext
w.Header().Set("Content-Disposition", "attachment; filename="+filename)
// w.Header().Set("Content-Type", req.Header.Get("Content-Type"))
// fmt.Fprint(w, content)
return content, http.StatusOK, nil
} else if err == badger.ErrKeyNotFound {
return nil, http.StatusNotFound, nil
}
return nil, http.StatusInternalServerError, nil
}
func (c *TopicsController) FetchMessage(ctx *WebContext, w http.ResponseWriter, req *http.Request) (interface{}, int, error) {
topic := pat.Param(req, "topic")
partition, err := Int32Param("partition", req)
if err != nil {
return nil, http.StatusBadRequest, nil
}
offset, err := Int64Param("offset", req)
if err != nil {
return nil, http.StatusBadRequest, nil
}
msg, err := ctx.engine.Db.FindMessage(topic, partition, offset)
if err == nil {
return msg, http.StatusOK, nil
} else if err == badger.ErrKeyNotFound {
return nil, http.StatusNotFound, nil
}
return nil, http.StatusInternalServerError, nil
}