github.com/grpc-ecosystem/grpc-gateway/v2@v2.19.1/examples/internal/gateway/handlers.go (about) 1 package gateway 2 3 import ( 4 "fmt" 5 "net/http" 6 "path" 7 "strings" 8 9 "google.golang.org/grpc" 10 "google.golang.org/grpc/connectivity" 11 "google.golang.org/grpc/grpclog" 12 ) 13 14 // openAPIServer returns OpenAPI specification files located under "/openapiv2/" 15 func openAPIServer(dir string) http.HandlerFunc { 16 return func(w http.ResponseWriter, r *http.Request) { 17 if !strings.HasSuffix(r.URL.Path, ".swagger.json") { 18 grpclog.Errorf("Not Found: %s", r.URL.Path) 19 http.NotFound(w, r) 20 return 21 } 22 23 grpclog.Infof("Serving %s", r.URL.Path) 24 p := strings.TrimPrefix(r.URL.Path, "/openapiv2/") 25 p = path.Join(dir, p) 26 http.ServeFile(w, r, p) 27 } 28 } 29 30 // allowCORS allows Cross Origin Resoruce Sharing from any origin. 31 // Don't do this without consideration in production systems. 32 func allowCORS(h http.Handler) http.Handler { 33 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 34 if origin := r.Header.Get("Origin"); origin != "" { 35 w.Header().Set("Access-Control-Allow-Origin", origin) 36 if r.Method == "OPTIONS" && r.Header.Get("Access-Control-Request-Method") != "" { 37 preflightHandler(w, r) 38 return 39 } 40 } 41 h.ServeHTTP(w, r) 42 }) 43 } 44 45 // preflightHandler adds the necessary headers in order to serve 46 // CORS from any origin using the methods "GET", "HEAD", "POST", "PUT", "DELETE" 47 // We insist, don't do this without consideration in production systems. 48 func preflightHandler(w http.ResponseWriter, r *http.Request) { 49 headers := []string{"Content-Type", "Accept", "Authorization"} 50 w.Header().Set("Access-Control-Allow-Headers", strings.Join(headers, ",")) 51 methods := []string{"GET", "HEAD", "POST", "PUT", "DELETE"} 52 w.Header().Set("Access-Control-Allow-Methods", strings.Join(methods, ",")) 53 grpclog.Infof("Preflight request for %s", r.URL.Path) 54 } 55 56 // healthzServer returns a simple health handler which returns ok. 57 func healthzServer(conn *grpc.ClientConn) http.HandlerFunc { 58 return func(w http.ResponseWriter, r *http.Request) { 59 w.Header().Set("Content-Type", "text/plain") 60 if s := conn.GetState(); s != connectivity.Ready { 61 http.Error(w, fmt.Sprintf("grpc server is %s", s), http.StatusBadGateway) 62 return 63 } 64 fmt.Fprintln(w, "ok") 65 } 66 }