-
Notifications
You must be signed in to change notification settings - Fork 324
/
http.go
85 lines (73 loc) · 1.96 KB
/
http.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
package api
import (
"context"
"encoding/json"
"net/http"
"strconv"
"time"
"go.uber.org/zap"
apitypes "github.com/iotexproject/iotex-core/v2/api/types"
"github.com/iotexproject/iotex-core/v2/pkg/log"
"github.com/iotexproject/iotex-core/v2/pkg/util/httputil"
)
type (
// HTTPServer crates a http server
HTTPServer struct {
svr *http.Server
}
// hTTPHandler handles requests from http protocol
hTTPHandler struct {
msgHandler Web3Handler
}
)
// NewHTTPServer creates a new http server
func NewHTTPServer(route string, port int, handler http.Handler) *HTTPServer {
if port == 0 {
return nil
}
mux := http.NewServeMux()
mux.Handle("/"+route, handler)
svr := httputil.NewServer(":"+strconv.Itoa(port), mux, httputil.ReadHeaderTimeout(10*time.Second))
return &HTTPServer{
svr: &svr,
}
}
// Start starts the http server
func (hSvr *HTTPServer) Start(_ context.Context) error {
go func() {
if err := hSvr.svr.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.L().Fatal("Node failed to serve.", zap.Error(err))
}
}()
return nil
}
// Stop stops the http server
func (hSvr *HTTPServer) Stop(ctx context.Context) error {
return hSvr.svr.Shutdown(ctx)
}
// newHTTPHandler creates a new http handler
func newHTTPHandler(web3Handler Web3Handler) *hTTPHandler {
return &hTTPHandler{
msgHandler: web3Handler,
}
}
func (handler *hTTPHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if req.Method != "POST" {
w.Write([]byte("IoTeX RPC endpoint is ready."))
return
}
if err := handler.msgHandler.HandlePOSTReq(req.Context(), req.Body,
apitypes.NewResponseWriter(
func(resp interface{}) (int, error) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
raw, err := json.Marshal(resp)
if err != nil {
return 0, err
}
return w.Write(raw)
}),
); err != nil {
log.Logger("api").Warn("fail to respond request.", zap.Error(err))
}
}