...

Source file src/github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-grpc-gateway/main.go

Documentation: github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-grpc-gateway

     1  // Command protoc-gen-grpc-gateway is a plugin for Google protocol buffer
     2  // compiler to generate a reverse-proxy, which converts incoming RESTful
     3  // HTTP/1 requests gRPC invocation.
     4  // You rarely need to run this program directly. Instead, put this program
     5  // into your $PATH with a name "protoc-gen-grpc-gateway" and run
     6  //
     7  //	protoc --grpc-gateway_out=output_directory path/to/input.proto
     8  //
     9  // See README.md for more details.
    10  package main
    11  
    12  import (
    13  	"flag"
    14  	"fmt"
    15  	"os"
    16  	"strings"
    17  
    18  	"github.com/grpc-ecosystem/grpc-gateway/v2/internal/codegenerator"
    19  	"github.com/grpc-ecosystem/grpc-gateway/v2/internal/descriptor"
    20  	"github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-grpc-gateway/internal/gengateway"
    21  	"google.golang.org/grpc/grpclog"
    22  	"google.golang.org/protobuf/compiler/protogen"
    23  )
    24  
    25  var (
    26  	registerFuncSuffix         = flag.String("register_func_suffix", "Handler", "used to construct names of generated Register*<Suffix> methods.")
    27  	useRequestContext          = flag.Bool("request_context", true, "determine whether to use http.Request's context or not")
    28  	allowDeleteBody            = flag.Bool("allow_delete_body", false, "unless set, HTTP DELETE methods may not have a body")
    29  	grpcAPIConfiguration       = flag.String("grpc_api_configuration", "", "path to gRPC API Configuration in YAML format")
    30  	_                          = flag.Bool("allow_repeated_fields_in_body", true, "allows to use repeated field in `body` and `response_body` field of `google.api.http` annotation option. DEPRECATED: the value is ignored and always behaves as `true`.")
    31  	repeatedPathParamSeparator = flag.String("repeated_path_param_separator", "csv", "configures how repeated fields should be split. Allowed values are `csv`, `pipes`, `ssv` and `tsv`.")
    32  	allowPatchFeature          = flag.Bool("allow_patch_feature", true, "determines whether to use PATCH feature involving update masks (using google.protobuf.FieldMask).")
    33  	omitPackageDoc             = flag.Bool("omit_package_doc", false, "if true, no package comment will be included in the generated code")
    34  	standalone                 = flag.Bool("standalone", false, "generates a standalone gateway package, which imports the target service package")
    35  	versionFlag                = flag.Bool("version", false, "print the current version")
    36  	warnOnUnboundMethods       = flag.Bool("warn_on_unbound_methods", false, "emit a warning message if an RPC method has no HttpRule annotation")
    37  	generateUnboundMethods     = flag.Bool("generate_unbound_methods", false, "generate proxy methods even for RPC methods that have no HttpRule annotation")
    38  
    39  	_ = flag.Bool("logtostderr", false, "Legacy glog compatibility. This flag is a no-op, you can safely remove it")
    40  )
    41  
    42  // Variables set by goreleaser at build time
    43  var (
    44  	version = "dev"
    45  	commit  = "unknown"
    46  	date    = "unknown"
    47  )
    48  
    49  func main() {
    50  	flag.Parse()
    51  
    52  	if *versionFlag {
    53  		fmt.Printf("Version %v, commit %v, built at %v\n", version, commit, date)
    54  		os.Exit(0)
    55  	}
    56  
    57  	protogen.Options{
    58  		ParamFunc: flag.CommandLine.Set,
    59  	}.Run(func(gen *protogen.Plugin) error {
    60  		reg := descriptor.NewRegistry()
    61  
    62  		if err := applyFlags(reg); err != nil {
    63  			return err
    64  		}
    65  
    66  		codegenerator.SetSupportedFeaturesOnPluginGen(gen)
    67  
    68  		generator := gengateway.New(reg, *useRequestContext, *registerFuncSuffix, *allowPatchFeature, *standalone)
    69  
    70  		if grpclog.V(1) {
    71  			grpclog.Infof("Parsing code generator request")
    72  		}
    73  
    74  		if err := reg.LoadFromPlugin(gen); err != nil {
    75  			return err
    76  		}
    77  
    78  		unboundHTTPRules := reg.UnboundExternalHTTPRules()
    79  		if len(unboundHTTPRules) != 0 {
    80  			return fmt.Errorf("HTTP rules without a matching selector: %s", strings.Join(unboundHTTPRules, ", "))
    81  		}
    82  
    83  		targets := make([]*descriptor.File, 0, len(gen.Request.FileToGenerate))
    84  		for _, target := range gen.Request.FileToGenerate {
    85  			f, err := reg.LookupFile(target)
    86  			if err != nil {
    87  				return err
    88  			}
    89  			targets = append(targets, f)
    90  		}
    91  
    92  		files, err := generator.Generate(targets)
    93  		for _, f := range files {
    94  			if grpclog.V(1) {
    95  				grpclog.Infof("NewGeneratedFile %q in %s", f.GetName(), f.GoPkg)
    96  			}
    97  
    98  			genFile := gen.NewGeneratedFile(f.GetName(), protogen.GoImportPath(f.GoPkg.Path))
    99  			if _, err := genFile.Write([]byte(f.GetContent())); err != nil {
   100  				return err
   101  			}
   102  		}
   103  
   104  		if grpclog.V(1) {
   105  			grpclog.Info("Processed code generator request")
   106  		}
   107  
   108  		return err
   109  	})
   110  }
   111  
   112  func applyFlags(reg *descriptor.Registry) error {
   113  	if *grpcAPIConfiguration != "" {
   114  		if err := reg.LoadGrpcAPIServiceFromYAML(*grpcAPIConfiguration); err != nil {
   115  			return err
   116  		}
   117  	}
   118  	if *warnOnUnboundMethods && *generateUnboundMethods {
   119  		grpclog.Warningf("Option warn_on_unbound_methods has no effect when generate_unbound_methods is used.")
   120  	}
   121  	reg.SetStandalone(*standalone)
   122  	reg.SetAllowDeleteBody(*allowDeleteBody)
   123  
   124  	flag.Visit(func(f *flag.Flag) {
   125  		if f.Name == "allow_repeated_fields_in_body" {
   126  			grpclog.Warning("The `allow_repeated_fields_in_body` flag is deprecated and will always behave as `true`.")
   127  		}
   128  	})
   129  
   130  	reg.SetOmitPackageDoc(*omitPackageDoc)
   131  	reg.SetWarnOnUnboundMethods(*warnOnUnboundMethods)
   132  	reg.SetGenerateUnboundMethods(*generateUnboundMethods)
   133  	return reg.SetRepeatedPathParamSeparator(*repeatedPathParamSeparator)
   134  }
   135  

View as plain text