-
Notifications
You must be signed in to change notification settings - Fork 4
/
rest.go
62 lines (51 loc) · 1.26 KB
/
rest.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
package app
import (
"context"
"fmt"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/labstack/echo/v4"
"github.com/labstack/gommon/color"
"github.com/labstack/gommon/log"
internalGrpc "github.com/saefullohmaslul/kuki/internal/grpc"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"net"
)
type Rest struct {
port string
listener net.Listener
server *echo.Echo
}
func NewRest(port string, listener net.Listener) App {
return &Rest{
port: port,
listener: listener,
}
}
func (a *Rest) Start(ctx context.Context) {
conn, err := grpc.DialContext(
ctx,
a.listener.Addr().String(),
grpc.WithBlock(),
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
if err != nil {
panic(err)
}
a.server = echo.New()
mux := runtime.NewServeMux()
err = internalGrpc.RegisterTodosHandlerHandler(ctx, mux, conn)
if err != nil {
panic(err)
}
a.server.Any("*", echo.WrapHandler(mux))
fmt.Printf("⇨ http server started on %s\n", color.New().Magenta(fmt.Sprintf(":%s", a.port)))
_ = a.server.Start(fmt.Sprintf(":%s", a.port))
}
func (a *Rest) Shutdown(ctx context.Context) {
err := a.server.Shutdown(ctx)
if err != nil {
log.Fatalf("Server shutdown error: %v", err)
}
log.Info("Rest server shutdown")
}