2021-01-17 22:15:20 +08:00

107 lines
2.4 KiB
Go

package main
import (
"context"
"crypto/tls"
"crypto/x509"
"flag"
"io/ioutil"
"net/http"
"github.com/golang/glog"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
log "github.com/sirupsen/logrus"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
gw "github.com/esinio/geco/gen/proto/echo/v1" // Update
)
var (
grpcServerEndpoint string
)
func init() {
flag.StringVar(&grpcServerEndpoint, "grpc-server-endpoint", "localhost:9090", "gRPC server endpoint")
}
func run() error {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// Register gRPC server endpoint
// Note: Make sure the gRPC server is running properly and accessible
mux := runtime.NewServeMux()
opts := []grpc.DialOption{
grpcServerClientCreds(),
}
err := gw.RegisterEchoServiceHandlerFromEndpoint(ctx, mux, grpcServerEndpoint, opts)
if err != nil {
return err
}
// Start HTTP server (and proxy calls to gRPC server endpoint)
return http.ListenAndServe(":8081", mux)
}
func main() {
flag.Parse()
defer glog.Flush()
if err := run(); err != nil {
glog.Fatal(err)
}
}
// func gwCreds() credentials.TransportCredentials {
// cert, err := tls.LoadX509KeyPair("./cert/server.pem", "./cert/server.key")
// if err != nil {
// log.Fatal(err)
// }
// certPool := x509.NewCertPool()
// ca, err := ioutil.ReadFile("./cert/ca.pem")
// if err != nil {
// log.Fatal(err)
// }
// if ok := certPool.AppendCertsFromPEM(ca); !ok {
// log.Fatal("failed to append certs")
// }
// creds := credentials.NewTLS(&tls.Config{
// Certificates: []tls.Certificate{cert},
// ClientAuth: tls.RequireAndVerifyClientCert, // NOTE: this is optional!
// ClientCAs: certPool,
// })
// return creds
// }
func grpcServerClientCreds() grpc.DialOption {
cert, err := tls.LoadX509KeyPair("./cert/client.pem", "./cert/client.key")
if err != nil {
log.Fatalf("tls.LoadX509KeyPair err: %v", err)
return nil
}
certPool := x509.NewCertPool()
ca, err := ioutil.ReadFile("./cert/ca.pem")
if err != nil {
log.Fatalf("ioutil.ReadFile err: %v", err)
return nil
}
if ok := certPool.AppendCertsFromPEM(ca); !ok {
log.Fatalf("certPool.AppendCertsFromPEM err")
return nil
}
creds := credentials.NewTLS(&tls.Config{
Certificates: []tls.Certificate{cert},
ServerName: "example.grpc.io",
RootCAs: certPool,
})
return grpc.WithTransportCredentials(creds)
}