/
main.go
97 lines (76 loc) · 2.04 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
94
95
96
97
// Copyright (C) 2021 Storj Labs, Inc.
// See LICENSE for copying information.
package main
import (
"context"
"net"
"net/http"
"golang.org/x/sync/errgroup"
"storj.io/drpc/drpchttp"
"storj.io/drpc/drpcmigrate"
"storj.io/drpc/drpcmux"
"storj.io/drpc/drpcserver"
"storj.io/drpc/examples/drpc_and_http/pb"
)
type CookieMonsterServer struct {
pb.DRPCCookieMonsterUnimplementedServer
// struct fields
}
// EatCookie turns a cookie into crumbs.
func (s *CookieMonsterServer) EatCookie(ctx context.Context, cookie *pb.Cookie) (*pb.Crumbs, error) {
return &pb.Crumbs{
Cookie: cookie,
}, nil
}
func main() {
err := Main(context.Background())
if err != nil {
panic(err)
}
}
func Main(ctx context.Context) error {
// create an RPC server
cookieMonster := &CookieMonsterServer{}
// create a drpc RPC mux
m := drpcmux.New()
// register the proto-specific methods on the mux
err := pb.DRPCRegisterCookieMonster(m, cookieMonster)
if err != nil {
return err
}
// listen on a tcp socket
lis, err := net.Listen("tcp", ":8080")
if err != nil {
return err
}
// create a listen mux that evalutes enough bytes to recognize the DRPC header
lisMux := drpcmigrate.NewListenMux(lis, len(drpcmigrate.DRPCHeader))
// grap the listen mux route for the DRPC Header and default handler
drpcLis := lisMux.Route(drpcmigrate.DRPCHeader)
httpLis := lisMux.Default()
// we're going to run the different protocol servers in parallel, so
// make an errgroup
var group errgroup.Group
// drpc handling
group.Go(func() error {
// create a drpc server
s := drpcserver.New(m)
// run the server
// N.B.: if you want TLS, you need to wrap the drpcLis net.Listener
// with TLS before passing to Serve here.
return s.Serve(ctx, drpcLis)
})
// http handling
group.Go(func() error {
// create an http server using the drpc mux wrapped in a handler
s := http.Server{Handler: drpchttp.New(m)}
// run the server
return s.Serve(httpLis)
})
// run the listen mux
group.Go(func() error {
return lisMux.Run(ctx)
})
// wait
return group.Wait()
}