-
Notifications
You must be signed in to change notification settings - Fork 1
/
web.go
93 lines (79 loc) · 2.07 KB
/
web.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 web
import (
"encoding/hex"
"fmt"
"net/http"
"strings"
"github.com/bohdantrotsenko/chainy"
)
type Server struct {
b *chainy.Blocks
}
func New(b *chainy.Blocks) *Server {
return &Server{b}
}
func (s *Server) serveEntry(w http.ResponseWriter, r *http.Request, e *chainy.Entry) {
h := w.Header()
h.Add("Content-Length", fmt.Sprintf("%d", len(e.Content)))
if len(e.PrevHash) > 0 {
h.Add("X-Prev-Hash", fmt.Sprintf("%x", e.PrevHash))
}
if len(e.NextHash) > 0 {
h.Add("X-Next-Hash", fmt.Sprintf("%x", e.NextHash))
}
h.Add("X-Block", fmt.Sprintf("%d", e.Height))
h.Add("X-Date", fmt.Sprintf("%d:%d", e.Instant.Unix(), e.Instant.Nanosecond()))
h.Add("X-Content-Hash", fmt.Sprintf("%x", e.ContentHash))
h.Add("X-Sign", fmt.Sprintf("%x", e.Signature))
w.WriteHeader(http.StatusOK)
if r.Method == "GET" {
w.Write(e.Content)
}
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" && r.Method != "HEAD" {
http.Error(w, "", http.StatusMethodNotAllowed)
return
}
if r.URL == nil {
http.Error(w, "no url", http.StatusInternalServerError)
return
}
//log.Println(r.URL.Path)
if strings.HasPrefix(r.URL.Path, "/next/") {
hashStr := r.URL.Path[len("/next/"):]
hash, err := hex.DecodeString(hashStr)
if err != nil {
http.Error(w, "bad hash", http.StatusBadRequest)
return
}
entry, err := s.b.WaitForNext(r.Context(), hash)
if err != nil {
http.Error(w, "bad hash", http.StatusBadRequest)
return
}
http.Redirect(w, r, fmt.Sprintf("/%x", entry.Hash()), http.StatusMovedPermanently)
return
}
if r.URL.Path == "/" {
entry, err := s.b.WaitForNext(r.Context(), nil)
if err != nil {
http.Error(w, "bad hash", http.StatusBadRequest)
return
}
http.Redirect(w, r, fmt.Sprintf("/%x", entry.Hash()), http.StatusMovedPermanently)
return
}
hashStr := r.URL.Path[len("/"):]
hash, err := hex.DecodeString(hashStr)
if err != nil {
http.Error(w, "bad hash", http.StatusBadRequest)
return
}
entry, err := s.b.Get(hash)
if entry == nil {
http.NotFound(w, r)
return
}
s.serveEntry(w, r, entry)
}