forked from trezor/trezord-go
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathhttp.go
More file actions
91 lines (73 loc) · 1.97 KB
/
Copy pathhttp.go
File metadata and controls
91 lines (73 loc) · 1.97 KB
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
package server
import (
"fmt"
"io"
"net/http"
"github.com/OneKeyHQ/onekey-bridge/core"
"github.com/OneKeyHQ/onekey-bridge/memorywriter"
"github.com/OneKeyHQ/onekey-bridge/server/api"
"github.com/OneKeyHQ/onekey-bridge/server/status"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
type serverPrivate struct {
*http.Server
}
type Server struct {
serverPrivate
writer io.Writer
port int
}
func New(
c *core.Core,
stderrWriter io.Writer,
shortWriter *memorywriter.MemoryWriter,
longWriter *memorywriter.MemoryWriter,
version string,
httpPort int,
) (*Server, error) {
longWriter.Log("starting")
https := &http.Server{
Addr: fmt.Sprintf("127.0.0.1:%d", httpPort),
}
allWriter := io.MultiWriter(stderrWriter, shortWriter, longWriter)
s := &Server{
serverPrivate: serverPrivate{
Server: https,
},
writer: allWriter,
port: httpPort,
}
r := mux.NewRouter()
statusRouter := r.PathPrefix("/status").Subrouter()
postRouter := r.Methods("POST").Subrouter()
redirectRouter := r.Methods("GET").Path("/").Subrouter()
status.ServeStatus(statusRouter, c, version, shortWriter, longWriter, httpPort)
err := api.ServeAPI(postRouter, c, version, longWriter)
if err != nil {
panic(err) // only error is an error from originValidator regexp constructor
}
status.ServeStatusRedirect(redirectRouter, httpPort)
var h http.Handler = r
// Log after the request is done, in the Apache format.
h = handlers.LoggingHandler(allWriter, h)
// Log when the request is received.
h = s.logRequest(h)
https.Handler = h
longWriter.Log("server created")
return s, nil
}
func (s *Server) logRequest(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
text := fmt.Sprintf("%s %s\n", r.Method, r.URL)
_, err := s.writer.Write([]byte(text))
if err != nil {
// give up, just print on stdout
fmt.Println(err)
}
handler.ServeHTTP(w, r)
})
}
func (s *Server) Run() error {
return s.ListenAndServe()
}