-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
63 lines (58 loc) · 1.69 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
// Command gunk-example-server-gw is a grpc-gateway example implementation for
// the gunk-example-server.
package main
import (
"context"
"flag"
"fmt"
"net"
"net/http"
"os"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/kenshaw/redoc"
"google.golang.org/grpc"
examplepb "github.com/gunk/gunk-example-server/api/v1"
)
func main() {
addr := flag.String("l", ":9091", "listen address")
endpoint := flag.String("endpoint", "localhost:9090", "grpc endpoint")
spec := flag.String("spec", "/v1/swagger.json", "spec url")
flag.Parse()
if err := run(context.Background(), *addr, *endpoint, *spec); err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
}
// run creates and runs the gateway instance.
func run(ctx context.Context, addr, endpoint, spec string) error {
// build gateway mux
gw, opts := runtime.NewServeMux(), []grpc.DialOption{grpc.WithInsecure()}
for _, f := range []func(context.Context, *runtime.ServeMux, string, []grpc.DialOption) error{
examplepb.RegisterUtilHandlerFromEndpoint,
examplepb.RegisterCountriesHandlerFromEndpoint,
} {
if err := f(ctx, gw, endpoint, opts); err != nil {
return err
}
}
// build mux
mux := http.NewServeMux()
// handle swagger
mux.HandleFunc(spec, func(res http.ResponseWriter, req *http.Request) {
res.Header().Set("Content-Type", "application/json")
_, _ = res.Write(examplepb.Swagger)
})
// handle gateway
mux.Handle("/v1/", gw)
// add redoc
if err := redoc.New(spec, "/", redoc.WithServeMux(mux)).Build(ctx, nil); err != nil {
return err
}
// listen and serve
l, err := (&net.ListenConfig{}).Listen(ctx, "tcp", addr)
if err != nil {
return err
}
defer l.Close()
return http.Serve(l, mux)
}