Created
July 12, 2019 02:04
-
-
Save zacker330/38842679aefa65e221a4394af6fcf952 to your computer and use it in GitHub Desktop.
main.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" // Use "golang.org/x/net/context" for Golang version <= 1.6 | |
"flag" | |
"net/http" | |
"github.com/golang/glog" | |
"github.com/grpc-ecosystem/grpc-gateway/runtime" | |
"google.golang.org/grpc" | |
gw "showme.codes/ossl/ossl" // Update | |
"strings" | |
) | |
var ( | |
// command-line options: | |
// gRPC server endpoint | |
grpcServerEndpoint = flag.String("grpc-server-endpoint", "localhost:8187", "gRPC server endpoint") | |
) | |
func allowCORS(h http.Handler) http.Handler { | |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
w.Header().Set("Access-Control-Allow-Origin", "*") | |
if r.Method == "OPTIONS" && r.Header.Get("Access-Control-Request-Method") != "" { | |
preflightHandler(w, r) | |
return | |
} | |
h.ServeHTTP(w, r) | |
}) | |
} | |
func preflightHandler(w http.ResponseWriter, r *http.Request) { | |
headers := []string{"Content-Type", "Accept"} | |
w.Header().Set("Access-Control-Allow-Origin", "*") | |
w.Header().Set("Access-Control-Allow-Headers", strings.Join(headers, ",")) | |
methods := []string{"GET", "HEAD", "POST", "PUT", "DELETE","OPTIONS"} | |
w.Header().Set("Access-Control-Allow-Methods", strings.Join(methods, ",")) | |
glog.Infof("preflight request for %s", r.URL.Path) | |
return | |
} | |
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{grpc.WithInsecure()} | |
err := gw.RegisterCategoryServiceHandlerFromEndpoint(ctx, mux, *grpcServerEndpoint, opts) | |
if err != nil { | |
return err | |
} | |
// Start HTTP server (and proxy calls to gRPC server endpoint) | |
return http.ListenAndServe(":8286", allowCORS(mux)) | |
} | |
func main() { | |
flag.Parse() | |
defer glog.Flush() | |
if err := run(); err != nil { | |
glog.Fatal(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment