diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..4576a43 --- /dev/null +++ b/Makefile @@ -0,0 +1,63 @@ +CMD_NAME := demo-app # TODO: Update app name + +.PHONY: all test build docker install clean proto check_protoc + +VERSION ?= development # Default to "development" if VERSION is not set +APIVERSION := v1alpha1 +API_DIR := api/$(APIVERSION) +PROTO_DIRS := $(wildcard proto/demo/app/*) # TODO: Update path (probably not demo) +PLATFORMS := linux/amd64 linux/arm64 darwin/amd64 darwin/arm64 +OUTPUT_DIR := bin +VER_PKG := gitea.libretechconsulting.com/rmcguire/go-app/pkg/config.Version +DOCKER_IMG := gitea.libretechconsulting.com/rmcguire/go-http-server-with-otel + +all: proto test build docker + +proto: check_protoc $(API_DIR) + protoc --proto_path=proto --proto_path=proto/google \ + --go_out=$(API_DIR) --go_opt=paths=source_relative \ + --go-grpc_out=$(API_DIR) --go-grpc_opt=paths=source_relative \ + --grpc-gateway_out=$(API_DIR) --grpc-gateway_opt=paths=source_relative \ + --openapiv2_out=$(API_DIR) \ + $(foreach dir, $(PROTO_DIRS), $(wildcard $(dir)/*.proto)) + +test: + go test -v ./... + +build: test + @echo "Building for platforms: $(PLATFORMS)" + @for platform in $(PLATFORMS); do \ + OS=$$(echo $$platform | cut -d/ -f1); \ + ARCH=$$(echo $$platform | cut -d/ -f2); \ + OUTPUT="$(OUTPUT_DIR)/$(CMD_NAME)-$$OS-$$ARCH"; \ + GOOS=$$OS GOARCH=$$ARCH go build -ldflags "-X $(VER_PKG)=$(VERSION)" -o $$OUTPUT; \ + echo "Built $$OUTPUT"; \ + done + go build -ldflags "-X $(VER_PKG)=$(VERSION)" -o bin/${CMD_NAME} + +schema: + go run . -schema > contrib/schema.json + +docker: + @echo "Building Docker image $(DOCKER_IMG):$(VERSION)" + docker build \ + --build-arg VER_PKG=$(VER_PKG) \ + --build-arg VERSION=$(VERSION) \ + -t $(DOCKER_IMG):$(VERSION) . + docker push $(DOCKER_IMG):$(VERSION) + +install: + go install -v -ldflags "-X $(VER_PKG)=$(VERSION)" . + +clean: + rm -rf bin/${CMD_NAME} + +check_protoc: + @if ! command -v protoc-gen-go > /dev/null; then \ + echo "Error: protoc-gen-go not found in PATH"; \ + exit 1; \ + fi + @if ! command -v protoc-gen-go-grpc > /dev/null; then \ + echo "Error: protoc-gen-go-grpc not found in PATH"; \ + exit 1; \ + fi diff --git a/TODO.md b/TODO.md new file mode 100644 index 0000000..43ff0c9 --- /dev/null +++ b/TODO.md @@ -0,0 +1,6 @@ +# Demo app TODO + +- [ ] Rename project +- [ ] Finish grpc sample implementation +- [ ] Add Dockerfile +- [ ] Add gitea CI diff --git a/api/v1alpha1/demo/app/v1alpha1/app.pb.go b/api/v1alpha1/demo/app/v1alpha1/app.pb.go new file mode 100644 index 0000000..2a24f1b --- /dev/null +++ b/api/v1alpha1/demo/app/v1alpha1/app.pb.go @@ -0,0 +1,210 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.36.6 +// protoc v5.29.3 +// source: demo/app/v1alpha1/app.proto + +package demo + +import ( + _ "google.golang.org/genproto/googleapis/api/annotations" + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + timestamppb "google.golang.org/protobuf/types/known/timestamppb" + reflect "reflect" + sync "sync" + unsafe "unsafe" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +// Options for random fact, in this case +// just a language +type GetDemoRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + Language *string `protobuf:"bytes,1,opt,name=language,proto3,oneof" json:"language,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetDemoRequest) Reset() { + *x = GetDemoRequest{} + mi := &file_demo_app_v1alpha1_app_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetDemoRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetDemoRequest) ProtoMessage() {} + +func (x *GetDemoRequest) ProtoReflect() protoreflect.Message { + mi := &file_demo_app_v1alpha1_app_proto_msgTypes[0] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetDemoRequest.ProtoReflect.Descriptor instead. +func (*GetDemoRequest) Descriptor() ([]byte, []int) { + return file_demo_app_v1alpha1_app_proto_rawDescGZIP(), []int{0} +} + +func (x *GetDemoRequest) GetLanguage() string { + if x != nil && x.Language != nil { + return *x.Language + } + return "" +} + +// Returns a randome fact, because this is a demo app +// so what else do we do? +type GetDemoResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Timestamp *timestamppb.Timestamp `protobuf:"bytes,1,opt,name=timestamp,proto3" json:"timestamp,omitempty"` + Fact string `protobuf:"bytes,2,opt,name=fact,proto3" json:"fact,omitempty"` + Source string `protobuf:"bytes,3,opt,name=source,proto3" json:"source,omitempty"` + Language string `protobuf:"bytes,4,opt,name=language,proto3" json:"language,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetDemoResponse) Reset() { + *x = GetDemoResponse{} + mi := &file_demo_app_v1alpha1_app_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetDemoResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetDemoResponse) ProtoMessage() {} + +func (x *GetDemoResponse) ProtoReflect() protoreflect.Message { + mi := &file_demo_app_v1alpha1_app_proto_msgTypes[1] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetDemoResponse.ProtoReflect.Descriptor instead. +func (*GetDemoResponse) Descriptor() ([]byte, []int) { + return file_demo_app_v1alpha1_app_proto_rawDescGZIP(), []int{1} +} + +func (x *GetDemoResponse) GetTimestamp() *timestamppb.Timestamp { + if x != nil { + return x.Timestamp + } + return nil +} + +func (x *GetDemoResponse) GetFact() string { + if x != nil { + return x.Fact + } + return "" +} + +func (x *GetDemoResponse) GetSource() string { + if x != nil { + return x.Source + } + return "" +} + +func (x *GetDemoResponse) GetLanguage() string { + if x != nil { + return x.Language + } + return "" +} + +var File_demo_app_v1alpha1_app_proto protoreflect.FileDescriptor + +const file_demo_app_v1alpha1_app_proto_rawDesc = "" + + "\n" + + "\x1bdemo/app/v1alpha1/app.proto\x12\x11demo.app.v1alpha1\x1a\x1cgoogle/api/annotations.proto\x1a\x1fgoogle/protobuf/timestamp.proto\">\n" + + "\x0eGetDemoRequest\x12\x1f\n" + + "\blanguage\x18\x01 \x01(\tH\x00R\blanguage\x88\x01\x01B\v\n" + + "\t_language\"\x93\x01\n" + + "\x0fGetDemoResponse\x128\n" + + "\ttimestamp\x18\x01 \x01(\v2\x1a.google.protobuf.TimestampR\ttimestamp\x12\x12\n" + + "\x04fact\x18\x02 \x01(\tR\x04fact\x12\x16\n" + + "\x06source\x18\x03 \x01(\tR\x06source\x12\x1a\n" + + "\blanguage\x18\x04 \x01(\tR\blanguage2z\n" + + "\x0eDemoAppService\x12h\n" + + "\aGetDemo\x12!.demo.app.v1alpha1.GetDemoRequest\x1a\".demo.app.v1alpha1.GetDemoResponse\"\x16\x82\xd3\xe4\x93\x02\x10\x12\x0e/v1alpha1/demoBSZQgitea.libretechconsulting.com/rmcguire/go-http-server-with-otel/api/v1alpha1/demob\x06proto3" + +var ( + file_demo_app_v1alpha1_app_proto_rawDescOnce sync.Once + file_demo_app_v1alpha1_app_proto_rawDescData []byte +) + +func file_demo_app_v1alpha1_app_proto_rawDescGZIP() []byte { + file_demo_app_v1alpha1_app_proto_rawDescOnce.Do(func() { + file_demo_app_v1alpha1_app_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_demo_app_v1alpha1_app_proto_rawDesc), len(file_demo_app_v1alpha1_app_proto_rawDesc))) + }) + return file_demo_app_v1alpha1_app_proto_rawDescData +} + +var file_demo_app_v1alpha1_app_proto_msgTypes = make([]protoimpl.MessageInfo, 2) +var file_demo_app_v1alpha1_app_proto_goTypes = []any{ + (*GetDemoRequest)(nil), // 0: demo.app.v1alpha1.GetDemoRequest + (*GetDemoResponse)(nil), // 1: demo.app.v1alpha1.GetDemoResponse + (*timestamppb.Timestamp)(nil), // 2: google.protobuf.Timestamp +} +var file_demo_app_v1alpha1_app_proto_depIdxs = []int32{ + 2, // 0: demo.app.v1alpha1.GetDemoResponse.timestamp:type_name -> google.protobuf.Timestamp + 0, // 1: demo.app.v1alpha1.DemoAppService.GetDemo:input_type -> demo.app.v1alpha1.GetDemoRequest + 1, // 2: demo.app.v1alpha1.DemoAppService.GetDemo:output_type -> demo.app.v1alpha1.GetDemoResponse + 2, // [2:3] is the sub-list for method output_type + 1, // [1:2] is the sub-list for method input_type + 1, // [1:1] is the sub-list for extension type_name + 1, // [1:1] is the sub-list for extension extendee + 0, // [0:1] is the sub-list for field type_name +} + +func init() { file_demo_app_v1alpha1_app_proto_init() } +func file_demo_app_v1alpha1_app_proto_init() { + if File_demo_app_v1alpha1_app_proto != nil { + return + } + file_demo_app_v1alpha1_app_proto_msgTypes[0].OneofWrappers = []any{} + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: unsafe.Slice(unsafe.StringData(file_demo_app_v1alpha1_app_proto_rawDesc), len(file_demo_app_v1alpha1_app_proto_rawDesc)), + NumEnums: 0, + NumMessages: 2, + NumExtensions: 0, + NumServices: 1, + }, + GoTypes: file_demo_app_v1alpha1_app_proto_goTypes, + DependencyIndexes: file_demo_app_v1alpha1_app_proto_depIdxs, + MessageInfos: file_demo_app_v1alpha1_app_proto_msgTypes, + }.Build() + File_demo_app_v1alpha1_app_proto = out.File + file_demo_app_v1alpha1_app_proto_goTypes = nil + file_demo_app_v1alpha1_app_proto_depIdxs = nil +} diff --git a/api/v1alpha1/demo/app/v1alpha1/app.pb.gw.go b/api/v1alpha1/demo/app/v1alpha1/app.pb.gw.go new file mode 100644 index 0000000..7e042b8 --- /dev/null +++ b/api/v1alpha1/demo/app/v1alpha1/app.pb.gw.go @@ -0,0 +1,163 @@ +// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. +// source: demo/app/v1alpha1/app.proto + +/* +Package demo is a reverse proxy. + +It translates gRPC into RESTful JSON APIs. +*/ +package demo + +import ( + "context" + "errors" + "io" + "net/http" + + "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" + "github.com/grpc-ecosystem/grpc-gateway/v2/utilities" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" +) + +// Suppress "imported and not used" errors +var ( + _ codes.Code + _ io.Reader + _ status.Status + _ = errors.New + _ = runtime.String + _ = utilities.NewDoubleArray + _ = metadata.Join +) + +var filter_DemoAppService_GetDemo_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} + +func request_DemoAppService_GetDemo_0(ctx context.Context, marshaler runtime.Marshaler, client DemoAppServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var ( + protoReq GetDemoRequest + metadata runtime.ServerMetadata + ) + io.Copy(io.Discard, req.Body) + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_DemoAppService_GetDemo_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + msg, err := client.GetDemo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err +} + +func local_request_DemoAppService_GetDemo_0(ctx context.Context, marshaler runtime.Marshaler, server DemoAppServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var ( + protoReq GetDemoRequest + metadata runtime.ServerMetadata + ) + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_DemoAppService_GetDemo_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + msg, err := server.GetDemo(ctx, &protoReq) + return msg, metadata, err +} + +// RegisterDemoAppServiceHandlerServer registers the http handlers for service DemoAppService to "mux". +// UnaryRPC :call DemoAppServiceServer directly. +// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. +// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterDemoAppServiceHandlerFromEndpoint instead. +// GRPC interceptors will not work for this type of registration. To use interceptors, you must use the "runtime.WithMiddlewares" option in the "runtime.NewServeMux" call. +func RegisterDemoAppServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux, server DemoAppServiceServer) error { + mux.Handle(http.MethodGet, pattern_DemoAppService_GetDemo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/demo.app.v1alpha1.DemoAppService/GetDemo", runtime.WithHTTPPathPattern("/v1alpha1/demo")) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_DemoAppService_GetDemo_0(annotatedContext, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) + if err != nil { + runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) + return + } + forward_DemoAppService_GetDemo_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + + return nil +} + +// RegisterDemoAppServiceHandlerFromEndpoint is same as RegisterDemoAppServiceHandler but +// automatically dials to "endpoint" and closes the connection when "ctx" gets done. +func RegisterDemoAppServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { + conn, err := grpc.NewClient(endpoint, opts...) + if err != nil { + return err + } + defer func() { + if err != nil { + if cerr := conn.Close(); cerr != nil { + grpclog.Errorf("Failed to close conn to %s: %v", endpoint, cerr) + } + return + } + go func() { + <-ctx.Done() + if cerr := conn.Close(); cerr != nil { + grpclog.Errorf("Failed to close conn to %s: %v", endpoint, cerr) + } + }() + }() + return RegisterDemoAppServiceHandler(ctx, mux, conn) +} + +// RegisterDemoAppServiceHandler registers the http handlers for service DemoAppService to "mux". +// The handlers forward requests to the grpc endpoint over "conn". +func RegisterDemoAppServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { + return RegisterDemoAppServiceHandlerClient(ctx, mux, NewDemoAppServiceClient(conn)) +} + +// RegisterDemoAppServiceHandlerClient registers the http handlers for service DemoAppService +// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "DemoAppServiceClient". +// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "DemoAppServiceClient" +// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in +// "DemoAppServiceClient" to call the correct interceptors. This client ignores the HTTP middlewares. +func RegisterDemoAppServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client DemoAppServiceClient) error { + mux.Handle(http.MethodGet, pattern_DemoAppService_GetDemo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/demo.app.v1alpha1.DemoAppService/GetDemo", runtime.WithHTTPPathPattern("/v1alpha1/demo")) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_DemoAppService_GetDemo_0(annotatedContext, inboundMarshaler, client, req, pathParams) + annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) + if err != nil { + runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) + return + } + forward_DemoAppService_GetDemo_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + return nil +} + +var ( + pattern_DemoAppService_GetDemo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1alpha1", "demo"}, "")) +) + +var ( + forward_DemoAppService_GetDemo_0 = runtime.ForwardResponseMessage +) diff --git a/api/v1alpha1/demo/app/v1alpha1/app.swagger.json b/api/v1alpha1/demo/app/v1alpha1/app.swagger.json new file mode 100644 index 0000000..df72bf5 --- /dev/null +++ b/api/v1alpha1/demo/app/v1alpha1/app.swagger.json @@ -0,0 +1,99 @@ +{ + "swagger": "2.0", + "info": { + "title": "demo/app/v1alpha1/app.proto", + "version": "version not set" + }, + "tags": [ + { + "name": "DemoAppService" + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "paths": { + "/v1alpha1/demo": { + "get": { + "operationId": "DemoAppService_GetDemo", + "responses": { + "200": { + "description": "A successful response.", + "schema": { + "$ref": "#/definitions/v1alpha1GetDemoResponse" + } + }, + "default": { + "description": "An unexpected error response.", + "schema": { + "$ref": "#/definitions/rpcStatus" + } + } + }, + "parameters": [ + { + "name": "language", + "in": "query", + "required": false, + "type": "string" + } + ], + "tags": [ + "DemoAppService" + ] + } + } + }, + "definitions": { + "protobufAny": { + "type": "object", + "properties": { + "@type": { + "type": "string" + } + }, + "additionalProperties": {} + }, + "rpcStatus": { + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + }, + "details": { + "type": "array", + "items": { + "type": "object", + "$ref": "#/definitions/protobufAny" + } + } + } + }, + "v1alpha1GetDemoResponse": { + "type": "object", + "properties": { + "timestamp": { + "type": "string", + "format": "date-time" + }, + "fact": { + "type": "string" + }, + "source": { + "type": "string" + }, + "language": { + "type": "string" + } + }, + "title": "Returns a randome fact, because this is a demo app\nso what else do we do?" + } + } +} diff --git a/api/v1alpha1/demo/app/v1alpha1/app_grpc.pb.go b/api/v1alpha1/demo/app/v1alpha1/app_grpc.pb.go new file mode 100644 index 0000000..46d49c3 --- /dev/null +++ b/api/v1alpha1/demo/app/v1alpha1/app_grpc.pb.go @@ -0,0 +1,121 @@ +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. +// versions: +// - protoc-gen-go-grpc v1.5.1 +// - protoc v5.29.3 +// source: demo/app/v1alpha1/app.proto + +package demo + +import ( + context "context" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" +) + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +// Requires gRPC-Go v1.64.0 or later. +const _ = grpc.SupportPackageIsVersion9 + +const ( + DemoAppService_GetDemo_FullMethodName = "/demo.app.v1alpha1.DemoAppService/GetDemo" +) + +// DemoAppServiceClient is the client API for DemoAppService service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +type DemoAppServiceClient interface { + GetDemo(ctx context.Context, in *GetDemoRequest, opts ...grpc.CallOption) (*GetDemoResponse, error) +} + +type demoAppServiceClient struct { + cc grpc.ClientConnInterface +} + +func NewDemoAppServiceClient(cc grpc.ClientConnInterface) DemoAppServiceClient { + return &demoAppServiceClient{cc} +} + +func (c *demoAppServiceClient) GetDemo(ctx context.Context, in *GetDemoRequest, opts ...grpc.CallOption) (*GetDemoResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(GetDemoResponse) + err := c.cc.Invoke(ctx, DemoAppService_GetDemo_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +// DemoAppServiceServer is the server API for DemoAppService service. +// All implementations must embed UnimplementedDemoAppServiceServer +// for forward compatibility. +type DemoAppServiceServer interface { + GetDemo(context.Context, *GetDemoRequest) (*GetDemoResponse, error) + mustEmbedUnimplementedDemoAppServiceServer() +} + +// UnimplementedDemoAppServiceServer must be embedded to have +// forward compatible implementations. +// +// NOTE: this should be embedded by value instead of pointer to avoid a nil +// pointer dereference when methods are called. +type UnimplementedDemoAppServiceServer struct{} + +func (UnimplementedDemoAppServiceServer) GetDemo(context.Context, *GetDemoRequest) (*GetDemoResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetDemo not implemented") +} +func (UnimplementedDemoAppServiceServer) mustEmbedUnimplementedDemoAppServiceServer() {} +func (UnimplementedDemoAppServiceServer) testEmbeddedByValue() {} + +// UnsafeDemoAppServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to DemoAppServiceServer will +// result in compilation errors. +type UnsafeDemoAppServiceServer interface { + mustEmbedUnimplementedDemoAppServiceServer() +} + +func RegisterDemoAppServiceServer(s grpc.ServiceRegistrar, srv DemoAppServiceServer) { + // If the following call pancis, it indicates UnimplementedDemoAppServiceServer was + // embedded by pointer and is nil. This will cause panics if an + // unimplemented method is ever invoked, so we test this at initialization + // time to prevent it from happening at runtime later due to I/O. + if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { + t.testEmbeddedByValue() + } + s.RegisterService(&DemoAppService_ServiceDesc, srv) +} + +func _DemoAppService_GetDemo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetDemoRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(DemoAppServiceServer).GetDemo(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: DemoAppService_GetDemo_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(DemoAppServiceServer).GetDemo(ctx, req.(*GetDemoRequest)) + } + return interceptor(ctx, in, info, handler) +} + +// DemoAppService_ServiceDesc is the grpc.ServiceDesc for DemoAppService service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var DemoAppService_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "demo.app.v1alpha1.DemoAppService", + HandlerType: (*DemoAppServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "GetDemo", + Handler: _DemoAppService_GetDemo_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "demo/app/v1alpha1/app.proto", +} diff --git a/main.go b/main.go index dfdd4ac..77813ee 100644 --- a/main.go +++ b/main.go @@ -13,7 +13,6 @@ import ( "context" "flag" "fmt" - "net/http" "os" "os/signal" @@ -24,6 +23,7 @@ import ( optshttp "gitea.libretechconsulting.com/rmcguire/go-app/pkg/srv/http/opts" "gitea.libretechconsulting.com/rmcguire/go-http-server-with-otel/pkg/config" + "gitea.libretechconsulting.com/rmcguire/go-http-server-with-otel/pkg/demohttp" ) var flagSchema bool @@ -32,12 +32,10 @@ func main() { ctx, cncl := signal.NotifyContext(context.Background(), os.Interrupt, unix.SIGTERM) defer cncl() - // This will be loaded by go-app courtesy of MustLoadConfigInto, which will - // combine our sample configuration along with the embedded go-app AppConfig - demoAppConfig := &config.DemoConfig{} - - // Load configuration and setup logging - ctx, demoApp := app.MustLoadConfigInto(ctx, demoAppConfig) + // Load configuration and setup logging. The go-app framework + // will handle loading config and environment into our demo + // app config struct which embeds app.AooConfig + ctx, demoApp := app.MustLoadConfigInto(ctx, &config.DemoConfig{}) // Print schema if that's all we have to do if flagSchema { @@ -47,19 +45,16 @@ func main() { log.Debug().Any("demoAppMergedConfig", demoApp).Msg("demo app config prepared") + // Prepare servers + demoHTTP := demohttp.NewDemoHTTPServer(ctx, demoApp) + // Prepare app app := &app.App{ AppContext: ctx, HTTP: &optshttp.AppHTTP{ - Funcs: []optshttp.HTTPFunc{ - { - Path: "/test", - HandlerFunc: func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusNotImplemented) - w.Write([]byte("http test route")) - }, - }, - }, + Ctx: ctx, + HealthChecks: demoHTTP.GetHealthCheckFuncs(), + Funcs: demoHTTP.GetHandleFuncs(), }, } diff --git a/pkg/demohttp/server.go b/pkg/demohttp/server.go new file mode 100644 index 0000000..d59e7f2 --- /dev/null +++ b/pkg/demohttp/server.go @@ -0,0 +1,44 @@ +package demohttp + +import ( + "context" + "net/http" + + "gitea.libretechconsulting.com/rmcguire/go-app/pkg/srv/http/opts" + + "gitea.libretechconsulting.com/rmcguire/go-http-server-with-otel/pkg/config" +) + +type DemoHTTPServer struct { + ctx context.Context + cfg *config.DemoConfig +} + +func NewDemoHTTPServer(ctx context.Context, cfg *config.DemoConfig) *DemoHTTPServer { + return &DemoHTTPServer{ + ctx: ctx, + cfg: cfg, + } +} + +func (dh *DemoHTTPServer) GetHandleFuncs() []opts.HTTPFunc { + // TODO: Implement real http handle funcs + return []opts.HTTPFunc{ + { + Path: "/test", + HandlerFunc: func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNotImplemented) + w.Write([]byte("unimplemented demo app")) + }, + }, + } +} + +func (dh *DemoHTTPServer) GetHealthCheckFuncs() []opts.HealthCheckFunc { + return []opts.HealthCheckFunc{ + func(ctx context.Context) error { + // TODO: Implement real health checks + return nil + }, + } +} diff --git a/proto/demo/app/v1alpha1/app.proto b/proto/demo/app/v1alpha1/app.proto new file mode 100644 index 0000000..0c4d437 --- /dev/null +++ b/proto/demo/app/v1alpha1/app.proto @@ -0,0 +1,28 @@ +syntax = "proto3"; +package demo.app.v1alpha1; + +import "google/api/annotations.proto"; +import "google/protobuf/timestamp.proto"; + +option go_package = "gitea.libretechconsulting.com/rmcguire/go-http-server-with-otel/api/v1alpha1/demo"; + +// Options for random fact, in this case +// just a language +message GetDemoRequest { + optional string language = 1; +} + +// Returns a randome fact, because this is a demo app +// so what else do we do? +message GetDemoResponse { + google.protobuf.Timestamp timestamp = 1; + string fact = 2; + string source = 3; + string language = 4; +} + +service DemoAppService { + rpc GetDemo(GetDemoRequest) returns (GetDemoResponse) { + option (google.api.http) = {get: "/v1alpha1/demo"}; // grpc-gateway endpoint + } +} diff --git a/proto/google/README.md b/proto/google/README.md new file mode 100644 index 0000000..3d5a283 --- /dev/null +++ b/proto/google/README.md @@ -0,0 +1,22 @@ +# Google API Proto + +These are required for grpc-gateway. Ideally these are either +added to a git submodule, retrieved from a Makefile, downloaded by +buf, or retrieved by a CI job. + +**These are not guaranteed to be up to date** + +## Repo and Files + +These come from the following repo, and are required for +grpc gateway [per their documentation]() + +* Repo: [googleapis git repo](https://github.com/googleapis/googleapis) +* Docs: [grpc-gateay docs](https://github.com/grpc-ecosystem/grpc-gateway?tab=readme-ov-file#2-with-custom-annotations) + +### Files + +- [annotations.proto](https://raw.githubusercontent.com/googleapis/googleapis/refs/heads/master/google/api/annotations.proto) +- [field_behavior.proto](https://github.com/googleapis/googleapis/raw/refs/heads/master/google/api/field_behavior.proto) +- [http.proto](https://github.com/googleapis/googleapis/raw/refs/heads/master/google/api/http.proto) +- [httpbody.proto](https://github.com/googleapis/googleapis/raw/refs/heads/master/google/api/httpbody.proto) diff --git a/proto/google/api/annotations.proto b/proto/google/api/annotations.proto new file mode 100644 index 0000000..417edd8 --- /dev/null +++ b/proto/google/api/annotations.proto @@ -0,0 +1,31 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +import "google/api/http.proto"; +import "google/protobuf/descriptor.proto"; + +option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations"; +option java_multiple_files = true; +option java_outer_classname = "AnnotationsProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +extend google.protobuf.MethodOptions { + // See `HttpRule`. + HttpRule http = 72295728; +} diff --git a/proto/google/api/field_behavior.proto b/proto/google/api/field_behavior.proto new file mode 100644 index 0000000..1fdaaed --- /dev/null +++ b/proto/google/api/field_behavior.proto @@ -0,0 +1,104 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +import "google/protobuf/descriptor.proto"; + +option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations"; +option java_multiple_files = true; +option java_outer_classname = "FieldBehaviorProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +extend google.protobuf.FieldOptions { + // A designation of a specific field behavior (required, output only, etc.) + // in protobuf messages. + // + // Examples: + // + // string name = 1 [(google.api.field_behavior) = REQUIRED]; + // State state = 1 [(google.api.field_behavior) = OUTPUT_ONLY]; + // google.protobuf.Duration ttl = 1 + // [(google.api.field_behavior) = INPUT_ONLY]; + // google.protobuf.Timestamp expire_time = 1 + // [(google.api.field_behavior) = OUTPUT_ONLY, + // (google.api.field_behavior) = IMMUTABLE]; + repeated google.api.FieldBehavior field_behavior = 1052 [packed = false]; +} + +// An indicator of the behavior of a given field (for example, that a field +// is required in requests, or given as output but ignored as input). +// This **does not** change the behavior in protocol buffers itself; it only +// denotes the behavior and may affect how API tooling handles the field. +// +// Note: This enum **may** receive new values in the future. +enum FieldBehavior { + // Conventional default for enums. Do not use this. + FIELD_BEHAVIOR_UNSPECIFIED = 0; + + // Specifically denotes a field as optional. + // While all fields in protocol buffers are optional, this may be specified + // for emphasis if appropriate. + OPTIONAL = 1; + + // Denotes a field as required. + // This indicates that the field **must** be provided as part of the request, + // and failure to do so will cause an error (usually `INVALID_ARGUMENT`). + REQUIRED = 2; + + // Denotes a field as output only. + // This indicates that the field is provided in responses, but including the + // field in a request does nothing (the server *must* ignore it and + // *must not* throw an error as a result of the field's presence). + OUTPUT_ONLY = 3; + + // Denotes a field as input only. + // This indicates that the field is provided in requests, and the + // corresponding field is not included in output. + INPUT_ONLY = 4; + + // Denotes a field as immutable. + // This indicates that the field may be set once in a request to create a + // resource, but may not be changed thereafter. + IMMUTABLE = 5; + + // Denotes that a (repeated) field is an unordered list. + // This indicates that the service may provide the elements of the list + // in any arbitrary order, rather than the order the user originally + // provided. Additionally, the list's order may or may not be stable. + UNORDERED_LIST = 6; + + // Denotes that this field returns a non-empty default value if not set. + // This indicates that if the user provides the empty value in a request, + // a non-empty value will be returned. The user will not be aware of what + // non-empty value to expect. + NON_EMPTY_DEFAULT = 7; + + // Denotes that the field in a resource (a message annotated with + // google.api.resource) is used in the resource name to uniquely identify the + // resource. For AIP-compliant APIs, this should only be applied to the + // `name` field on the resource. + // + // This behavior should not be applied to references to other resources within + // the message. + // + // The identifier field of resources often have different field behavior + // depending on the request it is embedded in (e.g. for Create methods name + // is optional and unused, while for Update methods it is required). Instead + // of method-specific annotations, only `IDENTIFIER` is required. + IDENTIFIER = 8; +} diff --git a/proto/google/api/http.proto b/proto/google/api/http.proto new file mode 100644 index 0000000..57621b5 --- /dev/null +++ b/proto/google/api/http.proto @@ -0,0 +1,370 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations"; +option java_multiple_files = true; +option java_outer_classname = "HttpProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +// Defines the HTTP configuration for an API service. It contains a list of +// [HttpRule][google.api.HttpRule], each specifying the mapping of an RPC method +// to one or more HTTP REST API methods. +message Http { + // A list of HTTP configuration rules that apply to individual API methods. + // + // **NOTE:** All service configuration rules follow "last one wins" order. + repeated HttpRule rules = 1; + + // When set to true, URL path parameters will be fully URI-decoded except in + // cases of single segment matches in reserved expansion, where "%2F" will be + // left encoded. + // + // The default behavior is to not decode RFC 6570 reserved characters in multi + // segment matches. + bool fully_decode_reserved_expansion = 2; +} + +// gRPC Transcoding +// +// gRPC Transcoding is a feature for mapping between a gRPC method and one or +// more HTTP REST endpoints. It allows developers to build a single API service +// that supports both gRPC APIs and REST APIs. Many systems, including [Google +// APIs](https://github.com/googleapis/googleapis), +// [Cloud Endpoints](https://cloud.google.com/endpoints), [gRPC +// Gateway](https://github.com/grpc-ecosystem/grpc-gateway), +// and [Envoy](https://github.com/envoyproxy/envoy) proxy support this feature +// and use it for large scale production services. +// +// `HttpRule` defines the schema of the gRPC/REST mapping. The mapping specifies +// how different portions of the gRPC request message are mapped to the URL +// path, URL query parameters, and HTTP request body. It also controls how the +// gRPC response message is mapped to the HTTP response body. `HttpRule` is +// typically specified as an `google.api.http` annotation on the gRPC method. +// +// Each mapping specifies a URL path template and an HTTP method. The path +// template may refer to one or more fields in the gRPC request message, as long +// as each field is a non-repeated field with a primitive (non-message) type. +// The path template controls how fields of the request message are mapped to +// the URL path. +// +// Example: +// +// service Messaging { +// rpc GetMessage(GetMessageRequest) returns (Message) { +// option (google.api.http) = { +// get: "/v1/{name=messages/*}" +// }; +// } +// } +// message GetMessageRequest { +// string name = 1; // Mapped to URL path. +// } +// message Message { +// string text = 1; // The resource content. +// } +// +// This enables an HTTP REST to gRPC mapping as below: +// +// - HTTP: `GET /v1/messages/123456` +// - gRPC: `GetMessage(name: "messages/123456")` +// +// Any fields in the request message which are not bound by the path template +// automatically become HTTP query parameters if there is no HTTP request body. +// For example: +// +// service Messaging { +// rpc GetMessage(GetMessageRequest) returns (Message) { +// option (google.api.http) = { +// get:"/v1/messages/{message_id}" +// }; +// } +// } +// message GetMessageRequest { +// message SubMessage { +// string subfield = 1; +// } +// string message_id = 1; // Mapped to URL path. +// int64 revision = 2; // Mapped to URL query parameter `revision`. +// SubMessage sub = 3; // Mapped to URL query parameter `sub.subfield`. +// } +// +// This enables a HTTP JSON to RPC mapping as below: +// +// - HTTP: `GET /v1/messages/123456?revision=2&sub.subfield=foo` +// - gRPC: `GetMessage(message_id: "123456" revision: 2 sub: +// SubMessage(subfield: "foo"))` +// +// Note that fields which are mapped to URL query parameters must have a +// primitive type or a repeated primitive type or a non-repeated message type. +// In the case of a repeated type, the parameter can be repeated in the URL +// as `...?param=A¶m=B`. In the case of a message type, each field of the +// message is mapped to a separate parameter, such as +// `...?foo.a=A&foo.b=B&foo.c=C`. +// +// For HTTP methods that allow a request body, the `body` field +// specifies the mapping. Consider a REST update method on the +// message resource collection: +// +// service Messaging { +// rpc UpdateMessage(UpdateMessageRequest) returns (Message) { +// option (google.api.http) = { +// patch: "/v1/messages/{message_id}" +// body: "message" +// }; +// } +// } +// message UpdateMessageRequest { +// string message_id = 1; // mapped to the URL +// Message message = 2; // mapped to the body +// } +// +// The following HTTP JSON to RPC mapping is enabled, where the +// representation of the JSON in the request body is determined by +// protos JSON encoding: +// +// - HTTP: `PATCH /v1/messages/123456 { "text": "Hi!" }` +// - gRPC: `UpdateMessage(message_id: "123456" message { text: "Hi!" })` +// +// The special name `*` can be used in the body mapping to define that +// every field not bound by the path template should be mapped to the +// request body. This enables the following alternative definition of +// the update method: +// +// service Messaging { +// rpc UpdateMessage(Message) returns (Message) { +// option (google.api.http) = { +// patch: "/v1/messages/{message_id}" +// body: "*" +// }; +// } +// } +// message Message { +// string message_id = 1; +// string text = 2; +// } +// +// +// The following HTTP JSON to RPC mapping is enabled: +// +// - HTTP: `PATCH /v1/messages/123456 { "text": "Hi!" }` +// - gRPC: `UpdateMessage(message_id: "123456" text: "Hi!")` +// +// Note that when using `*` in the body mapping, it is not possible to +// have HTTP parameters, as all fields not bound by the path end in +// the body. This makes this option more rarely used in practice when +// defining REST APIs. The common usage of `*` is in custom methods +// which don't use the URL at all for transferring data. +// +// It is possible to define multiple HTTP methods for one RPC by using +// the `additional_bindings` option. Example: +// +// service Messaging { +// rpc GetMessage(GetMessageRequest) returns (Message) { +// option (google.api.http) = { +// get: "/v1/messages/{message_id}" +// additional_bindings { +// get: "/v1/users/{user_id}/messages/{message_id}" +// } +// }; +// } +// } +// message GetMessageRequest { +// string message_id = 1; +// string user_id = 2; +// } +// +// This enables the following two alternative HTTP JSON to RPC mappings: +// +// - HTTP: `GET /v1/messages/123456` +// - gRPC: `GetMessage(message_id: "123456")` +// +// - HTTP: `GET /v1/users/me/messages/123456` +// - gRPC: `GetMessage(user_id: "me" message_id: "123456")` +// +// Rules for HTTP mapping +// +// 1. Leaf request fields (recursive expansion nested messages in the request +// message) are classified into three categories: +// - Fields referred by the path template. They are passed via the URL path. +// - Fields referred by the [HttpRule.body][google.api.HttpRule.body]. They +// are passed via the HTTP +// request body. +// - All other fields are passed via the URL query parameters, and the +// parameter name is the field path in the request message. A repeated +// field can be represented as multiple query parameters under the same +// name. +// 2. If [HttpRule.body][google.api.HttpRule.body] is "*", there is no URL +// query parameter, all fields +// are passed via URL path and HTTP request body. +// 3. If [HttpRule.body][google.api.HttpRule.body] is omitted, there is no HTTP +// request body, all +// fields are passed via URL path and URL query parameters. +// +// Path template syntax +// +// Template = "/" Segments [ Verb ] ; +// Segments = Segment { "/" Segment } ; +// Segment = "*" | "**" | LITERAL | Variable ; +// Variable = "{" FieldPath [ "=" Segments ] "}" ; +// FieldPath = IDENT { "." IDENT } ; +// Verb = ":" LITERAL ; +// +// The syntax `*` matches a single URL path segment. The syntax `**` matches +// zero or more URL path segments, which must be the last part of the URL path +// except the `Verb`. +// +// The syntax `Variable` matches part of the URL path as specified by its +// template. A variable template must not contain other variables. If a variable +// matches a single path segment, its template may be omitted, e.g. `{var}` +// is equivalent to `{var=*}`. +// +// The syntax `LITERAL` matches literal text in the URL path. If the `LITERAL` +// contains any reserved character, such characters should be percent-encoded +// before the matching. +// +// If a variable contains exactly one path segment, such as `"{var}"` or +// `"{var=*}"`, when such a variable is expanded into a URL path on the client +// side, all characters except `[-_.~0-9a-zA-Z]` are percent-encoded. The +// server side does the reverse decoding. Such variables show up in the +// [Discovery +// Document](https://developers.google.com/discovery/v1/reference/apis) as +// `{var}`. +// +// If a variable contains multiple path segments, such as `"{var=foo/*}"` +// or `"{var=**}"`, when such a variable is expanded into a URL path on the +// client side, all characters except `[-_.~/0-9a-zA-Z]` are percent-encoded. +// The server side does the reverse decoding, except "%2F" and "%2f" are left +// unchanged. Such variables show up in the +// [Discovery +// Document](https://developers.google.com/discovery/v1/reference/apis) as +// `{+var}`. +// +// Using gRPC API Service Configuration +// +// gRPC API Service Configuration (service config) is a configuration language +// for configuring a gRPC service to become a user-facing product. The +// service config is simply the YAML representation of the `google.api.Service` +// proto message. +// +// As an alternative to annotating your proto file, you can configure gRPC +// transcoding in your service config YAML files. You do this by specifying a +// `HttpRule` that maps the gRPC method to a REST endpoint, achieving the same +// effect as the proto annotation. This can be particularly useful if you +// have a proto that is reused in multiple services. Note that any transcoding +// specified in the service config will override any matching transcoding +// configuration in the proto. +// +// The following example selects a gRPC method and applies an `HttpRule` to it: +// +// http: +// rules: +// - selector: example.v1.Messaging.GetMessage +// get: /v1/messages/{message_id}/{sub.subfield} +// +// Special notes +// +// When gRPC Transcoding is used to map a gRPC to JSON REST endpoints, the +// proto to JSON conversion must follow the [proto3 +// specification](https://developers.google.com/protocol-buffers/docs/proto3#json). +// +// While the single segment variable follows the semantics of +// [RFC 6570](https://tools.ietf.org/html/rfc6570) Section 3.2.2 Simple String +// Expansion, the multi segment variable **does not** follow RFC 6570 Section +// 3.2.3 Reserved Expansion. The reason is that the Reserved Expansion +// does not expand special characters like `?` and `#`, which would lead +// to invalid URLs. As the result, gRPC Transcoding uses a custom encoding +// for multi segment variables. +// +// The path variables **must not** refer to any repeated or mapped field, +// because client libraries are not capable of handling such variable expansion. +// +// The path variables **must not** capture the leading "/" character. The reason +// is that the most common use case "{var}" does not capture the leading "/" +// character. For consistency, all path variables must share the same behavior. +// +// Repeated message fields must not be mapped to URL query parameters, because +// no client library can support such complicated mapping. +// +// If an API needs to use a JSON array for request or response body, it can map +// the request or response body to a repeated field. However, some gRPC +// Transcoding implementations may not support this feature. +message HttpRule { + // Selects a method to which this rule applies. + // + // Refer to [selector][google.api.DocumentationRule.selector] for syntax + // details. + string selector = 1; + + // Determines the URL pattern is matched by this rules. This pattern can be + // used with any of the {get|put|post|delete|patch} methods. A custom method + // can be defined using the 'custom' field. + oneof pattern { + // Maps to HTTP GET. Used for listing and getting information about + // resources. + string get = 2; + + // Maps to HTTP PUT. Used for replacing a resource. + string put = 3; + + // Maps to HTTP POST. Used for creating a resource or performing an action. + string post = 4; + + // Maps to HTTP DELETE. Used for deleting a resource. + string delete = 5; + + // Maps to HTTP PATCH. Used for updating a resource. + string patch = 6; + + // The custom pattern is used for specifying an HTTP method that is not + // included in the `pattern` field, such as HEAD, or "*" to leave the + // HTTP method unspecified for this rule. The wild-card rule is useful + // for services that provide content to Web (HTML) clients. + CustomHttpPattern custom = 8; + } + + // The name of the request field whose value is mapped to the HTTP request + // body, or `*` for mapping all request fields not captured by the path + // pattern to the HTTP body, or omitted for not having any HTTP request body. + // + // NOTE: the referred field must be present at the top-level of the request + // message type. + string body = 7; + + // Optional. The name of the response field whose value is mapped to the HTTP + // response body. When omitted, the entire response message will be used + // as the HTTP response body. + // + // NOTE: The referred field must be present at the top-level of the response + // message type. + string response_body = 12; + + // Additional HTTP bindings for the selector. Nested bindings must + // not contain an `additional_bindings` field themselves (that is, + // the nesting may only be one level deep). + repeated HttpRule additional_bindings = 11; +} + +// A custom pattern is used for defining custom HTTP verb. +message CustomHttpPattern { + // The name of this custom HTTP verb. + string kind = 1; + + // The path matched by this custom verb. + string path = 2; +} diff --git a/proto/google/api/httpbody.proto b/proto/google/api/httpbody.proto new file mode 100644 index 0000000..e3e17c8 --- /dev/null +++ b/proto/google/api/httpbody.proto @@ -0,0 +1,80 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +import "google/protobuf/any.proto"; + +option go_package = "google.golang.org/genproto/googleapis/api/httpbody;httpbody"; +option java_multiple_files = true; +option java_outer_classname = "HttpBodyProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +// Message that represents an arbitrary HTTP body. It should only be used for +// payload formats that can't be represented as JSON, such as raw binary or +// an HTML page. +// +// +// This message can be used both in streaming and non-streaming API methods in +// the request as well as the response. +// +// It can be used as a top-level request field, which is convenient if one +// wants to extract parameters from either the URL or HTTP template into the +// request fields and also want access to the raw HTTP body. +// +// Example: +// +// message GetResourceRequest { +// // A unique request id. +// string request_id = 1; +// +// // The raw HTTP body is bound to this field. +// google.api.HttpBody http_body = 2; +// +// } +// +// service ResourceService { +// rpc GetResource(GetResourceRequest) +// returns (google.api.HttpBody); +// rpc UpdateResource(google.api.HttpBody) +// returns (google.protobuf.Empty); +// +// } +// +// Example with streaming methods: +// +// service CaldavService { +// rpc GetCalendar(stream google.api.HttpBody) +// returns (stream google.api.HttpBody); +// rpc UpdateCalendar(stream google.api.HttpBody) +// returns (stream google.api.HttpBody); +// +// } +// +// Use of this type only changes how the request and response bodies are +// handled, all other features will continue to work unchanged. +message HttpBody { + // The HTTP Content-Type header value specifying the content type of the body. + string content_type = 1; + + // The HTTP request/response body as raw binary. + bytes data = 2; + + // Application specific response metadata. Must be set in the first response + // for streaming APIs. + repeated google.protobuf.Any extensions = 3; +}