-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.go
67 lines (63 loc) · 1.6 KB
/
run.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
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
rpcpb "github.com/iost-official/go-iost/rpc/pb"
"github.com/rs/cors"
"google.golang.org/grpc"
"net/http"
"os"
"strings"
)
var grpcAddr = "0.0.0.0:30002"
func errorHandler(_ context.Context, _ *runtime.ServeMux, _ runtime.Marshaler, w http.ResponseWriter, _ *http.Request, err error) {
w.WriteHeader(400)
bytes, e := json.Marshal(err)
if e != nil {
bytes = []byte(fmt.Sprint(err))
}
w.Write(bytes)
}
func startGateway() error {
mux := runtime.NewServeMux(
runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.JSONPb{OrigName: true, EmitDefaults: true}),
runtime.WithProtoErrorHandler(errorHandler))
opts := []grpc.DialOption{grpc.WithInsecure()}
err := rpcpb.RegisterApiServiceHandlerFromEndpoint(context.Background(), mux, grpcAddr, opts)
if err != nil {
return err
}
c := cors.New(cors.Options{
AllowedHeaders: []string{"Content-Type", "Accept"},
AllowedMethods: []string{"GET", "HEAD", "POST", "PUT", "DELETE"},
AllowedOrigins: []string{"*"},
})
gatewayServer := &http.Server{
Addr: "0.0.0.0:30001",
Handler: http.HandlerFunc( func(w http.ResponseWriter, req *http.Request) {
c.Handler(mux).ServeHTTP(w, req)
}),
}
err = gatewayServer.ListenAndServe()
if err != http.ErrServerClosed {
panic(err)
}
return nil
}
func main() {
if len(os.Args) >= 2 {
addr := os.Args[1]
if !strings.HasSuffix(addr, ":30002") {
addr += ":30002"
}
grpcAddr = addr
}
fmt.Println("grpc connect to", grpcAddr)
var err error
err = startGateway()
if err != nil {
panic(err)
}
}