add generate server and swagger

This commit is contained in:
Владимир Фёдоров 2024-05-18 05:34:55 +07:00
parent 5bba5821ab
commit 286048d068
11 changed files with 1220 additions and 15 deletions

10
Makefile Normal file
View File

@ -0,0 +1,10 @@
generate:
rm -rf proto
mkdir -p proto
protoc -I ./api \
--go_out ./proto --go_opt paths=source_relative \
--go-grpc_out ./proto --go-grpc_opt paths=source_relative \
--grpc-gateway_out ./proto --grpc-gateway_opt paths=source_relative \
--swagger_out=allow_merge=true,merge_file_name=main:./proto \
./api/main.proto

View File

@ -0,0 +1,31 @@
// Copyright 2024 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;
}

379
api/google/api/http.proto Normal file
View File

@ -0,0 +1,379 @@
// Copyright 2024 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 cc_enable_arenas = true;
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 | gRPC
// -----|-----
// `GET /v1/messages/123456` | `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 | gRPC
// -----|-----
// `GET /v1/messages/123456?revision=2&sub.subfield=foo` |
// `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&param=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 | gRPC
// -----|-----
// `PATCH /v1/messages/123456 { "text": "Hi!" }` | `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 | gRPC
// -----|-----
// `PATCH /v1/messages/123456 { "text": "Hi!" }` | `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 | gRPC
// -----|-----
// `GET /v1/messages/123456` | `GetMessage(message_id: "123456")`
// `GET /v1/users/me/messages/123456` | `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.
//
// Example:
//
// http:
// rules:
// # Selects a gRPC method and applies HttpRule to it.
// - 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;
}

28
api/main.proto Normal file
View File

@ -0,0 +1,28 @@
syntax = "proto3";
package crabs.crm;
import "google/api/annotations.proto";
option go_package = "pkg/crm";
service CRM {
rpc GetCatalog(GetCatalogReq) returns (CatalogRsp) {
option (google.api.http) = {
get: "/catalog"
};
}
}
message GetCatalogReq {}
message CatalogRsp {
message Category {
int64 id = 1;
string name = 2;
string uri = 3;
repeated Category children = 4;
}
repeated Category categories = 1;
}

View File

