forked from yank1/golang-hellowolrd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
93 lines (73 loc) · 2.22 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
82
83
84
85
86
87
88
89
90
91
92
93
package main
import (
// "flag"
"context"
"flag"
"log"
"net"
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/soheilhy/cmux"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
pb "github.com/yankay/golang-helloworld/pkg/helloworld"
)
// RunInProcessGateway starts the invoke in process http gateway.
func RunInProcessGateway(ctx context.Context, addr string, opts ...runtime.ServeMuxOption) error {
// Create the main listener.
l, err := net.Listen("tcp", addr)
if err != nil {
log.Fatal(err)
}
// Create a cmux.
m := cmux.New(l)
// Match connections in order:
// First grpc, then HTTP, and otherwise Go RPC/TCP.
grpcL := m.Match(cmux.HTTP2())
httpL := m.Match(cmux.HTTP1Fast())
// gin = cmux.HTTP1HeaderFieldPrefix('path','/v1/hahaha')
// trpcL := m.Match(cmux.Any()) // Any means anything that is not yet matched.
// Create your protocol servers.
grpcS := grpc.NewServer()
pb.RegisterHelloworldServer(grpcS, pb.NewHelloWorldServer())
// Register reflection service on gRPC server.
reflection.Register(grpcS)
// grpchello.RegisterGreeterServer(grpcS, &server{})
//HTTP
r := gin.Default()
mux := runtime.NewServeMux(opts...)
pb.RegisterHelloworldHandlerServer(ctx, mux, pb.NewHelloWorldServer())
r.Any("/v1/*any", gin.WrapF(mux.ServeHTTP))
r.Static("/swagger-ui/", "assets/swagger-ui")
httpS := &http.Server{
Handler: r,
}
// fs := http.FileServer(http.Dir("./docs/swaggerui-4.1.3"))
// http.Handle("/swaggerui/", http.StripPrefix("/swaggerui/", fs))
// trpcS := rpc.NewServer()
// trpcS.Register(&ExampleRPCRcvr{})
// Use the muxed listeners for your servers.
go grpcS.Serve(grpcL)
go httpS.Serve(httpL)
// go trpcS.Accept(trpcL)
// Start serving!
if err := m.Serve(); !strings.Contains(err.Error(), "use of closed network connection") {
panic(err)
}
return nil
}
func main() {
//Init the command-line flags.
flag.Parse()
ctx, _ := context.WithCancel(context.Background())
RunInProcessGateway(ctx, ":8080")
// r := gin.Default()
// r.GET("/ping", func(c *gin.Context) {
// c.JSON(200, gin.H{
// "message": "pong",
// })
// })
// r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}