diff --git a/chat-service/internal/server/server.go b/chat-service/internal/server/server.go index e147e7d..5bfa78c 100644 --- a/chat-service/internal/server/server.go +++ b/chat-service/internal/server/server.go @@ -1,6 +1,7 @@ package server import ( + "context" "fmt" "net" @@ -40,3 +41,11 @@ func (s *Server) Server() error { return nil } + +func (s *Server) Connect(stream pb.ChatService_ConnectServer) error { + return s.service.Connect(stream) +} + +func (s *Server) CreateChat(ctx context.Context, req *pb.CreateChatRequest) (*pb.CreateChatResponse, error) { + return s.service.CreateChat(ctx, req) +} diff --git a/gen/go/v1/chatroom.pb.go b/gen/go/v1/chatroom/chatroom.pb.go similarity index 70% rename from gen/go/v1/chatroom.pb.go rename to gen/go/v1/chatroom/chatroom.pb.go index 0c44bfd..7877da7 100644 --- a/gen/go/v1/chatroom.pb.go +++ b/gen/go/v1/chatroom/chatroom.pb.go @@ -2,11 +2,12 @@ // versions: // protoc-gen-go v1.36.10 // protoc v6.32.1 -// source: chatroom.proto +// source: chatroom/chatroom.proto -package gen +package chatroom import ( + _ "google.golang.org/genproto/googleapis/api/annotations" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" @@ -61,11 +62,11 @@ func (x MessageType) String() string { } func (MessageType) Descriptor() protoreflect.EnumDescriptor { - return file_chatroom_proto_enumTypes[0].Descriptor() + return file_chatroom_chatroom_proto_enumTypes[0].Descriptor() } func (MessageType) Type() protoreflect.EnumType { - return &file_chatroom_proto_enumTypes[0] + return &file_chatroom_chatroom_proto_enumTypes[0] } func (x MessageType) Number() protoreflect.EnumNumber { @@ -74,14 +75,14 @@ func (x MessageType) Number() protoreflect.EnumNumber { // Deprecated: Use MessageType.Descriptor instead. func (MessageType) EnumDescriptor() ([]byte, []int) { - return file_chatroom_proto_rawDescGZIP(), []int{0} + return file_chatroom_chatroom_proto_rawDescGZIP(), []int{0} } // Сообщение чата type ChatMessage struct { state protoimpl.MessageState `protogen:"open.v1"` Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - Type MessageType `protobuf:"varint,2,opt,name=type,proto3,enum=v1.MessageType" json:"type,omitempty"` + Type MessageType `protobuf:"varint,2,opt,name=type,proto3,enum=chatroom.MessageType" json:"type,omitempty"` RoomId string `protobuf:"bytes,3,opt,name=room_id,json=roomId,proto3" json:"room_id,omitempty"` UserId string `protobuf:"bytes,4,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"` Username string `protobuf:"bytes,5,opt,name=username,proto3" json:"username,omitempty"` @@ -93,7 +94,7 @@ type ChatMessage struct { func (x *ChatMessage) Reset() { *x = ChatMessage{} - mi := &file_chatroom_proto_msgTypes[0] + mi := &file_chatroom_chatroom_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -105,7 +106,7 @@ func (x *ChatMessage) String() string { func (*ChatMessage) ProtoMessage() {} func (x *ChatMessage) ProtoReflect() protoreflect.Message { - mi := &file_chatroom_proto_msgTypes[0] + mi := &file_chatroom_chatroom_proto_msgTypes[0] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -118,7 +119,7 @@ func (x *ChatMessage) ProtoReflect() protoreflect.Message { // Deprecated: Use ChatMessage.ProtoReflect.Descriptor instead. func (*ChatMessage) Descriptor() ([]byte, []int) { - return file_chatroom_proto_rawDescGZIP(), []int{0} + return file_chatroom_chatroom_proto_rawDescGZIP(), []int{0} } func (x *ChatMessage) GetId() string { @@ -183,7 +184,7 @@ type CreateChatRequest struct { func (x *CreateChatRequest) Reset() { *x = CreateChatRequest{} - mi := &file_chatroom_proto_msgTypes[1] + mi := &file_chatroom_chatroom_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -195,7 +196,7 @@ func (x *CreateChatRequest) String() string { func (*CreateChatRequest) ProtoMessage() {} func (x *CreateChatRequest) ProtoReflect() protoreflect.Message { - mi := &file_chatroom_proto_msgTypes[1] + mi := &file_chatroom_chatroom_proto_msgTypes[1] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -208,7 +209,7 @@ func (x *CreateChatRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use CreateChatRequest.ProtoReflect.Descriptor instead. func (*CreateChatRequest) Descriptor() ([]byte, []int) { - return file_chatroom_proto_rawDescGZIP(), []int{1} + return file_chatroom_chatroom_proto_rawDescGZIP(), []int{1} } func (x *CreateChatRequest) GetRoomId() string { @@ -249,7 +250,7 @@ type CreateChatResponse struct { func (x *CreateChatResponse) Reset() { *x = CreateChatResponse{} - mi := &file_chatroom_proto_msgTypes[2] + mi := &file_chatroom_chatroom_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -261,7 +262,7 @@ func (x *CreateChatResponse) String() string { func (*CreateChatResponse) ProtoMessage() {} func (x *CreateChatResponse) ProtoReflect() protoreflect.Message { - mi := &file_chatroom_proto_msgTypes[2] + mi := &file_chatroom_chatroom_proto_msgTypes[2] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -274,7 +275,7 @@ func (x *CreateChatResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use CreateChatResponse.ProtoReflect.Descriptor instead. func (*CreateChatResponse) Descriptor() ([]byte, []int) { - return file_chatroom_proto_rawDescGZIP(), []int{2} + return file_chatroom_chatroom_proto_rawDescGZIP(), []int{2} } func (x *CreateChatResponse) GetRoomId() string { @@ -302,7 +303,7 @@ type MessageHistoryRequest struct { func (x *MessageHistoryRequest) Reset() { *x = MessageHistoryRequest{} - mi := &file_chatroom_proto_msgTypes[3] + mi := &file_chatroom_chatroom_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -314,7 +315,7 @@ func (x *MessageHistoryRequest) String() string { func (*MessageHistoryRequest) ProtoMessage() {} func (x *MessageHistoryRequest) ProtoReflect() protoreflect.Message { - mi := &file_chatroom_proto_msgTypes[3] + mi := &file_chatroom_chatroom_proto_msgTypes[3] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -327,7 +328,7 @@ func (x *MessageHistoryRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use MessageHistoryRequest.ProtoReflect.Descriptor instead. func (*MessageHistoryRequest) Descriptor() ([]byte, []int) { - return file_chatroom_proto_rawDescGZIP(), []int{3} + return file_chatroom_chatroom_proto_rawDescGZIP(), []int{3} } func (x *MessageHistoryRequest) GetRoomId() string { @@ -353,7 +354,7 @@ type MessageHistoryResponse struct { func (x *MessageHistoryResponse) Reset() { *x = MessageHistoryResponse{} - mi := &file_chatroom_proto_msgTypes[4] + mi := &file_chatroom_chatroom_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -365,7 +366,7 @@ func (x *MessageHistoryResponse) String() string { func (*MessageHistoryResponse) ProtoMessage() {} func (x *MessageHistoryResponse) ProtoReflect() protoreflect.Message { - mi := &file_chatroom_proto_msgTypes[4] + mi := &file_chatroom_chatroom_proto_msgTypes[4] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -378,7 +379,7 @@ func (x *MessageHistoryResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use MessageHistoryResponse.ProtoReflect.Descriptor instead. func (*MessageHistoryResponse) Descriptor() ([]byte, []int) { - return file_chatroom_proto_rawDescGZIP(), []int{4} + return file_chatroom_chatroom_proto_rawDescGZIP(), []int{4} } func (x *MessageHistoryResponse) GetMessages() []*ChatMessage { @@ -388,14 +389,14 @@ func (x *MessageHistoryResponse) GetMessages() []*ChatMessage { return nil } -var File_chatroom_proto protoreflect.FileDescriptor +var File_chatroom_chatroom_proto protoreflect.FileDescriptor -const file_chatroom_proto_rawDesc = "" + +const file_chatroom_chatroom_proto_rawDesc = "" + "\n" + - "\x0echatroom.proto\x12\x02v1\"\xc8\x01\n" + + "\x17chatroom/chatroom.proto\x12\bchatroom\x1a\x1cgoogle/api/annotations.proto\"\xce\x01\n" + "\vChatMessage\x12\x0e\n" + - "\x02id\x18\x01 \x01(\tR\x02id\x12#\n" + - "\x04type\x18\x02 \x01(\x0e2\x0f.v1.MessageTypeR\x04type\x12\x17\n" + + "\x02id\x18\x01 \x01(\tR\x02id\x12)\n" + + "\x04type\x18\x02 \x01(\x0e2\x15.chatroom.MessageTypeR\x04type\x12\x17\n" + "\aroom_id\x18\x03 \x01(\tR\x06roomId\x12\x17\n" + "\auser_id\x18\x04 \x01(\tR\x06userId\x12\x1a\n" + "\busername\x18\x05 \x01(\tR\busername\x12\x18\n" + @@ -411,52 +412,52 @@ const file_chatroom_proto_rawDesc = "" + "\x04name\x18\x02 \x01(\tR\x04name\"F\n" + "\x15MessageHistoryRequest\x12\x17\n" + "\aroom_id\x18\x01 \x01(\tR\x06roomId\x12\x14\n" + - "\x05limit\x18\x02 \x01(\x05R\x05limit\"E\n" + - "\x16MessageHistoryResponse\x12+\n" + - "\bmessages\x18\x01 \x03(\v2\x0f.v1.ChatMessageR\bmessages*\\\n" + + "\x05limit\x18\x02 \x01(\x05R\x05limit\"K\n" + + "\x16MessageHistoryResponse\x121\n" + + "\bmessages\x18\x01 \x03(\v2\x15.chatroom.ChatMessageR\bmessages*\\\n" + "\vMessageType\x12\x10\n" + "\fUSER_MESSAGE\x10\x00\x12\x0f\n" + "\vUSER_JOINED\x10\x01\x12\r\n" + "\tUSER_LEFT\x10\x02\x12\x10\n" + "\fROOM_CREATED\x10\x03\x12\t\n" + - "\x05ERROR\x10\x042\xc7\x01\n" + - "\vChatService\x12/\n" + - "\aConnect\x12\x0f.v1.ChatMessage\x1a\x0f.v1.ChatMessage(\x010\x01\x12;\n" + + "\x05ERROR\x10\x042\xa5\x02\n" + + "\vChatService\x12;\n" + + "\aConnect\x12\x15.chatroom.ChatMessage\x1a\x15.chatroom.ChatMessage(\x010\x01\x12\\\n" + "\n" + - "CreateChat\x12\x15.v1.CreateChatRequest\x1a\x16.v1.CreateChatResponse\x12J\n" + - "\x11GetMessageHistory\x12\x19.v1.MessageHistoryRequest\x1a\x1a.v1.MessageHistoryResponseB\"Z github.com/Lemper29/ChatRoom/genb\x06proto3" + "CreateChat\x12\x1b.chatroom.CreateChatRequest\x1a\x1c.chatroom.CreateChatResponse\"\x13\x82\xd3\xe4\x93\x02\r:\x01*\"\b/v1/chat\x12{\n" + + "\x11GetMessageHistory\x12\x1f.chatroom.MessageHistoryRequest\x1a .chatroom.MessageHistoryResponse\"#\x82\xd3\xe4\x93\x02\x1d\x12\x1b/v1/chat/{room_id}/messagesB1Z/github.com/Lemper29/ChatRoom/gen/go/v1/chatroomb\x06proto3" var ( - file_chatroom_proto_rawDescOnce sync.Once - file_chatroom_proto_rawDescData []byte + file_chatroom_chatroom_proto_rawDescOnce sync.Once + file_chatroom_chatroom_proto_rawDescData []byte ) -func file_chatroom_proto_rawDescGZIP() []byte { - file_chatroom_proto_rawDescOnce.Do(func() { - file_chatroom_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_chatroom_proto_rawDesc), len(file_chatroom_proto_rawDesc))) +func file_chatroom_chatroom_proto_rawDescGZIP() []byte { + file_chatroom_chatroom_proto_rawDescOnce.Do(func() { + file_chatroom_chatroom_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_chatroom_chatroom_proto_rawDesc), len(file_chatroom_chatroom_proto_rawDesc))) }) - return file_chatroom_proto_rawDescData -} - -var file_chatroom_proto_enumTypes = make([]protoimpl.EnumInfo, 1) -var file_chatroom_proto_msgTypes = make([]protoimpl.MessageInfo, 5) -var file_chatroom_proto_goTypes = []any{ - (MessageType)(0), // 0: v1.MessageType - (*ChatMessage)(nil), // 1: v1.ChatMessage - (*CreateChatRequest)(nil), // 2: v1.CreateChatRequest - (*CreateChatResponse)(nil), // 3: v1.CreateChatResponse - (*MessageHistoryRequest)(nil), // 4: v1.MessageHistoryRequest - (*MessageHistoryResponse)(nil), // 5: v1.MessageHistoryResponse -} -var file_chatroom_proto_depIdxs = []int32{ - 0, // 0: v1.ChatMessage.type:type_name -> v1.MessageType - 1, // 1: v1.MessageHistoryResponse.messages:type_name -> v1.ChatMessage - 1, // 2: v1.ChatService.Connect:input_type -> v1.ChatMessage - 2, // 3: v1.ChatService.CreateChat:input_type -> v1.CreateChatRequest - 4, // 4: v1.ChatService.GetMessageHistory:input_type -> v1.MessageHistoryRequest - 1, // 5: v1.ChatService.Connect:output_type -> v1.ChatMessage - 3, // 6: v1.ChatService.CreateChat:output_type -> v1.CreateChatResponse - 5, // 7: v1.ChatService.GetMessageHistory:output_type -> v1.MessageHistoryResponse + return file_chatroom_chatroom_proto_rawDescData +} + +var file_chatroom_chatroom_proto_enumTypes = make([]protoimpl.EnumInfo, 1) +var file_chatroom_chatroom_proto_msgTypes = make([]protoimpl.MessageInfo, 5) +var file_chatroom_chatroom_proto_goTypes = []any{ + (MessageType)(0), // 0: chatroom.MessageType + (*ChatMessage)(nil), // 1: chatroom.ChatMessage + (*CreateChatRequest)(nil), // 2: chatroom.CreateChatRequest + (*CreateChatResponse)(nil), // 3: chatroom.CreateChatResponse + (*MessageHistoryRequest)(nil), // 4: chatroom.MessageHistoryRequest + (*MessageHistoryResponse)(nil), // 5: chatroom.MessageHistoryResponse +} +var file_chatroom_chatroom_proto_depIdxs = []int32{ + 0, // 0: chatroom.ChatMessage.type:type_name -> chatroom.MessageType + 1, // 1: chatroom.MessageHistoryResponse.messages:type_name -> chatroom.ChatMessage + 1, // 2: chatroom.ChatService.Connect:input_type -> chatroom.ChatMessage + 2, // 3: chatroom.ChatService.CreateChat:input_type -> chatroom.CreateChatRequest + 4, // 4: chatroom.ChatService.GetMessageHistory:input_type -> chatroom.MessageHistoryRequest + 1, // 5: chatroom.ChatService.Connect:output_type -> chatroom.ChatMessage + 3, // 6: chatroom.ChatService.CreateChat:output_type -> chatroom.CreateChatResponse + 5, // 7: chatroom.ChatService.GetMessageHistory:output_type -> chatroom.MessageHistoryResponse 5, // [5:8] is the sub-list for method output_type 2, // [2:5] is the sub-list for method input_type 2, // [2:2] is the sub-list for extension type_name @@ -464,27 +465,27 @@ var file_chatroom_proto_depIdxs = []int32{ 0, // [0:2] is the sub-list for field type_name } -func init() { file_chatroom_proto_init() } -func file_chatroom_proto_init() { - if File_chatroom_proto != nil { +func init() { file_chatroom_chatroom_proto_init() } +func file_chatroom_chatroom_proto_init() { + if File_chatroom_chatroom_proto != nil { return } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: unsafe.Slice(unsafe.StringData(file_chatroom_proto_rawDesc), len(file_chatroom_proto_rawDesc)), + RawDescriptor: unsafe.Slice(unsafe.StringData(file_chatroom_chatroom_proto_rawDesc), len(file_chatroom_chatroom_proto_rawDesc)), NumEnums: 1, NumMessages: 5, NumExtensions: 0, NumServices: 1, }, - GoTypes: file_chatroom_proto_goTypes, - DependencyIndexes: file_chatroom_proto_depIdxs, - EnumInfos: file_chatroom_proto_enumTypes, - MessageInfos: file_chatroom_proto_msgTypes, + GoTypes: file_chatroom_chatroom_proto_goTypes, + DependencyIndexes: file_chatroom_chatroom_proto_depIdxs, + EnumInfos: file_chatroom_chatroom_proto_enumTypes, + MessageInfos: file_chatroom_chatroom_proto_msgTypes, }.Build() - File_chatroom_proto = out.File - file_chatroom_proto_goTypes = nil - file_chatroom_proto_depIdxs = nil + File_chatroom_chatroom_proto = out.File + file_chatroom_chatroom_proto_goTypes = nil + file_chatroom_chatroom_proto_depIdxs = nil } diff --git a/gen/go/v1/chatroom/chatroom.pb.gw.go b/gen/go/v1/chatroom/chatroom.pb.gw.go new file mode 100644 index 0000000..b72e550 --- /dev/null +++ b/gen/go/v1/chatroom/chatroom.pb.gw.go @@ -0,0 +1,249 @@ +// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. +// source: chatroom/chatroom.proto + +/* +Package chatroom is a reverse proxy. + +It translates gRPC into RESTful JSON APIs. +*/ +package chatroom + +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 +) + +func request_ChatService_CreateChat_0(ctx context.Context, marshaler runtime.Marshaler, client ChatServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var ( + protoReq CreateChatRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if req.Body != nil { + _, _ = io.Copy(io.Discard, req.Body) + } + msg, err := client.CreateChat(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err +} + +func local_request_ChatService_CreateChat_0(ctx context.Context, marshaler runtime.Marshaler, server ChatServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var ( + protoReq CreateChatRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + msg, err := server.CreateChat(ctx, &protoReq) + return msg, metadata, err +} + +var filter_ChatService_GetMessageHistory_0 = &utilities.DoubleArray{Encoding: map[string]int{"room_id": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} + +func request_ChatService_GetMessageHistory_0(ctx context.Context, marshaler runtime.Marshaler, client ChatServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var ( + protoReq MessageHistoryRequest + metadata runtime.ServerMetadata + err error + ) + if req.Body != nil { + _, _ = io.Copy(io.Discard, req.Body) + } + val, ok := pathParams["room_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "room_id") + } + protoReq.RoomId, err = runtime.String(val) + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "room_id", err) + } + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_ChatService_GetMessageHistory_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + msg, err := client.GetMessageHistory(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err +} + +func local_request_ChatService_GetMessageHistory_0(ctx context.Context, marshaler runtime.Marshaler, server ChatServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var ( + protoReq MessageHistoryRequest + metadata runtime.ServerMetadata + err error + ) + val, ok := pathParams["room_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "room_id") + } + protoReq.RoomId, err = runtime.String(val) + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "room_id", err) + } + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_ChatService_GetMessageHistory_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + msg, err := server.GetMessageHistory(ctx, &protoReq) + return msg, metadata, err +} + +// RegisterChatServiceHandlerServer registers the http handlers for service ChatService to "mux". +// UnaryRPC :call ChatServiceServer 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 RegisterChatServiceHandlerFromEndpoint 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 RegisterChatServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux, server ChatServiceServer) error { + mux.Handle(http.MethodPost, pattern_ChatService_CreateChat_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, "/chatroom.ChatService/CreateChat", runtime.WithHTTPPathPattern("/v1/chat")) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_ChatService_CreateChat_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_ChatService_CreateChat_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + mux.Handle(http.MethodGet, pattern_ChatService_GetMessageHistory_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, "/chatroom.ChatService/GetMessageHistory", runtime.WithHTTPPathPattern("/v1/chat/{room_id}/messages")) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_ChatService_GetMessageHistory_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_ChatService_GetMessageHistory_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + + return nil +} + +// RegisterChatServiceHandlerFromEndpoint is same as RegisterChatServiceHandler but +// automatically dials to "endpoint" and closes the connection when "ctx" gets done. +func RegisterChatServiceHandlerFromEndpoint(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 RegisterChatServiceHandler(ctx, mux, conn) +} + +// RegisterChatServiceHandler registers the http handlers for service ChatService to "mux". +// The handlers forward requests to the grpc endpoint over "conn". +func RegisterChatServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { + return RegisterChatServiceHandlerClient(ctx, mux, NewChatServiceClient(conn)) +} + +// RegisterChatServiceHandlerClient registers the http handlers for service ChatService +// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "ChatServiceClient". +// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "ChatServiceClient" +// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in +// "ChatServiceClient" to call the correct interceptors. This client ignores the HTTP middlewares. +func RegisterChatServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client ChatServiceClient) error { + mux.Handle(http.MethodPost, pattern_ChatService_CreateChat_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, "/chatroom.ChatService/CreateChat", runtime.WithHTTPPathPattern("/v1/chat")) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_ChatService_CreateChat_0(annotatedContext, inboundMarshaler, client, req, pathParams) + annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) + if err != nil { + runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) + return + } + forward_ChatService_CreateChat_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + mux.Handle(http.MethodGet, pattern_ChatService_GetMessageHistory_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, "/chatroom.ChatService/GetMessageHistory", runtime.WithHTTPPathPattern("/v1/chat/{room_id}/messages")) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_ChatService_GetMessageHistory_0(annotatedContext, inboundMarshaler, client, req, pathParams) + annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) + if err != nil { + runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) + return + } + forward_ChatService_GetMessageHistory_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + return nil +} + +var ( + pattern_ChatService_CreateChat_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "chat"}, "")) + pattern_ChatService_GetMessageHistory_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3}, []string{"v1", "chat", "room_id", "messages"}, "")) +) + +var ( + forward_ChatService_CreateChat_0 = runtime.ForwardResponseMessage + forward_ChatService_GetMessageHistory_0 = runtime.ForwardResponseMessage +) diff --git a/gen/go/v1/chatroom_grpc.pb.go b/gen/go/v1/chatroom/chatroom_grpc.pb.go similarity index 95% rename from gen/go/v1/chatroom_grpc.pb.go rename to gen/go/v1/chatroom/chatroom_grpc.pb.go index fe57392..77c319c 100644 --- a/gen/go/v1/chatroom_grpc.pb.go +++ b/gen/go/v1/chatroom/chatroom_grpc.pb.go @@ -2,9 +2,9 @@ // versions: // - protoc-gen-go-grpc v1.5.1 // - protoc v6.32.1 -// source: chatroom.proto +// source: chatroom/chatroom.proto -package gen +package chatroom import ( context "context" @@ -19,9 +19,9 @@ import ( const _ = grpc.SupportPackageIsVersion9 const ( - ChatService_Connect_FullMethodName = "/v1.ChatService/Connect" - ChatService_CreateChat_FullMethodName = "/v1.ChatService/CreateChat" - ChatService_GetMessageHistory_FullMethodName = "/v1.ChatService/GetMessageHistory" + ChatService_Connect_FullMethodName = "/chatroom.ChatService/Connect" + ChatService_CreateChat_FullMethodName = "/chatroom.ChatService/CreateChat" + ChatService_GetMessageHistory_FullMethodName = "/chatroom.ChatService/GetMessageHistory" ) // ChatServiceClient is the client API for ChatService service. @@ -34,7 +34,7 @@ type ChatServiceClient interface { Connect(ctx context.Context, opts ...grpc.CallOption) (grpc.BidiStreamingClient[ChatMessage, ChatMessage], error) // Unary RPC для создания чатов CreateChat(ctx context.Context, in *CreateChatRequest, opts ...grpc.CallOption) (*CreateChatResponse, error) - // Unary RPC для получения истории сообщений (опционально) + // Unary RPC для получения истории сообщений GetMessageHistory(ctx context.Context, in *MessageHistoryRequest, opts ...grpc.CallOption) (*MessageHistoryResponse, error) } @@ -89,7 +89,7 @@ type ChatServiceServer interface { Connect(grpc.BidiStreamingServer[ChatMessage, ChatMessage]) error // Unary RPC для создания чатов CreateChat(context.Context, *CreateChatRequest) (*CreateChatResponse, error) - // Unary RPC для получения истории сообщений (опционально) + // Unary RPC для получения истории сообщений GetMessageHistory(context.Context, *MessageHistoryRequest) (*MessageHistoryResponse, error) mustEmbedUnimplementedChatServiceServer() } @@ -178,7 +178,7 @@ func _ChatService_GetMessageHistory_Handler(srv interface{}, ctx context.Context // It's only intended for direct use with grpc.RegisterService, // and not to be introspected or modified (even as a copy) var ChatService_ServiceDesc = grpc.ServiceDesc{ - ServiceName: "v1.ChatService", + ServiceName: "chatroom.ChatService", HandlerType: (*ChatServiceServer)(nil), Methods: []grpc.MethodDesc{ { @@ -198,5 +198,5 @@ var ChatService_ServiceDesc = grpc.ServiceDesc{ ClientStreams: true, }, }, - Metadata: "chatroom.proto", + Metadata: "chatroom/chatroom.proto", } diff --git a/go.mod b/go.mod index 3a78b6e..1f4f668 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,8 @@ module github.com/Lemper29/ChatRoom go 1.25.1 require ( + github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 + google.golang.org/genproto/googleapis/api v0.0.0-20250929231259-57b25ae835d4 google.golang.org/grpc v1.75.1 google.golang.org/protobuf v1.36.10 ) @@ -10,6 +12,6 @@ require ( require ( golang.org/x/net v0.41.0 // indirect golang.org/x/sys v0.33.0 // indirect - golang.org/x/text v0.26.0 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20250707201910-8d1bb00bc6a7 // indirect + golang.org/x/text v0.29.0 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20250929231259-57b25ae835d4 // indirect ) diff --git a/go.sum b/go.sum index 436fd86..65a8f2f 100644 --- a/go.sum +++ b/go.sum @@ -8,6 +8,8 @@ github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 h1:NmZ1PKzSTQbuGHw9DGPFomqkkLWMC+vZCkfs+FHv1Vg= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3/go.mod h1:zQrxl1YP88HQlA6i9c63DSVPFklWpGX4OWAc9bFuaH4= go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= go.opentelemetry.io/otel v1.37.0 h1:9zhNfelUvx0KBfu/gb+ZgeAfAgtWrfHJZcAqFC228wQ= @@ -24,12 +26,14 @@ golang.org/x/net v0.41.0 h1:vBTly1HeNPEn3wtREYfy4GZ/NECgw2Cnl+nK6Nz3uvw= golang.org/x/net v0.41.0/go.mod h1:B/K4NNqkfmg07DQYrbwvSluqCJOOXwUjeb/5lOisjbA= golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw= golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= -golang.org/x/text v0.26.0 h1:P42AVeLghgTYr4+xUnTRKDMqpar+PtX7KWuNQL21L8M= -golang.org/x/text v0.26.0/go.mod h1:QK15LZJUUQVJxhz7wXgxSy/CJaTFjd0G+YLonydOVQA= +golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk= +golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4= gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk= gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250707201910-8d1bb00bc6a7 h1:pFyd6EwwL2TqFf8emdthzeX+gZE1ElRq3iM8pui4KBY= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250707201910-8d1bb00bc6a7/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A= +google.golang.org/genproto/googleapis/api v0.0.0-20250929231259-57b25ae835d4 h1:8XJ4pajGwOlasW+L13MnEGA8W4115jJySQtVfS2/IBU= +google.golang.org/genproto/googleapis/api v0.0.0-20250929231259-57b25ae835d4/go.mod h1:NnuHhy+bxcg30o7FnVAZbXsPHUDQ9qKWAQKCD7VxFtk= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250929231259-57b25ae835d4 h1:i8QOKZfYg6AbGVZzUAY3LrNWCKF8O6zFisU9Wl9RER4= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250929231259-57b25ae835d4/go.mod h1:HSkG/KdJWusxU1F6CNrwNDjBMgisKxGnc5dAZfT0mjQ= google.golang.org/grpc v1.75.1 h1:/ODCNEuf9VghjgO3rqLcfg8fiOP0nSluljWFlDxELLI= google.golang.org/grpc v1.75.1/go.mod h1:JtPAzKiq4v1xcAB2hydNlWI2RnF85XXcV0mhKXr2ecQ= google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= diff --git a/proto/chatroom.proto b/proto/chatroom/chatroom.proto similarity index 78% rename from proto/chatroom.proto rename to proto/chatroom/chatroom.proto index 85630d6..0069ac2 100644 --- a/proto/chatroom.proto +++ b/proto/chatroom/chatroom.proto @@ -1,8 +1,10 @@ syntax = "proto3"; -package v1; +package chatroom; -option go_package = "github.com/Lemper29/ChatRoom/gen"; +import "google/api/annotations.proto"; + +option go_package = "github.com/Lemper29/ChatRoom/gen/go/v1/chatroom"; // Типы сообщений enum MessageType { @@ -37,18 +39,6 @@ message CreateChatResponse { string name = 2; } -// Сервис -service ChatService { - // Stream RPC для connect - rpc Connect(stream ChatMessage) returns (stream ChatMessage); - - // Unary RPC для создания чатов - rpc CreateChat(CreateChatRequest) returns (CreateChatResponse); - - // Unary RPC для получения истории сообщений (опционально) - rpc GetMessageHistory(MessageHistoryRequest) returns (MessageHistoryResponse); -} - // Опционально: для получения истории сообщений message MessageHistoryRequest { string room_id = 1; @@ -57,4 +47,25 @@ message MessageHistoryRequest { message MessageHistoryResponse { repeated ChatMessage messages = 1; +} + +// Сервис +service ChatService { + // Stream RPC для connect + rpc Connect(stream ChatMessage) returns (stream ChatMessage); + + // Unary RPC для создания чатов + rpc CreateChat(CreateChatRequest) returns (CreateChatResponse) { + option (google.api.http) = { + post: "/v1/chat" + body: "*" + }; + } + + // Unary RPC для получения истории сообщений + rpc GetMessageHistory(MessageHistoryRequest) returns (MessageHistoryResponse) { + option (google.api.http) = { + get: "/v1/chat/{room_id}/messages" + }; + } } \ No newline at end of file diff --git a/proto/google/api/annotations.proto b/proto/google/api/annotations.proto new file mode 100644 index 0000000..bcf9546 --- /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; +} \ No newline at end of file diff --git a/proto/google/api/http.proto b/proto/google/api/http.proto new file mode 100644 index 0000000..366f5bc --- /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; +} \ No newline at end of file