-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
133 lines (112 loc) · 2.51 KB
/
router.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
package server
import (
"context"
"crypto/tls"
"fmt"
"net"
"net/http"
"os"
"strings"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/logger"
"github.com/mayocream/hath-go/pkg/hath"
hServer "github.com/mayocream/hath-go/server"
"github.com/spf13/viper"
"go.uber.org/zap"
)
// Server ...
type Server struct {
hath *hServer.Hath
}
// NewServer ...
func NewServer(hath *hServer.Hath) *Server {
return &Server{
hath: hath,
}
}
// Serve ...
func (s *Server) Serve(ctx context.Context) error {
srv := fiber.New()
srv.All("/h/*", s.hvFileHandler)
srv.All("/servercmd/*", s.serverCmdHandler)
srv.All("/t/*", s.testHandler)
if viper.GetBool("debug") {
zap.S().Info("Fiber server now record http request to logs")
logConf := logger.ConfigDefault
logConf.Output = os.Stdout
srv.Use(logger.New(logConf))
}
tlsConfig, err := s.hath.TLSConfig()
if err != nil {
return err
}
zap.S().Info("HTTP Server will serve at: %v", s.hath.Addr())
ln, err := net.Listen("tcp", fmt.Sprintf(":%v", s.hath.Addr()))
if err != nil {
return err
}
ln = tls.NewListener(ln, tlsConfig)
zap.S().Info("HTTPS Server enabled.")
go func() {
<-ctx.Done()
zap.S().Info("HTTP server graceful shutdown...")
srv.Shutdown()
zap.S().Info("Finished HTTP server graceful shutdown.")
}()
return srv.Listener(ln)
}
func (s *Server) hvFileHandler(c *fiber.Ctx) error {
params := c.Params("*")
split := strings.Split(params, "/")
if len(split) != 3 {
return &fiber.Error{
Code: http.StatusBadRequest,
}
}
hv, err := s.hath.HandleHV(split[0], split[1], split[2])
if err != nil {
return wrapErr(err)
}
c.Send(hv.Data)
return nil
}
func (s *Server) serverCmdHandler(c *fiber.Ctx) error {
params := c.Params("*")
split := strings.Split(params, "/")
if len(split) != 4 {
return &fiber.Error{
Code: http.StatusBadRequest,
}
}
ip := c.Context().RemoteIP().String()
result, err := s.hath.HandleHathCmd(ip, split[0], split[1], split[2], split[3])
if err != nil {
return wrapErr(err)
}
c.Send(result)
return nil
}
func (s *Server) testHandler(c *fiber.Ctx) error {
params := c.Params("*")
split := strings.Split(params, "/")
if len(split) != 3 {
return &fiber.Error{
Code: http.StatusBadRequest,
}
}
result, err := s.hath.HandleTest(split[0], split[1], split[2])
if err != nil {
return err
}
c.Send(result)
return nil
}
func wrapErr(err error) error {
if err, ok := err.(*hath.HTTPErr); ok {
return &fiber.Error{
Code: err.Status,
Message: err.Error(),
}
}
return err
}