@ -1,21 +1,79 @@
package main
import (
"cake_crm/internal/models/storage/storage_file"
"cake_crm/internal/services/server_web"
crm "cake_crm/proto"
"context"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"log"
"net"
"net/http"
)
type server struct {
crm.UnimplementedCRMServer
}
func NewServer() *server {
return &server{}
}
func (s *server) GetCatalog(ctx context.Context, req *crm.GetCatalogReq) (*crm.CatalogRsp, error) {
return nil, nil
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
//ctx, cancel := context.WithCancel(context.Background())
//defer cancel()
//
//storage := storage_file.NewStorageFile("resources/db.json")
//_ = storage
//
//server := server_web.NewServer(storage, 8080)
//err := server.Run(ctx)
//if err != nil {
// panic(err)
//}
storage := storage_file.NewStorageFile("resources/db.json")
_ = storage
server := server_web.NewServer(storage, 8080)
err := server.Run(ctx)
// Create a listener on TCP port
lis, err := net.Listen("tcp", ":8080")
if err != nil {
panic(err)
log.Fatalln("Failed to listen:", err)
}
// Create a gRPC server object
s := grpc.NewServer()
// Attach the Greeter service to the server
crm.RegisterCRMServer(s, &server{})
// Serve gRPC server
log.Println("Serving gRPC on 0.0.0.0:8080")
go func() {
log.Fatalln(s.Serve(lis))
}()
// Create a client connection to the gRPC server we just started
// This is where the gRPC-Gateway proxies the requests
conn, err := grpc.NewClient(
"0.0.0.0:8080",
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
if err != nil {
log.Fatalln("Failed to dial server:", err)
}
gwmux := runtime.NewServeMux()
// Register Greeter
err = crm.RegisterCRMHandler(context.Background(), gwmux, conn)
if err != nil {
log.Fatalln("Failed to register gateway:", err)
}
gwServer := &http.Server{
Addr: ":8090",
Handler: gwmux,
}
log.Println("Serving gRPC-Gateway on http://0.0.0.0:8090")
log.Fatalln(gwServer.ListenAndServe())
}

15
go.mod
View File

@ -2,4 +2,17 @@ module cake_crm
go 1.22
require github.com/go-pkgz/routegroup v1.1.1 // indirect
require (
github.com/go-pkgz/routegroup v1.1.1
github.com/grpc-ecosystem/grpc-gateway/v2 v2.20.0
google.golang.org/genproto/googleapis/api v0.0.0-20240513163218-0867130af1f8
google.golang.org/grpc v1.64.0
google.golang.org/protobuf v1.34.1
)
require (
golang.org/x/net v0.23.0 // indirect
golang.org/x/sys v0.18.0 // indirect
golang.org/x/text v0.15.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240513163218-0867130af1f8 // indirect
)

18
go.sum
View File

@ -1,2 +1,20 @@
github.com/go-pkgz/routegroup v1.1.1 h1:Dm5IBiEmUbQT+3rliBimhX0SifnZp/uRF/WOu3XPmms=
github.com/go-pkgz/routegroup v1.1.1/go.mod h1:kDDPDRLRiRY1vnENrZJw1jQAzQX7fvsbsHGRQFNQfKc=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.20.0 h1:bkypFPDjIYGfCYD5mRBvpqxfYX1YCS1PXdKYWi8FsN0=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.20.0/go.mod h1:P+Lt/0by1T8bfcF3z737NnSbmxQAppXMRziHUxPOC8k=
golang.org/x/net v0.23.0 h1:7EYJ93RZ9vYSZAIb2x3lnuvqO5zneoD6IvWjuhfxjTs=
golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4=
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk=
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
google.golang.org/genproto/googleapis/api v0.0.0-20240513163218-0867130af1f8 h1:W5Xj/70xIA4x60O/IFyXivR5MGqblAb8R3w26pnD6No=
google.golang.org/genproto/googleapis/api v0.0.0-20240513163218-0867130af1f8/go.mod h1:vPrPUTsDCYxXWjP7clS81mZ6/803D8K4iM9Ma27VKas=
google.golang.org/genproto/googleapis/rpc v0.0.0-20240513163218-0867130af1f8 h1:mxSlqyb8ZAHsYDCfiXN1EDdNTdvjUJSLY+OnAUtYNYA=
google.golang.org/genproto/googleapis/rpc v0.0.0-20240513163218-0867130af1f8/go.mod h1:I7Y+G38R2bu5j1aLzfFmQfTcU/WnFuqDwLZAbvKTKpM=
google.golang.org/grpc v1.64.0 h1:KH3VH9y/MgNQg1dE7b3XfVK0GsPSIzJwdF617gUSbvY=
google.golang.org/grpc v1.64.0/go.mod h1:oxjF8E3FBnjp+/gVFYdWacaLDx9na1aqy9oovLpxQYg=
google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=

300
proto/main.pb.go Normal file
View File

@ -0,0 +1,300 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.34.1
// protoc v5.26.1
// source: main.proto
package crm
import (
_ "google.golang.org/genproto/googleapis/api/annotations"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
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)
)
type GetCatalogReq struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
}
func (x *GetCatalogReq) Reset() {
*x = GetCatalogReq{}
if protoimpl.UnsafeEnabled {
mi := &file_main_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *GetCatalogReq) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GetCatalogReq) ProtoMessage() {}
func (x *GetCatalogReq) ProtoReflect() protoreflect.Message {
mi := &file_main_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GetCatalogReq.ProtoReflect.Descriptor instead.
func (*GetCatalogReq) Descriptor() ([]byte, []int) {
return file_main_proto_rawDescGZIP(), []int{0}
}
type CatalogRsp struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Categories []*CatalogRsp_Category `protobuf:"bytes,1,rep,name=categories,proto3" json:"categories,omitempty"`
}
func (x *CatalogRsp) Reset() {
*x = CatalogRsp{}
if protoimpl.UnsafeEnabled {
mi := &file_main_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *CatalogRsp) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*CatalogRsp) ProtoMessage() {}
func (x *CatalogRsp) ProtoReflect() protoreflect.Message {
mi := &file_main_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use CatalogRsp.ProtoReflect.Descriptor instead.
func (*CatalogRsp) Descriptor() ([]byte, []int) {
return file_main_proto_rawDescGZIP(), []int{1}
}
func (x *CatalogRsp) GetCategories() []*CatalogRsp_Category {
if x != nil {
return x.Categories
}
return nil
}
type CatalogRsp_Category struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"`
Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`
Uri string `protobuf:"bytes,3,opt,name=uri,proto3" json:"uri,omitempty"`
Children []*CatalogRsp_Category `protobuf:"bytes,4,rep,name=children,proto3" json:"children,omitempty"`
}
func (x *CatalogRsp_Category) Reset() {
*x = CatalogRsp_Category{}
if protoimpl.UnsafeEnabled {
mi := &file_main_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *CatalogRsp_Category) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*CatalogRsp_Category) ProtoMessage() {}
func (x *CatalogRsp_Category) ProtoReflect() protoreflect.Message {
mi := &file_main_proto_msgTypes[2]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use CatalogRsp_Category.ProtoReflect.Descriptor instead.
func (*CatalogRsp_Category) Descriptor() ([]byte, []int) {
return file_main_proto_rawDescGZIP(), []int{1, 0}
}
func (x *CatalogRsp_Category) GetId() int64 {
if x != nil {
return x.Id
}
return 0
}
func (x *CatalogRsp_Category) GetName() string {
if x != nil {
return x.Name
}
return ""
}
func (x *CatalogRsp_Category) GetUri() string {
if x != nil {
return x.Uri
}
return ""
}
func (x *CatalogRsp_Category) GetChildren() []*CatalogRsp_Category {
if x != nil {
return x.Children
}
return nil
}
var File_main_proto protoreflect.FileDescriptor
var file_main_proto_rawDesc = []byte{
0x0a, 0x0a, 0x6d, 0x61, 0x69, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x09, 0x63, 0x72,
0x61, 0x62, 0x73, 0x2e, 0x63, 0x72, 0x6d, 0x1a, 0x1c, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f,
0x61, 0x70, 0x69, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e,
0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x0f, 0x0a, 0x0d, 0x47, 0x65, 0x74, 0x43, 0x61, 0x74, 0x61,
0x6c, 0x6f, 0x67, 0x52, 0x65, 0x71, 0x22, 0xca, 0x01, 0x0a, 0x0a, 0x43, 0x61, 0x74, 0x61, 0x6c,
0x6f, 0x67, 0x52, 0x73, 0x70, 0x12, 0x3e, 0x0a, 0x0a, 0x63, 0x61, 0x74, 0x65, 0x67, 0x6f, 0x72,
0x69, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1e, 0x2e, 0x63, 0x72, 0x61, 0x62,
0x73, 0x2e, 0x63, 0x72, 0x6d, 0x2e, 0x43, 0x61, 0x74, 0x61, 0x6c, 0x6f, 0x67, 0x52, 0x73, 0x70,
0x2e, 0x43, 0x61, 0x74, 0x65, 0x67, 0x6f, 0x72, 0x79, 0x52, 0x0a, 0x63, 0x61, 0x74, 0x65, 0x67,
0x6f, 0x72, 0x69, 0x65, 0x73, 0x1a, 0x7c, 0x0a, 0x08, 0x43, 0x61, 0x74, 0x65, 0x67, 0x6f, 0x72,
0x79, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x02, 0x69,
0x64, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52,
0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x10, 0x0a, 0x03, 0x75, 0x72, 0x69, 0x18, 0x03, 0x20, 0x01,
0x28, 0x09, 0x52, 0x03, 0x75, 0x72, 0x69, 0x12, 0x3a, 0x0a, 0x08, 0x63, 0x68, 0x69, 0x6c, 0x64,
0x72, 0x65, 0x6e, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1e, 0x2e, 0x63, 0x72, 0x61, 0x62,
0x73, 0x2e, 0x63, 0x72, 0x6d, 0x2e, 0x43, 0x61, 0x74, 0x61, 0x6c, 0x6f, 0x67, 0x52, 0x73, 0x70,
0x2e, 0x43, 0x61, 0x74, 0x65, 0x67, 0x6f, 0x72, 0x79, 0x52, 0x08, 0x63, 0x68, 0x69, 0x6c, 0x64,
0x72, 0x65, 0x6e, 0x32, 0x56, 0x0a, 0x03, 0x43, 0x52, 0x4d, 0x12, 0x4f, 0x0a, 0x0a, 0x47, 0x65,
0x74, 0x43, 0x61, 0x74, 0x61, 0x6c, 0x6f, 0x67, 0x12, 0x18, 0x2e, 0x63, 0x72, 0x61, 0x62, 0x73,
0x2e, 0x63, 0x72, 0x6d, 0x2e, 0x47, 0x65, 0x74, 0x43, 0x61, 0x74, 0x61, 0x6c, 0x6f, 0x67, 0x52,
0x65, 0x71, 0x1a, 0x15, 0x2e, 0x63, 0x72, 0x61, 0x62, 0x73, 0x2e, 0x63, 0x72, 0x6d, 0x2e, 0x43,
0x61, 0x74, 0x61, 0x6c, 0x6f, 0x67, 0x52, 0x73, 0x70, 0x22, 0x10, 0x82, 0xd3, 0xe4, 0x93, 0x02,
0x0a, 0x12, 0x08, 0x2f, 0x63, 0x61, 0x74, 0x61, 0x6c, 0x6f, 0x67, 0x42, 0x09, 0x5a, 0x07, 0x70,
0x6b, 0x67, 0x2f, 0x63, 0x72, 0x6d, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_main_proto_rawDescOnce sync.Once
file_main_proto_rawDescData = file_main_proto_rawDesc
)
func file_main_proto_rawDescGZIP() []byte {
file_main_proto_rawDescOnce.Do(func() {
file_main_proto_rawDescData = protoimpl.X.CompressGZIP(file_main_proto_rawDescData)
})
return file_main_proto_rawDescData
}
var file_main_proto_msgTypes = make([]protoimpl.MessageInfo, 3)
var file_main_proto_goTypes = []interface{}{
(*GetCatalogReq)(nil), // 0: crabs.crm.GetCatalogReq
(*CatalogRsp)(nil), // 1: crabs.crm.CatalogRsp
(*CatalogRsp_Category)(nil), // 2: crabs.crm.CatalogRsp.Category
}
var file_main_proto_depIdxs = []int32{
2, // 0: crabs.crm.CatalogRsp.categories:type_name -> crabs.crm.CatalogRsp.Category
2, // 1: crabs.crm.CatalogRsp.Category.children:type_name -> crabs.crm.CatalogRsp.Category
0, // 2: crabs.crm.CRM.GetCatalog:input_type -> crabs.crm.GetCatalogReq
1, // 3: crabs.crm.CRM.GetCatalog:output_type -> crabs.crm.CatalogRsp
3, // [3:4] is the sub-list for method output_type
2, // [2:3] is the sub-list for method input_type
2, // [2:2] is the sub-list for extension type_name
2, // [2:2] is the sub-list for extension extendee
0, // [0:2] is the sub-list for field type_name
}
func init() { file_main_proto_init() }
func file_main_proto_init() {
if File_main_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_main_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*GetCatalogReq); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_main_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*CatalogRsp); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_main_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*CatalogRsp_Category); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_main_proto_rawDesc,
NumEnums: 0,
NumMessages: 3,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_main_proto_goTypes,
DependencyIndexes: file_main_proto_depIdxs,
MessageInfos: file_main_proto_msgTypes,
}.Build()
File_main_proto = out.File
file_main_proto_rawDesc = nil
file_main_proto_goTypes = nil
file_main_proto_depIdxs = nil
}

155
proto/main.pb.gw.go Normal file
View File

@ -0,0 +1,155 @@
// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT.
// source: main.proto
/*
Package crm is a reverse proxy.
It translates gRPC into RESTful JSON APIs.
*/
package crm
import (
"context"
"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
var _ io.Reader
var _ status.Status
var _ = runtime.String
var _ = utilities.NewDoubleArray
var _ = metadata.Join
func request_CRM_GetCatalog_0(ctx context.Context, marshaler runtime.Marshaler, client CRMClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq GetCatalogReq
var metadata runtime.ServerMetadata
msg, err := client.GetCatalog(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_CRM_GetCatalog_0(ctx context.Context, marshaler runtime.Marshaler, server CRMServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq GetCatalogReq
var metadata runtime.ServerMetadata
msg, err := server.GetCatalog(ctx, &protoReq)
return msg, metadata, err
}
// RegisterCRMHandlerServer registers the http handlers for service CRM to "mux".
// UnaryRPC :call CRMServer 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 RegisterCRMHandlerFromEndpoint instead.
func RegisterCRMHandlerServer(ctx context.Context, mux *runtime.ServeMux, server CRMServer) error {
mux.Handle("GET", pattern_CRM_GetCatalog_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)
var err error
var annotatedContext context.Context
annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/crabs.crm.CRM/GetCatalog", runtime.WithHTTPPathPattern("/catalog"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_CRM_GetCatalog_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_CRM_GetCatalog_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
return nil
}
// RegisterCRMHandlerFromEndpoint is same as RegisterCRMHandler but
// automatically dials to "endpoint" and closes the connection when "ctx" gets done.
func RegisterCRMHandlerFromEndpoint(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 RegisterCRMHandler(ctx, mux, conn)
}
// RegisterCRMHandler registers the http handlers for service CRM to "mux".
// The handlers forward requests to the grpc endpoint over "conn".
func RegisterCRMHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {
return RegisterCRMHandlerClient(ctx, mux, NewCRMClient(conn))
}
// RegisterCRMHandlerClient registers the http handlers for service CRM
// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "CRMClient".
// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "CRMClient"
// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in
// "CRMClient" to call the correct interceptors.
func RegisterCRMHandlerClient(ctx context.Context, mux *runtime.ServeMux, client CRMClient) error {
mux.Handle("GET", pattern_CRM_GetCatalog_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)
var err error
var annotatedContext context.Context
annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/crabs.crm.CRM/GetCatalog", runtime.WithHTTPPathPattern("/catalog"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_CRM_GetCatalog_0(annotatedContext, inboundMarshaler, client, req, pathParams)
annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)
if err != nil {
runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)
return
}
forward_CRM_GetCatalog_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
return nil
}
var (
pattern_CRM_GetCatalog_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0}, []string{"catalog"}, ""))
)
var (
forward_CRM_GetCatalog_0 = runtime.ForwardResponseMessage
)

104
proto/main.swagger.json Normal file
View File

@ -0,0 +1,104 @@
{
"swagger": "2.0",
"info": {
"title": "main.proto",
"version": "version not set"
},
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"paths": {
"/catalog": {
"get": {
"operationId": "CRM_GetCatalog",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"$ref": "#/definitions/crmCatalogRsp"
}
},
"default": {
"description": "An unexpected error response.",
"schema": {
"$ref": "#/definitions/runtimeError"
}
}
},
"tags": [
"CRM"
]
}
}
},
"definitions": {
"CatalogRspCategory": {
"type": "object",
"properties": {
"id": {
"type": "string",
"format": "int64"
},
"name": {
"type": "string"
},
"uri": {
"type": "string"
},
"children": {
"type": "array",
"items": {
"$ref": "#/definitions/CatalogRspCategory"
}
}
}
},
"crmCatalogRsp": {
"type": "object",
"properties": {
"categories": {
"type": "array",
"items": {
"$ref": "#/definitions/CatalogRspCategory"
}
}
}
},
"protobufAny": {
"type": "object",
"properties": {
"type_url": {
"type": "string"
},
"value": {
"type": "string",
"format": "byte"
}
}
},
"runtimeError": {
"type": "object",
"properties": {
"error": {
"type": "string"
},
"code": {
"type": "integer",
"format": "int32"
},
"message": {
"type": "string"
},
"details": {
"type": "array",
"items": {
"$ref": "#/definitions/protobufAny"
}
}
}
}
}
}

109
proto/main_grpc.pb.go Normal file
View File

@ -0,0 +1,109 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.3.0
// - protoc v5.26.1
// source: main.proto
package crm
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.32.0 or later.
const _ = grpc.SupportPackageIsVersion7
const (
CRM_GetCatalog_FullMethodName = "/crabs.crm.CRM/GetCatalog"
)
// CRMClient is the client API for CRM 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 CRMClient interface {
GetCatalog(ctx context.Context, in *GetCatalogReq, opts ...grpc.CallOption) (*CatalogRsp, error)
}
type cRMClient struct {
cc grpc.ClientConnInterface
}
func NewCRMClient(cc grpc.ClientConnInterface) CRMClient {
return &cRMClient{cc}
}
func (c *cRMClient) GetCatalog(ctx context.Context, in *GetCatalogReq, opts ...grpc.CallOption) (*CatalogRsp, error) {
out := new(CatalogRsp)
err := c.cc.Invoke(ctx, CRM_GetCatalog_FullMethodName, in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// CRMServer is the server API for CRM service.
// All implementations must embed UnimplementedCRMServer
// for forward compatibility
type CRMServer interface {
GetCatalog(context.Context, *GetCatalogReq) (*CatalogRsp, error)
mustEmbedUnimplementedCRMServer()
}
// UnimplementedCRMServer must be embedded to have forward compatible implementations.
type UnimplementedCRMServer struct {
}
func (UnimplementedCRMServer) GetCatalog(context.Context, *GetCatalogReq) (*CatalogRsp, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetCatalog not implemented")
}
func (UnimplementedCRMServer) mustEmbedUnimplementedCRMServer() {}
// UnsafeCRMServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to CRMServer will
// result in compilation errors.
type UnsafeCRMServer interface {
mustEmbedUnimplementedCRMServer()
}
func RegisterCRMServer(s grpc.ServiceRegistrar, srv CRMServer) {
s.RegisterService(&CRM_ServiceDesc, srv)
}
func _CRM_GetCatalog_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetCatalogReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(CRMServer).GetCatalog(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: CRM_GetCatalog_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(CRMServer).GetCatalog(ctx, req.(*GetCatalogReq))
}
return interceptor(ctx, in, info, handler)
}
// CRM_ServiceDesc is the grpc.ServiceDesc for CRM service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var CRM_ServiceDesc = grpc.ServiceDesc{
ServiceName: "crabs.crm.CRM",
HandlerType: (*CRMServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "GetCatalog",
Handler: _CRM_GetCatalog_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "main.proto",
}