-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
81 lines (75 loc) · 1.65 KB
/
main.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
package main
import (
"context"
"fmt"
"github.com/gin-gonic/gin"
"github.com/soheilhy/cmux"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"grpc/cfg"
"grpc/utils"
"net"
"net/http"
)
func main() {
//db.Init()
run()
}
func run() {
lis, err := net.Listen("tcp", cfg.Uri)
if err != nil {
println(err.Error())
return
}
m := cmux.New(lis)
httpl := m.Match(cmux.HTTP1Fast())
grpcl := m.Match(cmux.Any())
go gRpc(grpcl)
go ginOrSocketIo(httpl)
fmt.Println("Listen on " + cfg.Uri)
if err := m.Serve(); err != nil {
panic(err)
}
}
func gRpc(lin net.Listener) {
var creds credentials.TransportCredentials
var s *grpc.Server
var opts []grpc.ServerOption
var err error
//拦截器
interceptor := func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
err = utils.GrpcAuth(ctx, info)
if err != nil {
return
}
// 继续处理请求
return handler(ctx, req)
}
opts = append(opts, grpc.UnaryInterceptor(interceptor))
if cfg.OpenTLS {
// TLS认证
creds, err = credentials.NewServerTLSFromFile("./cfg/keys/server.pem", "./cfg/keys/server.key")
if err != nil {
panic(err.Error())
}
opts = append(opts, grpc.Creds(creds))
}
s = grpc.NewServer(opts...)
GrpcRouters(s)
if err := s.Serve(lin); err != nil {
panic(err.Error())
}
}
func ginOrSocketIo(lin net.Listener) {
r := gin.New()
r.Use(utils.GinAuth)
r.GET("/socket.io/*any", gin.WrapH(utils.SocketIo()))
r.POST("/socket.io/*any", gin.WrapH(utils.SocketIo()))
GinRouters(r)
s := &http.Server{
Handler: r,
}
if err := s.Serve(lin); err != cmux.ErrListenerClosed {
panic(err)
}
}