From 16a9c8f9bc47a2d0e847c636953664b6324898d1 Mon Sep 17 00:00:00 2001 From: Andrey Ivanov Date: Sun, 27 Sep 2020 09:56:35 +0300 Subject: [PATCH 01/16] HW13 WIP --- hw12_13_14_15_calendar/internal/logger/logger.go | 9 +++------ hw12_13_14_15_calendar/internal/storage/sql/sql.go | 11 +++++------ 2 files changed, 8 insertions(+), 12 deletions(-) diff --git a/hw12_13_14_15_calendar/internal/logger/logger.go b/hw12_13_14_15_calendar/internal/logger/logger.go index b2482dc..edd91ef 100644 --- a/hw12_13_14_15_calendar/internal/logger/logger.go +++ b/hw12_13_14_15_calendar/internal/logger/logger.go @@ -22,8 +22,10 @@ type Logger struct { Logger amitralog.Logger } +var validLevel = map[string]bool{"debug": true, "info":true, "warn": true, "error": true, "fatal": true} + func New(conf config.Config) (Interface, error) { - if conf.Logger.File == "" || !validLevel(conf.Logger.Level) { + if conf.Logger.File == "" || !validLevel[strings.ToLower(conf.Logger.Level)] { return nil, errors.New("invalid logger config") } @@ -64,8 +66,3 @@ func (l *Logger) Fatalf(format string, args ...interface{}) { l.Logger.Fatalf(format, args) os.Exit(2) } - -func validLevel(level string) bool { - var l = map[string]int{"debug": 1, "info": 1, "warn": 1, "error": 1, "fatal": 1} - return l[strings.ToLower(level)] == 1 -} diff --git a/hw12_13_14_15_calendar/internal/storage/sql/sql.go b/hw12_13_14_15_calendar/internal/storage/sql/sql.go index 4476f30..fcf9a39 100644 --- a/hw12_13_14_15_calendar/internal/storage/sql/sql.go +++ b/hw12_13_14_15_calendar/internal/storage/sql/sql.go @@ -83,10 +83,9 @@ func (s *Storage) Delete(id event.ID) error { func (s *Storage) List() (map[event.ID]event.Event, error) { res := make(map[event.ID]event.Event) - results, err := s.db.Query( - `SELECT (id,title,date,latency,note,userID,notifyTime) from events ORDER BY id`) + results, err := s.db.Query( `SELECT (id,title,date,latency,note,userID,notifyTime) from events ORDER BY id`) if err != nil { - return map[event.ID]event.Event{}, err + return nil, err } defer results.Close() for results.Next() { @@ -95,16 +94,16 @@ func (s *Storage) List() (map[event.ID]event.Event, error) { var dateRaw string err = results.Scan(&id, &evt.Title, &dateRaw, &evt.Latency, &evt.Note, &evt.UserID, &evt.NotifyTime) if err != nil { - return map[event.ID]event.Event{}, err + return nil, err } evt.Date, err = time.Parse(dateTimeLayout, dateRaw) if err != nil { - return map[event.ID]event.Event{}, err + return nil, err } res[id] = evt } if results.Err() != nil { - return map[event.ID]event.Event{}, results.Err() + return nil, results.Err() } return res, nil } From 83495e1e79f2db9f14ba28683c995cf6a3a9546a Mon Sep 17 00:00:00 2001 From: Andrey Ivanov Date: Sun, 27 Sep 2020 19:09:01 +0300 Subject: [PATCH 02/16] HW13 WIP --- hw12_13_14_15_calendar/api/EventService.proto | 44 ++++++++++++++++++- hw12_13_14_15_calendar/go.mod | 2 + 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/hw12_13_14_15_calendar/api/EventService.proto b/hw12_13_14_15_calendar/api/EventService.proto index d188eff..0a3f23d 100644 --- a/hw12_13_14_15_calendar/api/EventService.proto +++ b/hw12_13_14_15_calendar/api/EventService.proto @@ -2,6 +2,46 @@ syntax = "proto3"; package event; -message Event { - // TODO +option go_package = "event"; + +import "google/protobuf/timestamp.proto"; +import "google/protobuf/duration.proto"; +import "google/protobuf/empty.proto"; + +service CalendarRPC { + rpc Create(event) returns (eventID); + rpc Update(eventWithID) returns (google.protobuf.Empty); + rpc Delete(eventID) returns (google.protobuf.Empty); + rpc List(google.protobuf.Empty) returns (eventList); + rpc GetByID(eventID) returns (eventList); + rpc GetByDay(date) returns (eventList); + rpc GetByWeek(date) returns (eventList); + rpc GetByMonth(date) returns (eventList); +} + +message event { + string ID = 1; + string title = 2; + google.protobuf.Timestamp date = 3; + google.protobuf.Duration latency = 4; + string note = 5; + string UserID = 6; + google.protobuf.Duration notyfyTime = 7; +} + +message eventList { + repeated event events = 1; +} + +message eventID { + string ID = 1; +} + +message eventWithID { + string ID = 1; + event event = 2; +} + +message date { + google.protobuf.Timestamp date = 1; } diff --git a/hw12_13_14_15_calendar/go.mod b/hw12_13_14_15_calendar/go.mod index 60e7d9b..3dd9c48 100644 --- a/hw12_13_14_15_calendar/go.mod +++ b/hw12_13_14_15_calendar/go.mod @@ -6,8 +6,10 @@ require ( github.com/BurntSushi/toml v0.3.1 github.com/amitrai48/logger v0.0.0-20190214092904-448001c055ec github.com/go-sql-driver/mysql v1.5.0 + github.com/golang/protobuf v1.4.2 // indirect github.com/mattn/go-shellwords v1.0.10 // indirect github.com/stretchr/testify v1.4.0 go.uber.org/zap v1.15.0 // indirect + google.golang.org/protobuf v1.25.0 // indirect gopkg.in/yaml.v2 v2.3.0 // indirect ) From 34a017b0885ba4508c5c246bec539b1ce01bddbf Mon Sep 17 00:00:00 2001 From: Andrey Ivanov Date: Sun, 27 Sep 2020 13:27:33 -0400 Subject: [PATCH 03/16] HW13 WIP --- hw12_13_14_15_calendar/Makefile | 2 + .../calendar.proto} | 0 .../internal/grpc/calendar.pb.go | 316 ++++++++++++++++++ .../internal/logger/logger.go | 2 +- .../internal/storage/sql/sql.go | 2 +- 5 files changed, 320 insertions(+), 2 deletions(-) rename hw12_13_14_15_calendar/{api/EventService.proto => grpc/calendar.proto} (100%) create mode 100644 hw12_13_14_15_calendar/internal/grpc/calendar.pb.go diff --git a/hw12_13_14_15_calendar/Makefile b/hw12_13_14_15_calendar/Makefile index 93a3436..4b08356 100644 --- a/hw12_13_14_15_calendar/Makefile +++ b/hw12_13_14_15_calendar/Makefile @@ -13,4 +13,6 @@ lint: install-lint-deps install-lint-deps: (which golangci-lint > /dev/null) || curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(shell go env GOPATH)/bin v1.30.0 +generate: + protoc --go_out=grpc:internal grpc/calendar.proto .PHONY: build run test lint \ No newline at end of file diff --git a/hw12_13_14_15_calendar/api/EventService.proto b/hw12_13_14_15_calendar/grpc/calendar.proto similarity index 100% rename from hw12_13_14_15_calendar/api/EventService.proto rename to hw12_13_14_15_calendar/grpc/calendar.proto diff --git a/hw12_13_14_15_calendar/internal/grpc/calendar.pb.go b/hw12_13_14_15_calendar/internal/grpc/calendar.pb.go new file mode 100644 index 0000000..4d79a6b --- /dev/null +++ b/hw12_13_14_15_calendar/internal/grpc/calendar.pb.go @@ -0,0 +1,316 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// source: grpc/calendar.proto + +package event + +import ( + fmt "fmt" + proto "github.com/golang/protobuf/proto" + duration "github.com/golang/protobuf/ptypes/duration" + _ "github.com/golang/protobuf/ptypes/empty" + timestamp "github.com/golang/protobuf/ptypes/timestamp" + math "math" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package + +type Event struct { + ID string `protobuf:"bytes,1,opt,name=ID,proto3" json:"ID,omitempty"` + Title string `protobuf:"bytes,2,opt,name=title,proto3" json:"title,omitempty"` + Date *timestamp.Timestamp `protobuf:"bytes,3,opt,name=date,proto3" json:"date,omitempty"` + Latency *duration.Duration `protobuf:"bytes,4,opt,name=latency,proto3" json:"latency,omitempty"` + Note string `protobuf:"bytes,5,opt,name=note,proto3" json:"note,omitempty"` + UserID string `protobuf:"bytes,6,opt,name=UserID,proto3" json:"UserID,omitempty"` + NotyfyTime *duration.Duration `protobuf:"bytes,7,opt,name=notyfyTime,proto3" json:"notyfyTime,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *Event) Reset() { *m = Event{} } +func (m *Event) String() string { return proto.CompactTextString(m) } +func (*Event) ProtoMessage() {} +func (*Event) Descriptor() ([]byte, []int) { + return fileDescriptor_b5d285f4b6d41dfd, []int{0} +} + +func (m *Event) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_Event.Unmarshal(m, b) +} +func (m *Event) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_Event.Marshal(b, m, deterministic) +} +func (m *Event) XXX_Merge(src proto.Message) { + xxx_messageInfo_Event.Merge(m, src) +} +func (m *Event) XXX_Size() int { + return xxx_messageInfo_Event.Size(m) +} +func (m *Event) XXX_DiscardUnknown() { + xxx_messageInfo_Event.DiscardUnknown(m) +} + +var xxx_messageInfo_Event proto.InternalMessageInfo + +func (m *Event) GetID() string { + if m != nil { + return m.ID + } + return "" +} + +func (m *Event) GetTitle() string { + if m != nil { + return m.Title + } + return "" +} + +func (m *Event) GetDate() *timestamp.Timestamp { + if m != nil { + return m.Date + } + return nil +} + +func (m *Event) GetLatency() *duration.Duration { + if m != nil { + return m.Latency + } + return nil +} + +func (m *Event) GetNote() string { + if m != nil { + return m.Note + } + return "" +} + +func (m *Event) GetUserID() string { + if m != nil { + return m.UserID + } + return "" +} + +func (m *Event) GetNotyfyTime() *duration.Duration { + if m != nil { + return m.NotyfyTime + } + return nil +} + +type EventList struct { + Events []*Event `protobuf:"bytes,1,rep,name=events,proto3" json:"events,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *EventList) Reset() { *m = EventList{} } +func (m *EventList) String() string { return proto.CompactTextString(m) } +func (*EventList) ProtoMessage() {} +func (*EventList) Descriptor() ([]byte, []int) { + return fileDescriptor_b5d285f4b6d41dfd, []int{1} +} + +func (m *EventList) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_EventList.Unmarshal(m, b) +} +func (m *EventList) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_EventList.Marshal(b, m, deterministic) +} +func (m *EventList) XXX_Merge(src proto.Message) { + xxx_messageInfo_EventList.Merge(m, src) +} +func (m *EventList) XXX_Size() int { + return xxx_messageInfo_EventList.Size(m) +} +func (m *EventList) XXX_DiscardUnknown() { + xxx_messageInfo_EventList.DiscardUnknown(m) +} + +var xxx_messageInfo_EventList proto.InternalMessageInfo + +func (m *EventList) GetEvents() []*Event { + if m != nil { + return m.Events + } + return nil +} + +type EventID struct { + ID string `protobuf:"bytes,1,opt,name=ID,proto3" json:"ID,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *EventID) Reset() { *m = EventID{} } +func (m *EventID) String() string { return proto.CompactTextString(m) } +func (*EventID) ProtoMessage() {} +func (*EventID) Descriptor() ([]byte, []int) { + return fileDescriptor_b5d285f4b6d41dfd, []int{2} +} + +func (m *EventID) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_EventID.Unmarshal(m, b) +} +func (m *EventID) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_EventID.Marshal(b, m, deterministic) +} +func (m *EventID) XXX_Merge(src proto.Message) { + xxx_messageInfo_EventID.Merge(m, src) +} +func (m *EventID) XXX_Size() int { + return xxx_messageInfo_EventID.Size(m) +} +func (m *EventID) XXX_DiscardUnknown() { + xxx_messageInfo_EventID.DiscardUnknown(m) +} + +var xxx_messageInfo_EventID proto.InternalMessageInfo + +func (m *EventID) GetID() string { + if m != nil { + return m.ID + } + return "" +} + +type EventWithID struct { + ID string `protobuf:"bytes,1,opt,name=ID,proto3" json:"ID,omitempty"` + Event *Event `protobuf:"bytes,2,opt,name=event,proto3" json:"event,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *EventWithID) Reset() { *m = EventWithID{} } +func (m *EventWithID) String() string { return proto.CompactTextString(m) } +func (*EventWithID) ProtoMessage() {} +func (*EventWithID) Descriptor() ([]byte, []int) { + return fileDescriptor_b5d285f4b6d41dfd, []int{3} +} + +func (m *EventWithID) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_EventWithID.Unmarshal(m, b) +} +func (m *EventWithID) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_EventWithID.Marshal(b, m, deterministic) +} +func (m *EventWithID) XXX_Merge(src proto.Message) { + xxx_messageInfo_EventWithID.Merge(m, src) +} +func (m *EventWithID) XXX_Size() int { + return xxx_messageInfo_EventWithID.Size(m) +} +func (m *EventWithID) XXX_DiscardUnknown() { + xxx_messageInfo_EventWithID.DiscardUnknown(m) +} + +var xxx_messageInfo_EventWithID proto.InternalMessageInfo + +func (m *EventWithID) GetID() string { + if m != nil { + return m.ID + } + return "" +} + +func (m *EventWithID) GetEvent() *Event { + if m != nil { + return m.Event + } + return nil +} + +type Date struct { + Date *timestamp.Timestamp `protobuf:"bytes,1,opt,name=date,proto3" json:"date,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *Date) Reset() { *m = Date{} } +func (m *Date) String() string { return proto.CompactTextString(m) } +func (*Date) ProtoMessage() {} +func (*Date) Descriptor() ([]byte, []int) { + return fileDescriptor_b5d285f4b6d41dfd, []int{4} +} + +func (m *Date) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_Date.Unmarshal(m, b) +} +func (m *Date) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_Date.Marshal(b, m, deterministic) +} +func (m *Date) XXX_Merge(src proto.Message) { + xxx_messageInfo_Date.Merge(m, src) +} +func (m *Date) XXX_Size() int { + return xxx_messageInfo_Date.Size(m) +} +func (m *Date) XXX_DiscardUnknown() { + xxx_messageInfo_Date.DiscardUnknown(m) +} + +var xxx_messageInfo_Date proto.InternalMessageInfo + +func (m *Date) GetDate() *timestamp.Timestamp { + if m != nil { + return m.Date + } + return nil +} + +func init() { + proto.RegisterType((*Event)(nil), "event.event") + proto.RegisterType((*EventList)(nil), "event.eventList") + proto.RegisterType((*EventID)(nil), "event.eventID") + proto.RegisterType((*EventWithID)(nil), "event.eventWithID") + proto.RegisterType((*Date)(nil), "event.date") +} + +func init() { proto.RegisterFile("grpc/calendar.proto", fileDescriptor_b5d285f4b6d41dfd) } + +var fileDescriptor_b5d285f4b6d41dfd = []byte{ + // 429 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x92, 0xdf, 0x8b, 0xd3, 0x40, + 0x10, 0xc7, 0x49, 0x7f, 0x24, 0x76, 0x22, 0x87, 0x8c, 0x72, 0xec, 0x45, 0xd0, 0x12, 0x44, 0xaa, + 0x07, 0xa9, 0xf6, 0x44, 0xf0, 0xd1, 0xeb, 0x8a, 0x04, 0x14, 0x24, 0x78, 0x1c, 0xf8, 0x96, 0x6b, + 0xe7, 0x7a, 0xc1, 0x34, 0x1b, 0xd2, 0x39, 0x21, 0x6f, 0xfe, 0xdb, 0xbe, 0x49, 0x66, 0x53, 0xa9, + 0xa9, 0x5a, 0x5f, 0xc2, 0xce, 0x7e, 0x3f, 0x3b, 0xdf, 0x9d, 0x6f, 0x16, 0xee, 0xaf, 0xaa, 0x72, + 0x31, 0x5d, 0xa4, 0x39, 0x15, 0xcb, 0xb4, 0x8a, 0xca, 0xca, 0xb0, 0xc1, 0x21, 0x7d, 0xa3, 0x82, + 0x83, 0xc7, 0x2b, 0x63, 0x56, 0x39, 0x4d, 0x65, 0xf3, 0xea, 0xf6, 0x7a, 0xca, 0xd9, 0x9a, 0x36, + 0x9c, 0xae, 0x4b, 0xcb, 0x05, 0x8f, 0xba, 0xc0, 0xf2, 0xb6, 0x4a, 0x39, 0x33, 0x45, 0xab, 0x3f, + 0xec, 0xea, 0xb4, 0x2e, 0xb9, 0xb6, 0x62, 0xf8, 0xc3, 0x01, 0xeb, 0x83, 0x47, 0xd0, 0x8b, 0xb5, + 0x72, 0xc6, 0xce, 0x64, 0x94, 0xf4, 0x62, 0x8d, 0x0f, 0x60, 0xc8, 0x19, 0xe7, 0xa4, 0x7a, 0xb2, + 0x65, 0x0b, 0x8c, 0x60, 0xb0, 0x4c, 0x99, 0x54, 0x7f, 0xec, 0x4c, 0xfc, 0x59, 0x10, 0xd9, 0xde, + 0xd1, 0xb6, 0x77, 0xf4, 0x79, 0x7b, 0xb9, 0x44, 0x38, 0x3c, 0x03, 0x2f, 0x4f, 0x99, 0x8a, 0x45, + 0xad, 0x06, 0x72, 0xe4, 0x64, 0xef, 0x88, 0x6e, 0xaf, 0x9b, 0x6c, 0x49, 0x44, 0x18, 0x14, 0x86, + 0x49, 0x0d, 0xc5, 0x59, 0xd6, 0x78, 0x0c, 0xee, 0xc5, 0x86, 0xaa, 0x58, 0x2b, 0x57, 0x76, 0xdb, + 0x0a, 0xdf, 0x00, 0x14, 0x86, 0xeb, 0xeb, 0xba, 0x71, 0x56, 0xde, 0x21, 0x8f, 0x1d, 0x38, 0x7c, + 0x09, 0x23, 0x19, 0xfd, 0x43, 0xb6, 0x61, 0x7c, 0x02, 0xae, 0x14, 0x1b, 0xe5, 0x8c, 0xfb, 0x13, + 0x7f, 0x76, 0x37, 0x92, 0xd2, 0x7e, 0x93, 0x56, 0x0b, 0x4f, 0xc0, 0x93, 0x55, 0xac, 0xbb, 0x79, + 0x85, 0x6f, 0xc1, 0x17, 0xe9, 0x32, 0xe3, 0x9b, 0x7d, 0x19, 0xc3, 0x36, 0x67, 0x89, 0xb3, 0xdb, + 0xde, 0x4a, 0xe1, 0x6b, 0x1b, 0xee, 0xaf, 0x90, 0x9d, 0xff, 0x0b, 0x79, 0xf6, 0xbd, 0x0f, 0xfe, + 0xbc, 0x7d, 0x3c, 0xc9, 0xa7, 0x39, 0x3e, 0x05, 0x77, 0x5e, 0x51, 0xd3, 0xe9, 0x37, 0x9b, 0xe0, + 0x68, 0xb7, 0x8a, 0x35, 0xbe, 0x02, 0xf7, 0xa2, 0x14, 0x47, 0xdc, 0x55, 0xec, 0x04, 0xc1, 0xf1, + 0x9e, 0xef, 0xbb, 0xe6, 0xe1, 0xe0, 0x0b, 0x70, 0x35, 0xe5, 0xc4, 0x84, 0x9d, 0x7e, 0xff, 0x38, + 0x31, 0x90, 0x8c, 0xff, 0xa2, 0x07, 0xf7, 0x76, 0xfb, 0x08, 0x79, 0x0a, 0xde, 0x7b, 0xe2, 0xf3, + 0xba, 0x09, 0xb2, 0x63, 0xb2, 0x0f, 0x3f, 0x83, 0x3b, 0x02, 0xeb, 0xb4, 0x46, 0xbf, 0x55, 0x9b, + 0xa9, 0xfe, 0x80, 0x3e, 0x87, 0x91, 0xa0, 0x97, 0x44, 0x5f, 0x0f, 0xb1, 0xa7, 0x00, 0xc2, 0x7e, + 0x34, 0x05, 0xdf, 0x1c, 0x80, 0xcf, 0xbd, 0x2f, 0xf6, 0x1f, 0x5e, 0xb9, 0x32, 0xdb, 0xd9, 0xcf, + 0x00, 0x00, 0x00, 0xff, 0xff, 0xb3, 0xa8, 0x5f, 0x40, 0xd3, 0x03, 0x00, 0x00, +} diff --git a/hw12_13_14_15_calendar/internal/logger/logger.go b/hw12_13_14_15_calendar/internal/logger/logger.go index edd91ef..005ca88 100644 --- a/hw12_13_14_15_calendar/internal/logger/logger.go +++ b/hw12_13_14_15_calendar/internal/logger/logger.go @@ -22,7 +22,7 @@ type Logger struct { Logger amitralog.Logger } -var validLevel = map[string]bool{"debug": true, "info":true, "warn": true, "error": true, "fatal": true} +var validLevel = map[string]bool{"debug": true, "info": true, "warn": true, "error": true, "fatal": true} func New(conf config.Config) (Interface, error) { if conf.Logger.File == "" || !validLevel[strings.ToLower(conf.Logger.Level)] { diff --git a/hw12_13_14_15_calendar/internal/storage/sql/sql.go b/hw12_13_14_15_calendar/internal/storage/sql/sql.go index fcf9a39..316c5b8 100644 --- a/hw12_13_14_15_calendar/internal/storage/sql/sql.go +++ b/hw12_13_14_15_calendar/internal/storage/sql/sql.go @@ -83,7 +83,7 @@ func (s *Storage) Delete(id event.ID) error { func (s *Storage) List() (map[event.ID]event.Event, error) { res := make(map[event.ID]event.Event) - results, err := s.db.Query( `SELECT (id,title,date,latency,note,userID,notifyTime) from events ORDER BY id`) + results, err := s.db.Query(`SELECT (id,title,date,latency,note,userID,notifyTime) from events ORDER BY id`) if err != nil { return nil, err } From 1c48e18aedd86c30df49162338289e31e875429b Mon Sep 17 00:00:00 2001 From: Andrey Ivanov Date: Wed, 30 Sep 2020 17:09:25 +0300 Subject: [PATCH 04/16] HW13 WIP --- hw12_13_14_15_calendar/Makefile | 8 + hw12_13_14_15_calendar/cmd/calendar/main.go | 11 +- hw12_13_14_15_calendar/go.mod | 7 +- hw12_13_14_15_calendar/grpc/calendar.proto | 47 --- .../grpc/google/api/annotations.proto | 31 ++ .../grpc/google/api/http.proto | 318 ++++++++++++++++++ .../grpc/google/api/httpbody.proto | 78 +++++ hw12_13_14_15_calendar/grpc/grpc.proto | 76 +++++ .../internal/grpc/calendar.pb.go | 316 ----------------- .../internal/server/grpc/grpc.go | 16 + .../server/http/{server.go => http.go} | 0 .../internal/storage/memory/memory.go | 29 ++ .../internal/storage/sql/sql.go | 48 +++ .../internal/storage/store.go | 10 +- 14 files changed, 623 insertions(+), 372 deletions(-) delete mode 100644 hw12_13_14_15_calendar/grpc/calendar.proto create mode 100755 hw12_13_14_15_calendar/grpc/google/api/annotations.proto create mode 100755 hw12_13_14_15_calendar/grpc/google/api/http.proto create mode 100755 hw12_13_14_15_calendar/grpc/google/api/httpbody.proto create mode 100644 hw12_13_14_15_calendar/grpc/grpc.proto delete mode 100644 hw12_13_14_15_calendar/internal/grpc/calendar.pb.go create mode 100644 hw12_13_14_15_calendar/internal/server/grpc/grpc.go rename hw12_13_14_15_calendar/internal/server/http/{server.go => http.go} (100%) diff --git a/hw12_13_14_15_calendar/Makefile b/hw12_13_14_15_calendar/Makefile index 4b08356..400c362 100644 --- a/hw12_13_14_15_calendar/Makefile +++ b/hw12_13_14_15_calendar/Makefile @@ -1,3 +1,5 @@ +cdir = $(shell pwd) + build: go build -o ./bin/calendar ./cmd/calendar/main.go @@ -15,4 +17,10 @@ install-lint-deps: generate: protoc --go_out=grpc:internal grpc/calendar.proto + +gen2: + protoc -I /usr/local/include -I ${cdir}/grpc --go_out=plugins=grpc:${cdir}/internal/grpc \ + --grpc-gateway_out=logtostderr=true:${cdir}/internal/grpc \ + ${cdir}/grpc/grpc.proto + .PHONY: build run test lint \ No newline at end of file diff --git a/hw12_13_14_15_calendar/cmd/calendar/main.go b/hw12_13_14_15_calendar/cmd/calendar/main.go index ecef853..f9d2822 100644 --- a/hw12_13_14_15_calendar/cmd/calendar/main.go +++ b/hw12_13_14_15_calendar/cmd/calendar/main.go @@ -2,6 +2,8 @@ package main import ( "flag" + "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/grpc" + googrpc "google.golang.org/grpc" oslog "log" "os" "os/signal" @@ -10,6 +12,7 @@ import ( "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/app" "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/config" "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/logger" + internalgrpc "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/server/grpc" internalhttp "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/server/http" store "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/storage" ) @@ -42,7 +45,9 @@ func main() { calendar := app.New(log, st) - server := internalhttp.NewServer(calendar, conf.Server.Address, conf.Server.Port) + serverHTTP := internalhttp.NewServer(calendar, conf.Server.Address, conf.Server.Port) + serverGRPC := googrpc.NewServer() + grpc.RegisterGrpcServer(serverGRPC, internalgrpc.Service{}) go func() { signals := make(chan os.Signal, 1) @@ -51,12 +56,12 @@ func main() { <-signals signal.Stop(signals) - if err := server.Stop(); err != nil { + if err := serverHTTP.Stop(); err != nil { log.Errorf("failed to stop http server: " + err.Error()) } }() - if err := server.Start(); err != nil { + if err := serverHTTP.Start(); err != nil { log.Errorf("failed to start http server: " + err.Error()) os.Exit(1) } diff --git a/hw12_13_14_15_calendar/go.mod b/hw12_13_14_15_calendar/go.mod index 3dd9c48..8377f6d 100644 --- a/hw12_13_14_15_calendar/go.mod +++ b/hw12_13_14_15_calendar/go.mod @@ -6,10 +6,13 @@ require ( github.com/BurntSushi/toml v0.3.1 github.com/amitrai48/logger v0.0.0-20190214092904-448001c055ec github.com/go-sql-driver/mysql v1.5.0 - github.com/golang/protobuf v1.4.2 // indirect - github.com/mattn/go-shellwords v1.0.10 // indirect + github.com/golang/protobuf v1.4.2 + github.com/grpc-ecosystem/grpc-gateway v1.15.0 github.com/stretchr/testify v1.4.0 go.uber.org/zap v1.15.0 // indirect + golang.org/x/net v0.0.0-20191002035440-2ec189313ef0 + google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013 + google.golang.org/grpc v1.32.0 google.golang.org/protobuf v1.25.0 // indirect gopkg.in/yaml.v2 v2.3.0 // indirect ) diff --git a/hw12_13_14_15_calendar/grpc/calendar.proto b/hw12_13_14_15_calendar/grpc/calendar.proto deleted file mode 100644 index 0a3f23d..0000000 --- a/hw12_13_14_15_calendar/grpc/calendar.proto +++ /dev/null @@ -1,47 +0,0 @@ -syntax = "proto3"; - -package event; - -option go_package = "event"; - -import "google/protobuf/timestamp.proto"; -import "google/protobuf/duration.proto"; -import "google/protobuf/empty.proto"; - -service CalendarRPC { - rpc Create(event) returns (eventID); - rpc Update(eventWithID) returns (google.protobuf.Empty); - rpc Delete(eventID) returns (google.protobuf.Empty); - rpc List(google.protobuf.Empty) returns (eventList); - rpc GetByID(eventID) returns (eventList); - rpc GetByDay(date) returns (eventList); - rpc GetByWeek(date) returns (eventList); - rpc GetByMonth(date) returns (eventList); -} - -message event { - string ID = 1; - string title = 2; - google.protobuf.Timestamp date = 3; - google.protobuf.Duration latency = 4; - string note = 5; - string UserID = 6; - google.protobuf.Duration notyfyTime = 7; -} - -message eventList { - repeated event events = 1; -} - -message eventID { - string ID = 1; -} - -message eventWithID { - string ID = 1; - event event = 2; -} - -message date { - google.protobuf.Timestamp date = 1; -} diff --git a/hw12_13_14_15_calendar/grpc/google/api/annotations.proto b/hw12_13_14_15_calendar/grpc/google/api/annotations.proto new file mode 100755 index 0000000..18dcf20 --- /dev/null +++ b/hw12_13_14_15_calendar/grpc/google/api/annotations.proto @@ -0,0 +1,31 @@ +// Copyright (c) 2015, Google Inc. +// +// 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/hw12_13_14_15_calendar/grpc/google/api/http.proto b/hw12_13_14_15_calendar/grpc/google/api/http.proto new file mode 100755 index 0000000..61168c3 --- /dev/null +++ b/hw12_13_14_15_calendar/grpc/google/api/http.proto @@ -0,0 +1,318 @@ +// Copyright 2018 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 parmeters 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; +} + +// `HttpRule` defines the mapping of an RPC method to one or more HTTP +// REST API methods. The mapping specifies how different portions of the RPC +// request message are mapped to URL path, URL query parameters, and +// HTTP request body. The mapping is typically specified as an +// `google.api.http` annotation on the RPC method, +// see "google/api/annotations.proto" for details. +// +// The mapping consists of a field specifying the path template and +// method kind. The path template can refer to fields in the request +// message, as in the example below which describes a REST GET +// operation on a resource collection of messages: +// +// +// service Messaging { +// rpc GetMessage(GetMessageRequest) returns (Message) { +// option (google.api.http).get = "/v1/messages/{message_id}/{sub.subfield}"; +// } +// } +// message GetMessageRequest { +// message SubMessage { +// string subfield = 1; +// } +// string message_id = 1; // mapped to the URL +// SubMessage sub = 2; // `sub.subfield` is url-mapped +// } +// message Message { +// string text = 1; // content of the resource +// } +// +// The same http annotation can alternatively be expressed inside the +// `GRPC API Configuration` YAML file. +// +// http: +// rules: +// - selector: .Messaging.GetMessage +// get: /v1/messages/{message_id}/{sub.subfield} +// +// This definition enables an automatic, bidrectional mapping of HTTP +// JSON to RPC. Example: +// +// HTTP | RPC +// -----|----- +// `GET /v1/messages/123456/foo` | `GetMessage(message_id: "123456" sub: SubMessage(subfield: "foo"))` +// +// In general, not only fields but also field paths can be referenced +// from a path pattern. Fields mapped to the path pattern cannot be +// repeated and must have a primitive (non-message) type. +// +// Any fields in the request message which are not bound by the path +// pattern automatically become (optional) HTTP query +// parameters. Assume the following definition of the request message: +// +// +// 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 the URL +// int64 revision = 2; // becomes a parameter +// SubMessage sub = 3; // `sub.subfield` becomes a parameter +// } +// +// +// This enables a HTTP JSON to RPC mapping as below: +// +// HTTP | RPC +// -----|----- +// `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 HTTP parameters must have a +// primitive type or a repeated primitive type. Message types are not +// allowed. In the case of a repeated type, the parameter can be +// repeated in the URL, as in `...?param=A¶m=B`. +// +// For HTTP method kinds which 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) = { +// put: "/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 | RPC +// -----|----- +// `PUT /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) = { +// put: "/v1/messages/{message_id}" +// body: "*" +// }; +// } +// } +// message Message { +// string message_id = 1; +// string text = 2; +// } +// +// +// The following HTTP JSON to RPC mapping is enabled: +// +// HTTP | RPC +// -----|----- +// `PUT /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 of +// 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 | RPC +// -----|----- +// `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 +// +// The rules for mapping HTTP path, query parameters, and body fields +// to the request message are as follows: +// +// 1. The `body` field specifies either `*` or a field path, or is +// omitted. If omitted, it indicates there is no HTTP request body. +// 2. Leaf fields (recursive expansion of nested messages in the +// request) can be classified into three types: +// (a) Matched in the URL template. +// (b) Covered by body (if body is `*`, everything except (a) fields; +// else everything under the body field) +// (c) All other fields. +// 3. URL query parameters found in the HTTP request are mapped to (c) fields. +// 4. Any body sent with an HTTP request can contain only (b) fields. +// +// The syntax of the path template is as follows: +// +// Template = "/" Segments [ Verb ] ; +// Segments = Segment { "/" Segment } ; +// Segment = "*" | "**" | LITERAL | Variable ; +// Variable = "{" FieldPath [ "=" Segments ] "}" ; +// FieldPath = IDENT { "." IDENT } ; +// Verb = ":" LITERAL ; +// +// The syntax `*` matches a single path segment. The syntax `**` matches zero +// or more path segments, which must be the last part of the path except the +// `Verb`. The syntax `LITERAL` matches literal text in the path. +// +// 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=*}`. +// +// If a variable contains exactly one path segment, such as `"{var}"` or +// `"{var=*}"`, when such a variable is expanded into a URL path, all characters +// except `[-_.~0-9a-zA-Z]` are percent-encoded. Such variables show up in the +// Discovery Document as `{var}`. +// +// If a variable contains one or more path segments, such as `"{var=foo/*}"` +// or `"{var=**}"`, when such a variable is expanded into a URL path, all +// characters except `[-_.~/0-9a-zA-Z]` are percent-encoded. Such variables +// show up in the Discovery Document as `{+var}`. +// +// NOTE: While the single segment variable matches the semantics of +// [RFC 6570](https://tools.ietf.org/html/rfc6570) Section 3.2.2 +// Simple String Expansion, the multi segment variable **does not** match +// RFC 6570 Reserved Expansion. The reason is that the Reserved Expansion +// does not expand special characters like `?` and `#`, which would lead +// to invalid URLs. +// +// NOTE: the field paths in variables and in the `body` must not refer to +// repeated fields or map fields. +message HttpRule { + // Selects methods 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 { + // Used for listing and getting information about resources. + string get = 2; + + // Used for updating a resource. + string put = 3; + + // Used for creating a resource. + string post = 4; + + // Used for deleting a resource. + string delete = 5; + + // 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 body, or + // `*` for mapping all fields not captured by the path pattern to the HTTP + // body. NOTE: the referred field must not be a repeated field and must be + // present at the top-level of request message type. + string body = 7; + + // Optional. The name of the response field whose value is mapped to the HTTP + // body of response. Other response fields are ignored. When + // not set, the response message will be used as HTTP body of response. + 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 diff --git a/hw12_13_14_15_calendar/grpc/google/api/httpbody.proto b/hw12_13_14_15_calendar/grpc/google/api/httpbody.proto new file mode 100755 index 0000000..4428515 --- /dev/null +++ b/hw12_13_14_15_calendar/grpc/google/api/httpbody.proto @@ -0,0 +1,78 @@ +// Copyright 2018 Google LLC. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +syntax = "proto3"; + +package google.api; + +import "google/protobuf/any.proto"; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/api/httpbody;httpbody"; +option java_multiple_files = true; +option java_outer_classname = "HttpBodyProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +// Message that represents an arbitrary HTTP body. It should only be used for +// payload formats that can't be represented as JSON, such as raw binary or +// an HTML page. +// +// +// This message can be used both in streaming and non-streaming API methods in +// the request as well as the response. +// +// It can be used as a top-level request field, which is convenient if one +// wants to extract parameters from either the URL or HTTP template into the +// request fields and also want access to the raw HTTP body. +// +// Example: +// +// message GetResourceRequest { +// // A unique request id. +// string request_id = 1; +// +// // The raw HTTP body is bound to this field. +// google.api.HttpBody http_body = 2; +// } +// +// service ResourceService { +// rpc GetResource(GetResourceRequest) returns (google.api.HttpBody); +// rpc UpdateResource(google.api.HttpBody) returns +// (google.protobuf.Empty); +// } +// +// Example with streaming methods: +// +// service CaldavService { +// rpc GetCalendar(stream google.api.HttpBody) +// returns (stream google.api.HttpBody); +// rpc UpdateCalendar(stream google.api.HttpBody) +// returns (stream google.api.HttpBody); +// } +// +// Use of this type only changes how the request and response bodies are +// handled, all other features will continue to work unchanged. +message HttpBody { + // The HTTP Content-Type header value specifying the content type of the body. + string content_type = 1; + + // The HTTP request/response body as raw binary. + bytes data = 2; + + // Application specific response metadata. Must be set in the first response + // for streaming APIs. + repeated google.protobuf.Any extensions = 3; +} \ No newline at end of file diff --git a/hw12_13_14_15_calendar/grpc/grpc.proto b/hw12_13_14_15_calendar/grpc/grpc.proto new file mode 100644 index 0000000..06fed34 --- /dev/null +++ b/hw12_13_14_15_calendar/grpc/grpc.proto @@ -0,0 +1,76 @@ +syntax = "proto3"; + + +import "google/protobuf/timestamp.proto"; +import "google/protobuf/duration.proto"; +import "google/protobuf/empty.proto"; +import "google/api/annotations.proto"; + +message Event { + string ID = 1; + string Title = 2; + google.protobuf.Timestamp Date = 3; + google.protobuf.Duration Latency = 4; + string Note = 5; + string UserID = 6; + google.protobuf.Duration NotifyTime = 7; +} + +message EventList { + repeated Event Events = 1; +} + +message EventID { + string ID = 1; +} + +message EventWthID { + string ID = 1; + Event Event = 2; +} + +enum QueryRange { + DAY = 0; + WEEK = 1; + MONTH = 2; +} + +message Date { + google.protobuf.Timestamp Date = 1; + QueryRange Range = 2; +} + +service grpc { + rpc Create(Event) returns (EventID) { + option (google.api.http) = { + post: "", + body: "*", + }; + } + rpc Update(EventWthID) returns (google.protobuf.Empty) { + option (google.api.http) = { + put: "/{ID}", + body: "*", + }; + } + rpc Delete(EventID) returns (google.protobuf.Empty) { + option (google.api.http) = { + delete: "/{ID}" + }; + } + rpc List(google.protobuf.Empty) returns (EventList) { + option (google.api.http) = { + get: "/event" + }; + } + rpc GetByID(EventID) returns (EventList) { + option (google.api.http) = { + get: "/{ID}" + }; + } + rpc GetByDate(Date) returns (EventList) { + option (google.api.http) = { + get: "/{Date}/{Range}" + }; + } +} \ No newline at end of file diff --git a/hw12_13_14_15_calendar/internal/grpc/calendar.pb.go b/hw12_13_14_15_calendar/internal/grpc/calendar.pb.go deleted file mode 100644 index 4d79a6b..0000000 --- a/hw12_13_14_15_calendar/internal/grpc/calendar.pb.go +++ /dev/null @@ -1,316 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: grpc/calendar.proto - -package event - -import ( - fmt "fmt" - proto "github.com/golang/protobuf/proto" - duration "github.com/golang/protobuf/ptypes/duration" - _ "github.com/golang/protobuf/ptypes/empty" - timestamp "github.com/golang/protobuf/ptypes/timestamp" - math "math" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package - -type Event struct { - ID string `protobuf:"bytes,1,opt,name=ID,proto3" json:"ID,omitempty"` - Title string `protobuf:"bytes,2,opt,name=title,proto3" json:"title,omitempty"` - Date *timestamp.Timestamp `protobuf:"bytes,3,opt,name=date,proto3" json:"date,omitempty"` - Latency *duration.Duration `protobuf:"bytes,4,opt,name=latency,proto3" json:"latency,omitempty"` - Note string `protobuf:"bytes,5,opt,name=note,proto3" json:"note,omitempty"` - UserID string `protobuf:"bytes,6,opt,name=UserID,proto3" json:"UserID,omitempty"` - NotyfyTime *duration.Duration `protobuf:"bytes,7,opt,name=notyfyTime,proto3" json:"notyfyTime,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Event) Reset() { *m = Event{} } -func (m *Event) String() string { return proto.CompactTextString(m) } -func (*Event) ProtoMessage() {} -func (*Event) Descriptor() ([]byte, []int) { - return fileDescriptor_b5d285f4b6d41dfd, []int{0} -} - -func (m *Event) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Event.Unmarshal(m, b) -} -func (m *Event) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Event.Marshal(b, m, deterministic) -} -func (m *Event) XXX_Merge(src proto.Message) { - xxx_messageInfo_Event.Merge(m, src) -} -func (m *Event) XXX_Size() int { - return xxx_messageInfo_Event.Size(m) -} -func (m *Event) XXX_DiscardUnknown() { - xxx_messageInfo_Event.DiscardUnknown(m) -} - -var xxx_messageInfo_Event proto.InternalMessageInfo - -func (m *Event) GetID() string { - if m != nil { - return m.ID - } - return "" -} - -func (m *Event) GetTitle() string { - if m != nil { - return m.Title - } - return "" -} - -func (m *Event) GetDate() *timestamp.Timestamp { - if m != nil { - return m.Date - } - return nil -} - -func (m *Event) GetLatency() *duration.Duration { - if m != nil { - return m.Latency - } - return nil -} - -func (m *Event) GetNote() string { - if m != nil { - return m.Note - } - return "" -} - -func (m *Event) GetUserID() string { - if m != nil { - return m.UserID - } - return "" -} - -func (m *Event) GetNotyfyTime() *duration.Duration { - if m != nil { - return m.NotyfyTime - } - return nil -} - -type EventList struct { - Events []*Event `protobuf:"bytes,1,rep,name=events,proto3" json:"events,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EventList) Reset() { *m = EventList{} } -func (m *EventList) String() string { return proto.CompactTextString(m) } -func (*EventList) ProtoMessage() {} -func (*EventList) Descriptor() ([]byte, []int) { - return fileDescriptor_b5d285f4b6d41dfd, []int{1} -} - -func (m *EventList) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EventList.Unmarshal(m, b) -} -func (m *EventList) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EventList.Marshal(b, m, deterministic) -} -func (m *EventList) XXX_Merge(src proto.Message) { - xxx_messageInfo_EventList.Merge(m, src) -} -func (m *EventList) XXX_Size() int { - return xxx_messageInfo_EventList.Size(m) -} -func (m *EventList) XXX_DiscardUnknown() { - xxx_messageInfo_EventList.DiscardUnknown(m) -} - -var xxx_messageInfo_EventList proto.InternalMessageInfo - -func (m *EventList) GetEvents() []*Event { - if m != nil { - return m.Events - } - return nil -} - -type EventID struct { - ID string `protobuf:"bytes,1,opt,name=ID,proto3" json:"ID,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EventID) Reset() { *m = EventID{} } -func (m *EventID) String() string { return proto.CompactTextString(m) } -func (*EventID) ProtoMessage() {} -func (*EventID) Descriptor() ([]byte, []int) { - return fileDescriptor_b5d285f4b6d41dfd, []int{2} -} - -func (m *EventID) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EventID.Unmarshal(m, b) -} -func (m *EventID) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EventID.Marshal(b, m, deterministic) -} -func (m *EventID) XXX_Merge(src proto.Message) { - xxx_messageInfo_EventID.Merge(m, src) -} -func (m *EventID) XXX_Size() int { - return xxx_messageInfo_EventID.Size(m) -} -func (m *EventID) XXX_DiscardUnknown() { - xxx_messageInfo_EventID.DiscardUnknown(m) -} - -var xxx_messageInfo_EventID proto.InternalMessageInfo - -func (m *EventID) GetID() string { - if m != nil { - return m.ID - } - return "" -} - -type EventWithID struct { - ID string `protobuf:"bytes,1,opt,name=ID,proto3" json:"ID,omitempty"` - Event *Event `protobuf:"bytes,2,opt,name=event,proto3" json:"event,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EventWithID) Reset() { *m = EventWithID{} } -func (m *EventWithID) String() string { return proto.CompactTextString(m) } -func (*EventWithID) ProtoMessage() {} -func (*EventWithID) Descriptor() ([]byte, []int) { - return fileDescriptor_b5d285f4b6d41dfd, []int{3} -} - -func (m *EventWithID) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EventWithID.Unmarshal(m, b) -} -func (m *EventWithID) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EventWithID.Marshal(b, m, deterministic) -} -func (m *EventWithID) XXX_Merge(src proto.Message) { - xxx_messageInfo_EventWithID.Merge(m, src) -} -func (m *EventWithID) XXX_Size() int { - return xxx_messageInfo_EventWithID.Size(m) -} -func (m *EventWithID) XXX_DiscardUnknown() { - xxx_messageInfo_EventWithID.DiscardUnknown(m) -} - -var xxx_messageInfo_EventWithID proto.InternalMessageInfo - -func (m *EventWithID) GetID() string { - if m != nil { - return m.ID - } - return "" -} - -func (m *EventWithID) GetEvent() *Event { - if m != nil { - return m.Event - } - return nil -} - -type Date struct { - Date *timestamp.Timestamp `protobuf:"bytes,1,opt,name=date,proto3" json:"date,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Date) Reset() { *m = Date{} } -func (m *Date) String() string { return proto.CompactTextString(m) } -func (*Date) ProtoMessage() {} -func (*Date) Descriptor() ([]byte, []int) { - return fileDescriptor_b5d285f4b6d41dfd, []int{4} -} - -func (m *Date) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Date.Unmarshal(m, b) -} -func (m *Date) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Date.Marshal(b, m, deterministic) -} -func (m *Date) XXX_Merge(src proto.Message) { - xxx_messageInfo_Date.Merge(m, src) -} -func (m *Date) XXX_Size() int { - return xxx_messageInfo_Date.Size(m) -} -func (m *Date) XXX_DiscardUnknown() { - xxx_messageInfo_Date.DiscardUnknown(m) -} - -var xxx_messageInfo_Date proto.InternalMessageInfo - -func (m *Date) GetDate() *timestamp.Timestamp { - if m != nil { - return m.Date - } - return nil -} - -func init() { - proto.RegisterType((*Event)(nil), "event.event") - proto.RegisterType((*EventList)(nil), "event.eventList") - proto.RegisterType((*EventID)(nil), "event.eventID") - proto.RegisterType((*EventWithID)(nil), "event.eventWithID") - proto.RegisterType((*Date)(nil), "event.date") -} - -func init() { proto.RegisterFile("grpc/calendar.proto", fileDescriptor_b5d285f4b6d41dfd) } - -var fileDescriptor_b5d285f4b6d41dfd = []byte{ - // 429 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x92, 0xdf, 0x8b, 0xd3, 0x40, - 0x10, 0xc7, 0x49, 0x7f, 0x24, 0x76, 0x22, 0x87, 0x8c, 0x72, 0xec, 0x45, 0xd0, 0x12, 0x44, 0xaa, - 0x07, 0xa9, 0xf6, 0x44, 0xf0, 0xd1, 0xeb, 0x8a, 0x04, 0x14, 0x24, 0x78, 0x1c, 0xf8, 0x96, 0x6b, - 0xe7, 0x7a, 0xc1, 0x34, 0x1b, 0xd2, 0x39, 0x21, 0x6f, 0xfe, 0xdb, 0xbe, 0x49, 0x66, 0x53, 0xa9, - 0xa9, 0x5a, 0x5f, 0xc2, 0xce, 0x7e, 0x3f, 0x3b, 0xdf, 0x9d, 0x6f, 0x16, 0xee, 0xaf, 0xaa, 0x72, - 0x31, 0x5d, 0xa4, 0x39, 0x15, 0xcb, 0xb4, 0x8a, 0xca, 0xca, 0xb0, 0xc1, 0x21, 0x7d, 0xa3, 0x82, - 0x83, 0xc7, 0x2b, 0x63, 0x56, 0x39, 0x4d, 0x65, 0xf3, 0xea, 0xf6, 0x7a, 0xca, 0xd9, 0x9a, 0x36, - 0x9c, 0xae, 0x4b, 0xcb, 0x05, 0x8f, 0xba, 0xc0, 0xf2, 0xb6, 0x4a, 0x39, 0x33, 0x45, 0xab, 0x3f, - 0xec, 0xea, 0xb4, 0x2e, 0xb9, 0xb6, 0x62, 0xf8, 0xc3, 0x01, 0xeb, 0x83, 0x47, 0xd0, 0x8b, 0xb5, - 0x72, 0xc6, 0xce, 0x64, 0x94, 0xf4, 0x62, 0x8d, 0x0f, 0x60, 0xc8, 0x19, 0xe7, 0xa4, 0x7a, 0xb2, - 0x65, 0x0b, 0x8c, 0x60, 0xb0, 0x4c, 0x99, 0x54, 0x7f, 0xec, 0x4c, 0xfc, 0x59, 0x10, 0xd9, 0xde, - 0xd1, 0xb6, 0x77, 0xf4, 0x79, 0x7b, 0xb9, 0x44, 0x38, 0x3c, 0x03, 0x2f, 0x4f, 0x99, 0x8a, 0x45, - 0xad, 0x06, 0x72, 0xe4, 0x64, 0xef, 0x88, 0x6e, 0xaf, 0x9b, 0x6c, 0x49, 0x44, 0x18, 0x14, 0x86, - 0x49, 0x0d, 0xc5, 0x59, 0xd6, 0x78, 0x0c, 0xee, 0xc5, 0x86, 0xaa, 0x58, 0x2b, 0x57, 0x76, 0xdb, - 0x0a, 0xdf, 0x00, 0x14, 0x86, 0xeb, 0xeb, 0xba, 0x71, 0x56, 0xde, 0x21, 0x8f, 0x1d, 0x38, 0x7c, - 0x09, 0x23, 0x19, 0xfd, 0x43, 0xb6, 0x61, 0x7c, 0x02, 0xae, 0x14, 0x1b, 0xe5, 0x8c, 0xfb, 0x13, - 0x7f, 0x76, 0x37, 0x92, 0xd2, 0x7e, 0x93, 0x56, 0x0b, 0x4f, 0xc0, 0x93, 0x55, 0xac, 0xbb, 0x79, - 0x85, 0x6f, 0xc1, 0x17, 0xe9, 0x32, 0xe3, 0x9b, 0x7d, 0x19, 0xc3, 0x36, 0x67, 0x89, 0xb3, 0xdb, - 0xde, 0x4a, 0xe1, 0x6b, 0x1b, 0xee, 0xaf, 0x90, 0x9d, 0xff, 0x0b, 0x79, 0xf6, 0xbd, 0x0f, 0xfe, - 0xbc, 0x7d, 0x3c, 0xc9, 0xa7, 0x39, 0x3e, 0x05, 0x77, 0x5e, 0x51, 0xd3, 0xe9, 0x37, 0x9b, 0xe0, - 0x68, 0xb7, 0x8a, 0x35, 0xbe, 0x02, 0xf7, 0xa2, 0x14, 0x47, 0xdc, 0x55, 0xec, 0x04, 0xc1, 0xf1, - 0x9e, 0xef, 0xbb, 0xe6, 0xe1, 0xe0, 0x0b, 0x70, 0x35, 0xe5, 0xc4, 0x84, 0x9d, 0x7e, 0xff, 0x38, - 0x31, 0x90, 0x8c, 0xff, 0xa2, 0x07, 0xf7, 0x76, 0xfb, 0x08, 0x79, 0x0a, 0xde, 0x7b, 0xe2, 0xf3, - 0xba, 0x09, 0xb2, 0x63, 0xb2, 0x0f, 0x3f, 0x83, 0x3b, 0x02, 0xeb, 0xb4, 0x46, 0xbf, 0x55, 0x9b, - 0xa9, 0xfe, 0x80, 0x3e, 0x87, 0x91, 0xa0, 0x97, 0x44, 0x5f, 0x0f, 0xb1, 0xa7, 0x00, 0xc2, 0x7e, - 0x34, 0x05, 0xdf, 0x1c, 0x80, 0xcf, 0xbd, 0x2f, 0xf6, 0x1f, 0x5e, 0xb9, 0x32, 0xdb, 0xd9, 0xcf, - 0x00, 0x00, 0x00, 0xff, 0xff, 0xb3, 0xa8, 0x5f, 0x40, 0xd3, 0x03, 0x00, 0x00, -} diff --git a/hw12_13_14_15_calendar/internal/server/grpc/grpc.go b/hw12_13_14_15_calendar/internal/server/grpc/grpc.go new file mode 100644 index 0000000..f08c952 --- /dev/null +++ b/hw12_13_14_15_calendar/internal/server/grpc/grpc.go @@ -0,0 +1,16 @@ +package grpc + +import ( + "context" + "github.com/golang/protobuf/ptypes/empty" + "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/grpc" +) + +type Service struct{} + +func (s Service) Create(context.Context, *grpc.Event) (*grpc.EventID, error) {} +func (s Service) Update(context.Context, *grpc.EventWthID) (*empty.Empty, error) {} +func (s Service) Delete(context.Context, *grpc.EventID) (*empty.Empty, error) {} +func (s Service) List(context.Context, *empty.Empty) (*grpc.EventList, error) {} +func (s Service) GetByID(context.Context, *grpc.EventID) (*grpc.EventList, error) {} +func (s Service) GetByDate(context.Context, *grpc.Date) (*grpc.EventList, error) {} diff --git a/hw12_13_14_15_calendar/internal/server/http/server.go b/hw12_13_14_15_calendar/internal/server/http/http.go similarity index 100% rename from hw12_13_14_15_calendar/internal/server/http/server.go rename to hw12_13_14_15_calendar/internal/server/http/http.go diff --git a/hw12_13_14_15_calendar/internal/storage/memory/memory.go b/hw12_13_14_15_calendar/internal/storage/memory/memory.go index 48ad73a..09bff9b 100644 --- a/hw12_13_14_15_calendar/internal/storage/memory/memory.go +++ b/hw12_13_14_15_calendar/internal/storage/memory/memory.go @@ -2,6 +2,7 @@ package memory import ( "sync" + "time" "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/storage/event" ) @@ -48,3 +49,31 @@ func (s *Storage) GetByID(id event.ID) (event.Event, bool) { } return s.Events[id], true } + +func (s *Storage) GetByDate(startDate time.Time, rng string) (map[event.ID]event.Event, error) { + endDate := getEndDate(startDate, rng) + s.Mu.Lock() + defer s.Mu.Unlock() + res := make(map[event.ID]event.Event) + for k, v := range s.Events { + if (v.Date.After(startDate) && v.Date.Before(endDate)) || + (v.Date.Add(v.Latency).Before(v.Date) && v.Date.Add(v.Latency).After(v.Date)) || + (v.Date.Before(startDate)) && (v.Date.Add(v.Latency).After(endDate)) { + res[k] = v + } + } + return res, nil +} + +func getEndDate(startDate time.Time, rng string) time.Time { + switch rng { + case "DAY": + return startDate.AddDate(0, 0, 1) + case "WEEK": + return startDate.AddDate(0, 0, 7) + case "MONTH": + return startDate.AddDate(0, 1, 0) + default: + return startDate + } +} diff --git a/hw12_13_14_15_calendar/internal/storage/sql/sql.go b/hw12_13_14_15_calendar/internal/storage/sql/sql.go index 316c5b8..97667ea 100644 --- a/hw12_13_14_15_calendar/internal/storage/sql/sql.go +++ b/hw12_13_14_15_calendar/internal/storage/sql/sql.go @@ -123,3 +123,51 @@ func (s *Storage) GetByID(id event.ID) (event.Event, bool) { res.Date = dateParced return res, true } + +func (s *Storage) GetByDate(startDate time.Time, rng string) (map[event.ID]event.Event, error) { + res := make(map[event.ID]event.Event) + results, err := s.db.Query( + `SELECT (id,title,date,latency,note,userID,notifyTime) + from events + where (date>$1 AND date<$2) OR + (date+latency>$1 AND date+latency<$2) OR + (date<$1 AND date+latency>$2) + ORDER BY id`, + startDate, + getEndDate(startDate, rng)) + if err != nil { + return nil, err + } + defer results.Close() + for results.Next() { + var id event.ID + var evt event.Event + var dateRaw string + err = results.Scan(&id, &evt.Title, &dateRaw, &evt.Latency, &evt.Note, &evt.UserID, &evt.NotifyTime) + if err != nil { + return nil, err + } + evt.Date, err = time.Parse(dateTimeLayout, dateRaw) + if err != nil { + return nil, err + } + res[id] = evt + } + if results.Err() != nil { + return nil, results.Err() + } + return res, nil +} + +func getEndDate(startDate time.Time, rng string) time.Time { + switch rng { + case "DAY": + return startDate.AddDate(0, 0, 1) + case "WEEK": + return startDate.AddDate(0, 0, 7) + case "MONTH": + return startDate.AddDate(0, 1, 0) + default: + return startDate + } +} diff --git a/hw12_13_14_15_calendar/internal/storage/store.go b/hw12_13_14_15_calendar/internal/storage/store.go index 5341c20..f729539 100644 --- a/hw12_13_14_15_calendar/internal/storage/store.go +++ b/hw12_13_14_15_calendar/internal/storage/store.go @@ -4,6 +4,7 @@ import ( "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/storage/event" memorystorage "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/storage/memory" sqlstorage "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/storage/sql" + "time" ) type Config struct { @@ -16,11 +17,12 @@ type Config struct { } type StorageInterface interface { - Create(event event.Event) (event.ID, error) - Update(id event.ID, event event.Event) error - Delete(id event.ID) error + Create(event.Event) (event.ID, error) + Update(event.ID, event.Event) error + Delete(event.ID) error List() (map[event.ID]event.Event, error) - GetByID(id event.ID) (event.Event, bool) + GetByID(event.ID) (event.Event, bool) + GetByDate(time.Time, string) (map[event.ID]event.Event, error) } func NewStore(conf Config) StorageInterface { From 9c5086d1459a63cc74c4ea64be9037c97287ceab Mon Sep 17 00:00:00 2001 From: Andrey Ivanov Date: Thu, 1 Oct 2020 10:11:21 +0300 Subject: [PATCH 05/16] HW13 WIP --- hw12_13_14_15_calendar/Makefile | 7 +---- .../internal/server/grpc/grpc.go | 29 +++++++++++++++---- 2 files changed, 24 insertions(+), 12 deletions(-) diff --git a/hw12_13_14_15_calendar/Makefile b/hw12_13_14_15_calendar/Makefile index 400c362..84c3ed7 100644 --- a/hw12_13_14_15_calendar/Makefile +++ b/hw12_13_14_15_calendar/Makefile @@ -16,11 +16,6 @@ install-lint-deps: (which golangci-lint > /dev/null) || curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(shell go env GOPATH)/bin v1.30.0 generate: - protoc --go_out=grpc:internal grpc/calendar.proto - -gen2: - protoc -I /usr/local/include -I ${cdir}/grpc --go_out=plugins=grpc:${cdir}/internal/grpc \ - --grpc-gateway_out=logtostderr=true:${cdir}/internal/grpc \ - ${cdir}/grpc/grpc.proto + protoc -I ./grpc --go_out=plugins=grpc:./internal/grpc --grpc-gateway_out=logtostderr=true:./internal/grpc ./grpc/grpc.proto .PHONY: build run test lint \ No newline at end of file diff --git a/hw12_13_14_15_calendar/internal/server/grpc/grpc.go b/hw12_13_14_15_calendar/internal/server/grpc/grpc.go index f08c952..d2faa57 100644 --- a/hw12_13_14_15_calendar/internal/server/grpc/grpc.go +++ b/hw12_13_14_15_calendar/internal/server/grpc/grpc.go @@ -8,9 +8,26 @@ import ( type Service struct{} -func (s Service) Create(context.Context, *grpc.Event) (*grpc.EventID, error) {} -func (s Service) Update(context.Context, *grpc.EventWthID) (*empty.Empty, error) {} -func (s Service) Delete(context.Context, *grpc.EventID) (*empty.Empty, error) {} -func (s Service) List(context.Context, *empty.Empty) (*grpc.EventList, error) {} -func (s Service) GetByID(context.Context, *grpc.EventID) (*grpc.EventList, error) {} -func (s Service) GetByDate(context.Context, *grpc.Date) (*grpc.EventList, error) {} +func (s Service) Create(context.Context, *grpc.Event) (*grpc.EventID, error) { + return nil, nil +} + +func (s Service) Update(context.Context, *grpc.EventWthID) (*empty.Empty, error) { + return nil, nil +} + +func (s Service) Delete(context.Context, *grpc.EventID) (*empty.Empty, error) { + return nil, nil +} + +func (s Service) List(context.Context, *empty.Empty) (*grpc.EventList, error) { + return nil, nil +} + +func (s Service) GetByID(context.Context, *grpc.EventID) (*grpc.EventList, error) { + return nil, nil +} + +func (s Service) GetByDate(context.Context, *grpc.Date) (*grpc.EventList, error) { + return nil, nil +} From 9502e665e2b42eefa98036358dec35975da8e96e Mon Sep 17 00:00:00 2001 From: Andrey Ivanov Date: Wed, 7 Oct 2020 14:17:35 +0300 Subject: [PATCH 06/16] HW13 WIP --- .gitignore | 1 + .../internal/grpc/grpc.pb.go | 624 ++++++++++++++++++ .../internal/grpc/grpc.pb.gw.go | 334 ++++++++++ 3 files changed, 959 insertions(+) create mode 100644 hw12_13_14_15_calendar/internal/grpc/grpc.pb.go create mode 100644 hw12_13_14_15_calendar/internal/grpc/grpc.pb.gw.go diff --git a/.gitignore b/.gitignore index 3ee24cd..e4bb223 100644 --- a/.gitignore +++ b/.gitignore @@ -24,3 +24,4 @@ go-telnet .Trashes ehthumbs.db Thumbs.db +/hw12_13_14_15_calendar/calendar.log diff --git a/hw12_13_14_15_calendar/internal/grpc/grpc.pb.go b/hw12_13_14_15_calendar/internal/grpc/grpc.pb.go new file mode 100644 index 0000000..8a49203 --- /dev/null +++ b/hw12_13_14_15_calendar/internal/grpc/grpc.pb.go @@ -0,0 +1,624 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// source: grpc.proto + +package grpc + +import ( + context "context" + fmt "fmt" + proto "github.com/golang/protobuf/proto" + duration "github.com/golang/protobuf/ptypes/duration" + empty "github.com/golang/protobuf/ptypes/empty" + timestamp "github.com/golang/protobuf/ptypes/timestamp" + _ "google.golang.org/genproto/googleapis/api/annotations" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" + math "math" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package + +type QueryRange int32 + +const ( + QueryRange_DAY QueryRange = 0 + QueryRange_WEEK QueryRange = 1 + QueryRange_MONTH QueryRange = 2 +) + +var QueryRange_name = map[int32]string{ + 0: "DAY", + 1: "WEEK", + 2: "MONTH", +} + +var QueryRange_value = map[string]int32{ + "DAY": 0, + "WEEK": 1, + "MONTH": 2, +} + +func (x QueryRange) String() string { + return proto.EnumName(QueryRange_name, int32(x)) +} + +func (QueryRange) EnumDescriptor() ([]byte, []int) { + return fileDescriptor_bedfbfc9b54e5600, []int{0} +} + +type Event struct { + ID string `protobuf:"bytes,1,opt,name=ID,proto3" json:"ID,omitempty"` + Title string `protobuf:"bytes,2,opt,name=Title,proto3" json:"Title,omitempty"` + Date *timestamp.Timestamp `protobuf:"bytes,3,opt,name=Date,proto3" json:"Date,omitempty"` + Latency *duration.Duration `protobuf:"bytes,4,opt,name=Latency,proto3" json:"Latency,omitempty"` + Note string `protobuf:"bytes,5,opt,name=Note,proto3" json:"Note,omitempty"` + UserID string `protobuf:"bytes,6,opt,name=UserID,proto3" json:"UserID,omitempty"` + NotifyTime *duration.Duration `protobuf:"bytes,7,opt,name=NotifyTime,proto3" json:"NotifyTime,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *Event) Reset() { *m = Event{} } +func (m *Event) String() string { return proto.CompactTextString(m) } +func (*Event) ProtoMessage() {} +func (*Event) Descriptor() ([]byte, []int) { + return fileDescriptor_bedfbfc9b54e5600, []int{0} +} + +func (m *Event) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_Event.Unmarshal(m, b) +} +func (m *Event) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_Event.Marshal(b, m, deterministic) +} +func (m *Event) XXX_Merge(src proto.Message) { + xxx_messageInfo_Event.Merge(m, src) +} +func (m *Event) XXX_Size() int { + return xxx_messageInfo_Event.Size(m) +} +func (m *Event) XXX_DiscardUnknown() { + xxx_messageInfo_Event.DiscardUnknown(m) +} + +var xxx_messageInfo_Event proto.InternalMessageInfo + +func (m *Event) GetID() string { + if m != nil { + return m.ID + } + return "" +} + +func (m *Event) GetTitle() string { + if m != nil { + return m.Title + } + return "" +} + +func (m *Event) GetDate() *timestamp.Timestamp { + if m != nil { + return m.Date + } + return nil +} + +func (m *Event) GetLatency() *duration.Duration { + if m != nil { + return m.Latency + } + return nil +} + +func (m *Event) GetNote() string { + if m != nil { + return m.Note + } + return "" +} + +func (m *Event) GetUserID() string { + if m != nil { + return m.UserID + } + return "" +} + +func (m *Event) GetNotifyTime() *duration.Duration { + if m != nil { + return m.NotifyTime + } + return nil +} + +type EventList struct { + Events []*Event `protobuf:"bytes,1,rep,name=Events,proto3" json:"Events,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *EventList) Reset() { *m = EventList{} } +func (m *EventList) String() string { return proto.CompactTextString(m) } +func (*EventList) ProtoMessage() {} +func (*EventList) Descriptor() ([]byte, []int) { + return fileDescriptor_bedfbfc9b54e5600, []int{1} +} + +func (m *EventList) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_EventList.Unmarshal(m, b) +} +func (m *EventList) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_EventList.Marshal(b, m, deterministic) +} +func (m *EventList) XXX_Merge(src proto.Message) { + xxx_messageInfo_EventList.Merge(m, src) +} +func (m *EventList) XXX_Size() int { + return xxx_messageInfo_EventList.Size(m) +} +func (m *EventList) XXX_DiscardUnknown() { + xxx_messageInfo_EventList.DiscardUnknown(m) +} + +var xxx_messageInfo_EventList proto.InternalMessageInfo + +func (m *EventList) GetEvents() []*Event { + if m != nil { + return m.Events + } + return nil +} + +type EventID struct { + ID string `protobuf:"bytes,1,opt,name=ID,proto3" json:"ID,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *EventID) Reset() { *m = EventID{} } +func (m *EventID) String() string { return proto.CompactTextString(m) } +func (*EventID) ProtoMessage() {} +func (*EventID) Descriptor() ([]byte, []int) { + return fileDescriptor_bedfbfc9b54e5600, []int{2} +} + +func (m *EventID) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_EventID.Unmarshal(m, b) +} +func (m *EventID) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_EventID.Marshal(b, m, deterministic) +} +func (m *EventID) XXX_Merge(src proto.Message) { + xxx_messageInfo_EventID.Merge(m, src) +} +func (m *EventID) XXX_Size() int { + return xxx_messageInfo_EventID.Size(m) +} +func (m *EventID) XXX_DiscardUnknown() { + xxx_messageInfo_EventID.DiscardUnknown(m) +} + +var xxx_messageInfo_EventID proto.InternalMessageInfo + +func (m *EventID) GetID() string { + if m != nil { + return m.ID + } + return "" +} + +type EventWthID struct { + ID string `protobuf:"bytes,1,opt,name=ID,proto3" json:"ID,omitempty"` + Event *Event `protobuf:"bytes,2,opt,name=Event,proto3" json:"Event,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *EventWthID) Reset() { *m = EventWthID{} } +func (m *EventWthID) String() string { return proto.CompactTextString(m) } +func (*EventWthID) ProtoMessage() {} +func (*EventWthID) Descriptor() ([]byte, []int) { + return fileDescriptor_bedfbfc9b54e5600, []int{3} +} + +func (m *EventWthID) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_EventWthID.Unmarshal(m, b) +} +func (m *EventWthID) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_EventWthID.Marshal(b, m, deterministic) +} +func (m *EventWthID) XXX_Merge(src proto.Message) { + xxx_messageInfo_EventWthID.Merge(m, src) +} +func (m *EventWthID) XXX_Size() int { + return xxx_messageInfo_EventWthID.Size(m) +} +func (m *EventWthID) XXX_DiscardUnknown() { + xxx_messageInfo_EventWthID.DiscardUnknown(m) +} + +var xxx_messageInfo_EventWthID proto.InternalMessageInfo + +func (m *EventWthID) GetID() string { + if m != nil { + return m.ID + } + return "" +} + +func (m *EventWthID) GetEvent() *Event { + if m != nil { + return m.Event + } + return nil +} + +type Date struct { + Date *timestamp.Timestamp `protobuf:"bytes,1,opt,name=Date,proto3" json:"Date,omitempty"` + Range QueryRange `protobuf:"varint,2,opt,name=Range,proto3,enum=QueryRange" json:"Range,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *Date) Reset() { *m = Date{} } +func (m *Date) String() string { return proto.CompactTextString(m) } +func (*Date) ProtoMessage() {} +func (*Date) Descriptor() ([]byte, []int) { + return fileDescriptor_bedfbfc9b54e5600, []int{4} +} + +func (m *Date) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_Date.Unmarshal(m, b) +} +func (m *Date) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_Date.Marshal(b, m, deterministic) +} +func (m *Date) XXX_Merge(src proto.Message) { + xxx_messageInfo_Date.Merge(m, src) +} +func (m *Date) XXX_Size() int { + return xxx_messageInfo_Date.Size(m) +} +func (m *Date) XXX_DiscardUnknown() { + xxx_messageInfo_Date.DiscardUnknown(m) +} + +var xxx_messageInfo_Date proto.InternalMessageInfo + +func (m *Date) GetDate() *timestamp.Timestamp { + if m != nil { + return m.Date + } + return nil +} + +func (m *Date) GetRange() QueryRange { + if m != nil { + return m.Range + } + return QueryRange_DAY +} + +func init() { + proto.RegisterEnum("QueryRange", QueryRange_name, QueryRange_value) + proto.RegisterType((*Event)(nil), "Event") + proto.RegisterType((*EventList)(nil), "EventList") + proto.RegisterType((*EventID)(nil), "EventID") + proto.RegisterType((*EventWthID)(nil), "EventWthID") + proto.RegisterType((*Date)(nil), "Date") +} + +func init() { proto.RegisterFile("grpc.proto", fileDescriptor_bedfbfc9b54e5600) } + +var fileDescriptor_bedfbfc9b54e5600 = []byte{ + // 516 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x52, 0xcd, 0x6e, 0xd3, 0x4c, + 0x14, 0xad, 0x1d, 0xff, 0x24, 0x37, 0xfa, 0xf2, 0x85, 0x2b, 0x54, 0x5c, 0x53, 0x95, 0xe0, 0x0d, + 0x51, 0x90, 0xc6, 0x52, 0xba, 0x40, 0xcd, 0x06, 0x01, 0x13, 0x81, 0x45, 0x09, 0xc2, 0x4a, 0x55, + 0x75, 0xe9, 0xb6, 0xd3, 0x60, 0x29, 0xb1, 0x2d, 0x67, 0x82, 0x14, 0x45, 0xd9, 0xf0, 0x0a, 0xbc, + 0x18, 0x12, 0xaf, 0xc0, 0x4b, 0xb0, 0x43, 0xbe, 0x9e, 0xfc, 0x90, 0xa8, 0x82, 0x95, 0x7d, 0xef, + 0x39, 0x67, 0xce, 0xbd, 0x67, 0x06, 0x60, 0x94, 0x67, 0x37, 0x2c, 0xcb, 0x53, 0x99, 0xba, 0x4f, + 0x46, 0x69, 0x3a, 0x1a, 0x0b, 0x9f, 0xaa, 0xeb, 0xd9, 0x9d, 0x2f, 0xe3, 0x89, 0x98, 0xca, 0x68, + 0x92, 0x29, 0xc2, 0xc9, 0x2e, 0xe1, 0x76, 0x96, 0x47, 0x32, 0x4e, 0x13, 0x85, 0x3f, 0xde, 0xc5, + 0xc5, 0x24, 0x93, 0x73, 0x05, 0x1e, 0x2b, 0x30, 0xca, 0x62, 0x3f, 0x4a, 0x92, 0x54, 0x92, 0x72, + 0x5a, 0xa2, 0xde, 0x2f, 0x0d, 0xcc, 0xfe, 0x17, 0x91, 0x48, 0x6c, 0x80, 0x1e, 0x70, 0x47, 0x6b, + 0x69, 0xed, 0x5a, 0xa8, 0x07, 0x1c, 0x1f, 0x82, 0x39, 0x8c, 0xe5, 0x58, 0x38, 0x3a, 0xb5, 0xca, + 0x02, 0x19, 0x18, 0x3c, 0x92, 0xc2, 0xa9, 0xb4, 0xb4, 0x76, 0xbd, 0xeb, 0xb2, 0xf2, 0x70, 0xb6, + 0x72, 0x66, 0xc3, 0xd5, 0xe8, 0x21, 0xf1, 0xf0, 0x14, 0xec, 0xf3, 0x48, 0x8a, 0xe4, 0x66, 0xee, + 0x18, 0x24, 0x39, 0xda, 0x93, 0x70, 0xb5, 0x4c, 0xb8, 0x62, 0x22, 0x82, 0x31, 0x48, 0xa5, 0x70, + 0x4c, 0x72, 0xa6, 0x7f, 0x3c, 0x04, 0xeb, 0x62, 0x2a, 0xf2, 0x80, 0x3b, 0x16, 0x75, 0x55, 0x85, + 0x67, 0x00, 0x83, 0x54, 0xc6, 0x77, 0xf3, 0xc2, 0xd9, 0xb1, 0xff, 0xe6, 0xb1, 0x45, 0xf6, 0x9e, + 0x43, 0x8d, 0x56, 0x3f, 0x8f, 0xa7, 0x12, 0x4f, 0xc0, 0xa2, 0x62, 0xea, 0x68, 0xad, 0x4a, 0xbb, + 0xde, 0xb5, 0x18, 0x95, 0xa1, 0xea, 0x7a, 0x47, 0x60, 0xd3, 0x5f, 0xc0, 0x77, 0x93, 0xf2, 0x7a, + 0x00, 0x04, 0x5d, 0xca, 0xcf, 0xfb, 0x28, 0x1e, 0xab, 0x80, 0x29, 0xc7, 0xcd, 0xb9, 0x65, 0xd3, + 0xbb, 0x2a, 0xf3, 0x5c, 0xe7, 0xaa, 0xfd, 0x63, 0xae, 0x4f, 0xc1, 0x0c, 0xa3, 0x64, 0x54, 0xde, + 0x4e, 0xa3, 0x5b, 0x67, 0x9f, 0x66, 0x22, 0x9f, 0x53, 0x2b, 0x2c, 0x91, 0x4e, 0x07, 0x60, 0xd3, + 0x44, 0x1b, 0x2a, 0xfc, 0xd5, 0x55, 0xf3, 0x00, 0xab, 0x60, 0x5c, 0xf6, 0xfb, 0xef, 0x9b, 0x1a, + 0xd6, 0xc0, 0xfc, 0xf0, 0x71, 0x30, 0x7c, 0xd7, 0xd4, 0xbb, 0xdf, 0x75, 0x30, 0x8a, 0x17, 0x89, + 0xcf, 0xc0, 0x7a, 0x93, 0x8b, 0xc2, 0x41, 0x0d, 0xea, 0x56, 0x99, 0xda, 0xdb, 0xab, 0x7f, 0xfd, + 0xf1, 0xf3, 0x9b, 0x6e, 0x7a, 0x07, 0x3d, 0xad, 0x83, 0x2f, 0xc1, 0xba, 0xc8, 0x6e, 0x0b, 0x62, + 0x9d, 0x6d, 0xb6, 0x77, 0x0f, 0xf7, 0x26, 0xef, 0x17, 0x6f, 0xd1, 0x6b, 0x92, 0x16, 0x5c, 0xd3, + 0x5f, 0x04, 0x7c, 0x59, 0x1c, 0x70, 0x06, 0x16, 0x17, 0x63, 0x21, 0x05, 0xae, 0x1d, 0xee, 0x55, + 0xff, 0x47, 0x6a, 0xbb, 0x53, 0xaa, 0xb1, 0x07, 0x06, 0xdd, 0xd9, 0x3d, 0x74, 0x17, 0xd8, 0xfa, + 0x5e, 0xbd, 0x06, 0x49, 0xab, 0x68, 0xf9, 0x82, 0x9e, 0x39, 0x03, 0xfb, 0xad, 0x90, 0xaf, 0xe7, + 0x01, 0xdf, 0xf2, 0xdd, 0x16, 0x28, 0x2f, 0x54, 0x5e, 0x2f, 0xa0, 0x46, 0x7c, 0x4a, 0xdd, 0x64, + 0xc5, 0xe7, 0x0f, 0xfa, 0x23, 0xa2, 0x3f, 0xc0, 0xff, 0xfd, 0x45, 0x81, 0x2d, 0xfd, 0x05, 0xe5, + 0xbd, 0xbc, 0xb6, 0x68, 0xa8, 0xd3, 0xdf, 0x01, 0x00, 0x00, 0xff, 0xff, 0xcc, 0x6d, 0x1a, 0xc6, + 0xea, 0x03, 0x00, 0x00, +} + +// Reference imports to suppress errors if they are not otherwise used. +var _ context.Context +var _ grpc.ClientConn + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +const _ = grpc.SupportPackageIsVersion4 + +// GrpcClient is the client API for Grpc service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. +type GrpcClient interface { + Create(ctx context.Context, in *Event, opts ...grpc.CallOption) (*EventID, error) + Update(ctx context.Context, in *EventWthID, opts ...grpc.CallOption) (*empty.Empty, error) + Delete(ctx context.Context, in *EventID, opts ...grpc.CallOption) (*empty.Empty, error) + List(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*EventList, error) + GetByID(ctx context.Context, in *EventID, opts ...grpc.CallOption) (*EventList, error) + GetByDate(ctx context.Context, in *Date, opts ...grpc.CallOption) (*EventList, error) +} + +type grpcClient struct { + cc *grpc.ClientConn +} + +func NewGrpcClient(cc *grpc.ClientConn) GrpcClient { + return &grpcClient{cc} +} + +func (c *grpcClient) Create(ctx context.Context, in *Event, opts ...grpc.CallOption) (*EventID, error) { + out := new(EventID) + err := c.cc.Invoke(ctx, "/grpc/Create", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *grpcClient) Update(ctx context.Context, in *EventWthID, opts ...grpc.CallOption) (*empty.Empty, error) { + out := new(empty.Empty) + err := c.cc.Invoke(ctx, "/grpc/Update", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *grpcClient) Delete(ctx context.Context, in *EventID, opts ...grpc.CallOption) (*empty.Empty, error) { + out := new(empty.Empty) + err := c.cc.Invoke(ctx, "/grpc/Delete", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *grpcClient) List(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*EventList, error) { + out := new(EventList) + err := c.cc.Invoke(ctx, "/grpc/List", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *grpcClient) GetByID(ctx context.Context, in *EventID, opts ...grpc.CallOption) (*EventList, error) { + out := new(EventList) + err := c.cc.Invoke(ctx, "/grpc/GetByID", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *grpcClient) GetByDate(ctx context.Context, in *Date, opts ...grpc.CallOption) (*EventList, error) { + out := new(EventList) + err := c.cc.Invoke(ctx, "/grpc/GetByDate", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// GrpcServer is the server API for Grpc service. +type GrpcServer interface { + Create(context.Context, *Event) (*EventID, error) + Update(context.Context, *EventWthID) (*empty.Empty, error) + Delete(context.Context, *EventID) (*empty.Empty, error) + List(context.Context, *empty.Empty) (*EventList, error) + GetByID(context.Context, *EventID) (*EventList, error) + GetByDate(context.Context, *Date) (*EventList, error) +} + +// UnimplementedGrpcServer can be embedded to have forward compatible implementations. +type UnimplementedGrpcServer struct { +} + +func (*UnimplementedGrpcServer) Create(ctx context.Context, req *Event) (*EventID, error) { + return nil, status.Errorf(codes.Unimplemented, "method Create not implemented") +} +func (*UnimplementedGrpcServer) Update(ctx context.Context, req *EventWthID) (*empty.Empty, error) { + return nil, status.Errorf(codes.Unimplemented, "method Update not implemented") +} +func (*UnimplementedGrpcServer) Delete(ctx context.Context, req *EventID) (*empty.Empty, error) { + return nil, status.Errorf(codes.Unimplemented, "method Delete not implemented") +} +func (*UnimplementedGrpcServer) List(ctx context.Context, req *empty.Empty) (*EventList, error) { + return nil, status.Errorf(codes.Unimplemented, "method List not implemented") +} +func (*UnimplementedGrpcServer) GetByID(ctx context.Context, req *EventID) (*EventList, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetByID not implemented") +} +func (*UnimplementedGrpcServer) GetByDate(ctx context.Context, req *Date) (*EventList, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetByDate not implemented") +} + +func RegisterGrpcServer(s *grpc.Server, srv GrpcServer) { + s.RegisterService(&_Grpc_serviceDesc, srv) +} + +func _Grpc_Create_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(Event) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(GrpcServer).Create(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/grpc/Create", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(GrpcServer).Create(ctx, req.(*Event)) + } + return interceptor(ctx, in, info, handler) +} + +func _Grpc_Update_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(EventWthID) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(GrpcServer).Update(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/grpc/Update", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(GrpcServer).Update(ctx, req.(*EventWthID)) + } + return interceptor(ctx, in, info, handler) +} + +func _Grpc_Delete_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(EventID) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(GrpcServer).Delete(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/grpc/Delete", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(GrpcServer).Delete(ctx, req.(*EventID)) + } + return interceptor(ctx, in, info, handler) +} + +func _Grpc_List_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(empty.Empty) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(GrpcServer).List(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/grpc/List", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(GrpcServer).List(ctx, req.(*empty.Empty)) + } + return interceptor(ctx, in, info, handler) +} + +func _Grpc_GetByID_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(EventID) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(GrpcServer).GetByID(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/grpc/GetByID", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(GrpcServer).GetByID(ctx, req.(*EventID)) + } + return interceptor(ctx, in, info, handler) +} + +func _Grpc_GetByDate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(Date) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(GrpcServer).GetByDate(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/grpc/GetByDate", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(GrpcServer).GetByDate(ctx, req.(*Date)) + } + return interceptor(ctx, in, info, handler) +} + +var _Grpc_serviceDesc = grpc.ServiceDesc{ + ServiceName: "grpc", + HandlerType: (*GrpcServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "Create", + Handler: _Grpc_Create_Handler, + }, + { + MethodName: "Update", + Handler: _Grpc_Update_Handler, + }, + { + MethodName: "Delete", + Handler: _Grpc_Delete_Handler, + }, + { + MethodName: "List", + Handler: _Grpc_List_Handler, + }, + { + MethodName: "GetByID", + Handler: _Grpc_GetByID_Handler, + }, + { + MethodName: "GetByDate", + Handler: _Grpc_GetByDate_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "grpc.proto", +} diff --git a/hw12_13_14_15_calendar/internal/grpc/grpc.pb.gw.go b/hw12_13_14_15_calendar/internal/grpc/grpc.pb.gw.go new file mode 100644 index 0000000..e7a7d31 --- /dev/null +++ b/hw12_13_14_15_calendar/internal/grpc/grpc.pb.gw.go @@ -0,0 +1,334 @@ +// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. +// source: grpc.proto + +/* +Package grpc is a reverse proxy. + +It translates gRPC into RESTful JSON APIs. +*/ +package grpc + +import ( + "io" + "net/http" + + "github.com/golang/protobuf/proto" + "github.com/golang/protobuf/ptypes/empty" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/grpc-ecosystem/grpc-gateway/utilities" + "golang.org/x/net/context" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/status" +) + +var _ codes.Code +var _ io.Reader +var _ status.Status +var _ = runtime.String +var _ = utilities.NewDoubleArray + +func request_Grpc_Update_0(ctx context.Context, marshaler runtime.Marshaler, client GrpcClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq EventWthID + var metadata runtime.ServerMetadata + + newReader, berr := utilities.IOReaderFactory(req.Body) + if berr != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) + } + if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["ID"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "ID") + } + + protoReq.ID, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "ID", err) + } + + msg, err := client.Update(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func request_Grpc_Delete_0(ctx context.Context, marshaler runtime.Marshaler, client GrpcClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq EventID + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["ID"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "ID") + } + + protoReq.ID, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "ID", err) + } + + msg, err := client.Delete(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func request_Grpc_List_0(ctx context.Context, marshaler runtime.Marshaler, client GrpcClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq empty.Empty + var metadata runtime.ServerMetadata + + msg, err := client.List(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func request_Grpc_GetByID_0(ctx context.Context, marshaler runtime.Marshaler, client GrpcClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq EventID + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["ID"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "ID") + } + + protoReq.ID, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "ID", err) + } + + msg, err := client.GetByID(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func request_Grpc_GetByDate_0(ctx context.Context, marshaler runtime.Marshaler, client GrpcClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq Date + var metadata runtime.ServerMetadata + + var ( + val string + e int32 + ok bool + err error + _ = err + ) + + val, ok = pathParams["Date"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "Date") + } + + protoReq.Date, err = runtime.Timestamp(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "Date", err) + } + + val, ok = pathParams["Range"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "Range") + } + + e, err = runtime.Enum(val, QueryRange_value) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "Range", err) + } + + protoReq.Range = QueryRange(e) + + msg, err := client.GetByDate(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +// RegisterGrpcHandlerFromEndpoint is same as RegisterGrpcHandler but +// automatically dials to "endpoint" and closes the connection when "ctx" gets done. +func RegisterGrpcHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { + conn, err := grpc.Dial(endpoint, opts...) + if err != nil { + return err + } + defer func() { + if err != nil { + if cerr := conn.Close(); cerr != nil { + grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + } + return + } + go func() { + <-ctx.Done() + if cerr := conn.Close(); cerr != nil { + grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + } + }() + }() + + return RegisterGrpcHandler(ctx, mux, conn) +} + +// RegisterGrpcHandler registers the http handlers for service Grpc to "mux". +// The handlers forward requests to the grpc endpoint over "conn". +func RegisterGrpcHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { + return RegisterGrpcHandlerClient(ctx, mux, NewGrpcClient(conn)) +} + +// RegisterGrpcHandlerClient registers the http handlers for service Grpc +// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "GrpcClient". +// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "GrpcClient" +// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in +// "GrpcClient" to call the correct interceptors. +func RegisterGrpcHandlerClient(ctx context.Context, mux *runtime.ServeMux, client GrpcClient) error { + + mux.Handle("PUT", pattern_Grpc_Update_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) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Grpc_Update_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Grpc_Update_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("DELETE", pattern_Grpc_Delete_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) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Grpc_Delete_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Grpc_Delete_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Grpc_List_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) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Grpc_List_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Grpc_List_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Grpc_GetByID_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) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Grpc_GetByID_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Grpc_GetByID_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Grpc_GetByDate_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) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Grpc_GetByDate_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Grpc_GetByDate_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + return nil +} + +var ( + pattern_Grpc_Update_0 = runtime.MustPattern(runtime.NewPattern(1, []int{1, 0, 4, 1, 5, 0}, []string{"ID"}, "")) + + pattern_Grpc_Delete_0 = runtime.MustPattern(runtime.NewPattern(1, []int{1, 0, 4, 1, 5, 0}, []string{"ID"}, "")) + + pattern_Grpc_List_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0}, []string{"event"}, "")) + + pattern_Grpc_GetByID_0 = runtime.MustPattern(runtime.NewPattern(1, []int{1, 0, 4, 1, 5, 0}, []string{"ID"}, "")) + + pattern_Grpc_GetByDate_0 = runtime.MustPattern(runtime.NewPattern(1, []int{1, 0, 4, 1, 5, 0, 1, 0, 4, 1, 5, 1}, []string{"Date", "Range"}, "")) +) + +var ( + forward_Grpc_Update_0 = runtime.ForwardResponseMessage + + forward_Grpc_Delete_0 = runtime.ForwardResponseMessage + + forward_Grpc_List_0 = runtime.ForwardResponseMessage + + forward_Grpc_GetByID_0 = runtime.ForwardResponseMessage + + forward_Grpc_GetByDate_0 = runtime.ForwardResponseMessage +) From 7cfe6eca89a02fe6d40574a76f69180d45ec8f9a Mon Sep 17 00:00:00 2001 From: Andrey Ivanov Date: Wed, 7 Oct 2020 16:14:13 +0300 Subject: [PATCH 07/16] HW13 WIP --- hw12_13_14_15_calendar/cmd/calendar/main.go | 10 ++++- hw12_13_14_15_calendar/configs/config.toml | 4 ++ hw12_13_14_15_calendar/go.mod | 3 +- .../internal/config/config.go | 4 ++ .../internal/grpc/handlers.go | 41 +++++++++++++++++++ .../internal/server/grpc/grpc.go | 33 --------------- .../internal/storage/store.go | 3 +- 7 files changed, 61 insertions(+), 37 deletions(-) create mode 100644 hw12_13_14_15_calendar/internal/grpc/handlers.go delete mode 100644 hw12_13_14_15_calendar/internal/server/grpc/grpc.go diff --git a/hw12_13_14_15_calendar/cmd/calendar/main.go b/hw12_13_14_15_calendar/cmd/calendar/main.go index f9d2822..69aa273 100644 --- a/hw12_13_14_15_calendar/cmd/calendar/main.go +++ b/hw12_13_14_15_calendar/cmd/calendar/main.go @@ -5,6 +5,7 @@ import ( "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/grpc" googrpc "google.golang.org/grpc" oslog "log" + "net" "os" "os/signal" @@ -12,7 +13,6 @@ import ( "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/app" "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/config" "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/logger" - internalgrpc "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/server/grpc" internalhttp "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/server/http" store "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/storage" ) @@ -46,8 +46,14 @@ func main() { calendar := app.New(log, st) serverHTTP := internalhttp.NewServer(calendar, conf.Server.Address, conf.Server.Port) + + listnGrpc, err := net.Listen("tcp", net.JoinHostPort(conf.Grpc.Address, conf.Grpc.Port)) + if err != nil { + log.Fatalf("failed to listen %v", err) + } serverGRPC := googrpc.NewServer() - grpc.RegisterGrpcServer(serverGRPC, internalgrpc.Service{}) + grpc.RegisterGrpcServer(serverGRPC, grpc.Service{*calendar}) + serverGRPC.Serve(listnGrpc) go func() { signals := make(chan os.Signal, 1) diff --git a/hw12_13_14_15_calendar/configs/config.toml b/hw12_13_14_15_calendar/configs/config.toml index af65fa9..a94e212 100644 --- a/hw12_13_14_15_calendar/configs/config.toml +++ b/hw12_13_14_15_calendar/configs/config.toml @@ -2,6 +2,10 @@ Address = "localhost" Port = "8080" +[Grpc] +Address = "localhost" +Port = "50051" + [Logger] File = "./calendar.log" Level = "INFO" diff --git a/hw12_13_14_15_calendar/go.mod b/hw12_13_14_15_calendar/go.mod index 8377f6d..1e4228f 100644 --- a/hw12_13_14_15_calendar/go.mod +++ b/hw12_13_14_15_calendar/go.mod @@ -5,12 +5,13 @@ go 1.14 require ( github.com/BurntSushi/toml v0.3.1 github.com/amitrai48/logger v0.0.0-20190214092904-448001c055ec + github.com/daixiang0/gci v0.2.4 // indirect github.com/go-sql-driver/mysql v1.5.0 github.com/golang/protobuf v1.4.2 github.com/grpc-ecosystem/grpc-gateway v1.15.0 github.com/stretchr/testify v1.4.0 go.uber.org/zap v1.15.0 // indirect - golang.org/x/net v0.0.0-20191002035440-2ec189313ef0 + golang.org/x/net v0.0.0-20200625001655-4c5254603344 google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013 google.golang.org/grpc v1.32.0 google.golang.org/protobuf v1.25.0 // indirect diff --git a/hw12_13_14_15_calendar/internal/config/config.go b/hw12_13_14_15_calendar/internal/config/config.go index fbf34fd..ae97302 100644 --- a/hw12_13_14_15_calendar/internal/config/config.go +++ b/hw12_13_14_15_calendar/internal/config/config.go @@ -12,6 +12,10 @@ type Config struct { Address string Port string } + Grpc struct { + Address string + Port string + } Logger struct { File string Level string diff --git a/hw12_13_14_15_calendar/internal/grpc/handlers.go b/hw12_13_14_15_calendar/internal/grpc/handlers.go new file mode 100644 index 0000000..1a3f7bb --- /dev/null +++ b/hw12_13_14_15_calendar/internal/grpc/handlers.go @@ -0,0 +1,41 @@ +package grpc + +import ( + "context" + + "github.com/golang/protobuf/ptypes/empty" + "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/app" +) + +type Service struct { + App app.App +} + +func (s Service) Create(ctx context.Context, e *Event) (*EventID, error) { + var res EventID + //var tmp = event.Event{e.Title, e.Date.(time.Time), e.Latency, e.Note, e.UserID, e.NotifyTime} + //t, err := s.App.Storage.Create(tmp) + //if err != nil { return nil, err } + //res.ID = string(t) + return &res, nil +} + +func (s Service) Update(ctx context.Context, e *EventWthID) (*empty.Empty, error) { + return nil, nil +} + +func (s Service) Delete(ctx context.Context, e *EventID) (*empty.Empty, error) { + return nil, nil +} + +func (s Service) List(ctx context.Context, e *empty.Empty) (*EventList, error) { + return nil, nil +} + +func (s Service) GetByID(ctx context.Context, e *EventID) (*EventList, error) { + return nil, nil +} + +func (s Service) GetByDate(ctx context.Context, e *Date) (*EventList, error) { + return nil, nil +} diff --git a/hw12_13_14_15_calendar/internal/server/grpc/grpc.go b/hw12_13_14_15_calendar/internal/server/grpc/grpc.go deleted file mode 100644 index d2faa57..0000000 --- a/hw12_13_14_15_calendar/internal/server/grpc/grpc.go +++ /dev/null @@ -1,33 +0,0 @@ -package grpc - -import ( - "context" - "github.com/golang/protobuf/ptypes/empty" - "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/grpc" -) - -type Service struct{} - -func (s Service) Create(context.Context, *grpc.Event) (*grpc.EventID, error) { - return nil, nil -} - -func (s Service) Update(context.Context, *grpc.EventWthID) (*empty.Empty, error) { - return nil, nil -} - -func (s Service) Delete(context.Context, *grpc.EventID) (*empty.Empty, error) { - return nil, nil -} - -func (s Service) List(context.Context, *empty.Empty) (*grpc.EventList, error) { - return nil, nil -} - -func (s Service) GetByID(context.Context, *grpc.EventID) (*grpc.EventList, error) { - return nil, nil -} - -func (s Service) GetByDate(context.Context, *grpc.Date) (*grpc.EventList, error) { - return nil, nil -} diff --git a/hw12_13_14_15_calendar/internal/storage/store.go b/hw12_13_14_15_calendar/internal/storage/store.go index f729539..741b651 100644 --- a/hw12_13_14_15_calendar/internal/storage/store.go +++ b/hw12_13_14_15_calendar/internal/storage/store.go @@ -1,10 +1,11 @@ package store import ( + "time" + "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/storage/event" memorystorage "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/storage/memory" sqlstorage "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/storage/sql" - "time" ) type Config struct { From 6355c4138e4f41e08d920ff5a50396859828512d Mon Sep 17 00:00:00 2001 From: Andrey Ivanov Date: Wed, 7 Oct 2020 19:04:48 +0300 Subject: [PATCH 08/16] HW13 WIP 007 --- hw12_13_14_15_calendar/cmd/calendar/main.go | 11 +-- hw12_13_14_15_calendar/grpc/grpc.proto | 8 +-- .../internal/grpc/converters.go | 40 +++++++++++ .../internal/grpc/grpc.pb.go | 72 +++++++++---------- .../internal/grpc/grpc.pb.gw.go | 6 +- .../internal/grpc/handlers.go | 19 +++-- 6 files changed, 104 insertions(+), 52 deletions(-) create mode 100644 hw12_13_14_15_calendar/internal/grpc/converters.go diff --git a/hw12_13_14_15_calendar/cmd/calendar/main.go b/hw12_13_14_15_calendar/cmd/calendar/main.go index 69aa273..27b1e5c 100644 --- a/hw12_13_14_15_calendar/cmd/calendar/main.go +++ b/hw12_13_14_15_calendar/cmd/calendar/main.go @@ -2,8 +2,6 @@ package main import ( "flag" - "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/grpc" - googrpc "google.golang.org/grpc" oslog "log" "net" "os" @@ -12,9 +10,11 @@ import ( _ "github.com/go-sql-driver/mysql" "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/app" "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/config" + "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/grpc" "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/logger" internalhttp "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/server/http" store "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/storage" + googrpc "google.golang.org/grpc" ) var configFile string @@ -52,8 +52,11 @@ func main() { log.Fatalf("failed to listen %v", err) } serverGRPC := googrpc.NewServer() - grpc.RegisterGrpcServer(serverGRPC, grpc.Service{*calendar}) - serverGRPC.Serve(listnGrpc) + grpc.RegisterGrpcServer(serverGRPC, grpc.Service{App: *calendar}) + if err := serverGRPC.Serve(listnGrpc); err != nil { + log.Errorf("failed to start grpc server: " + err.Error()) + os.Exit(1) + } go func() { signals := make(chan os.Signal, 1) diff --git a/hw12_13_14_15_calendar/grpc/grpc.proto b/hw12_13_14_15_calendar/grpc/grpc.proto index 06fed34..cafcb6b 100644 --- a/hw12_13_14_15_calendar/grpc/grpc.proto +++ b/hw12_13_14_15_calendar/grpc/grpc.proto @@ -7,12 +7,12 @@ import "google/protobuf/empty.proto"; import "google/api/annotations.proto"; message Event { - string ID = 1; + int64 ID = 1; string Title = 2; google.protobuf.Timestamp Date = 3; google.protobuf.Duration Latency = 4; string Note = 5; - string UserID = 6; + int64 UserID = 6; google.protobuf.Duration NotifyTime = 7; } @@ -21,11 +21,11 @@ message EventList { } message EventID { - string ID = 1; + int64 ID = 1; } message EventWthID { - string ID = 1; + int64 ID = 1; Event Event = 2; } diff --git a/hw12_13_14_15_calendar/internal/grpc/converters.go b/hw12_13_14_15_calendar/internal/grpc/converters.go new file mode 100644 index 0000000..0a12180 --- /dev/null +++ b/hw12_13_14_15_calendar/internal/grpc/converters.go @@ -0,0 +1,40 @@ +package grpc + +import ( + "github.com/golang/protobuf/ptypes" + "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/storage/event" +) + +func pbevent2event(pbe *Event) (res event.Event, err error) { + res = event.Event{Title: pbe.Title, Note: pbe.Note, UserID: pbe.UserID} + res.Date, err = ptypes.Timestamp(pbe.Date) + if err != nil { + return event.Event{}, err + } + res.Latency, err = ptypes.Duration(pbe.Latency) + if err != nil { + return event.Event{}, err + } + res.NotifyTime, err = ptypes.Duration(pbe.NotifyTime) + if err != nil { + return event.Event{}, err + } + return res, nil +} + +func pbeventWitID2eventAndID(pbe *EventWthID) (id event.ID, evt event.Event, err error) { + evt = event.Event{Title: pbe.Event.Title, Note: pbe.Event.Note, UserID: pbe.Event.UserID} + evt.Date, err = ptypes.Timestamp(pbe.Event.Date) + if err != nil { + return 0, event.Event{}, err + } + evt.Latency, err = ptypes.Duration(pbe.Event.Latency) + if err != nil { + return 0, event.Event{}, err + } + evt.NotifyTime, err = ptypes.Duration(pbe.Event.NotifyTime) + if err != nil { + return 0, event.Event{}, err + } + return event.ID(pbe.ID), evt, nil +} diff --git a/hw12_13_14_15_calendar/internal/grpc/grpc.pb.go b/hw12_13_14_15_calendar/internal/grpc/grpc.pb.go index 8a49203..967c203 100644 --- a/hw12_13_14_15_calendar/internal/grpc/grpc.pb.go +++ b/hw12_13_14_15_calendar/internal/grpc/grpc.pb.go @@ -57,12 +57,12 @@ func (QueryRange) EnumDescriptor() ([]byte, []int) { } type Event struct { - ID string `protobuf:"bytes,1,opt,name=ID,proto3" json:"ID,omitempty"` + ID int64 `protobuf:"varint,1,opt,name=ID,proto3" json:"ID,omitempty"` Title string `protobuf:"bytes,2,opt,name=Title,proto3" json:"Title,omitempty"` Date *timestamp.Timestamp `protobuf:"bytes,3,opt,name=Date,proto3" json:"Date,omitempty"` Latency *duration.Duration `protobuf:"bytes,4,opt,name=Latency,proto3" json:"Latency,omitempty"` Note string `protobuf:"bytes,5,opt,name=Note,proto3" json:"Note,omitempty"` - UserID string `protobuf:"bytes,6,opt,name=UserID,proto3" json:"UserID,omitempty"` + UserID int64 `protobuf:"varint,6,opt,name=UserID,proto3" json:"UserID,omitempty"` NotifyTime *duration.Duration `protobuf:"bytes,7,opt,name=NotifyTime,proto3" json:"NotifyTime,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` @@ -94,11 +94,11 @@ func (m *Event) XXX_DiscardUnknown() { var xxx_messageInfo_Event proto.InternalMessageInfo -func (m *Event) GetID() string { +func (m *Event) GetID() int64 { if m != nil { return m.ID } - return "" + return 0 } func (m *Event) GetTitle() string { @@ -129,11 +129,11 @@ func (m *Event) GetNote() string { return "" } -func (m *Event) GetUserID() string { +func (m *Event) GetUserID() int64 { if m != nil { return m.UserID } - return "" + return 0 } func (m *Event) GetNotifyTime() *duration.Duration { @@ -183,7 +183,7 @@ func (m *EventList) GetEvents() []*Event { } type EventID struct { - ID string `protobuf:"bytes,1,opt,name=ID,proto3" json:"ID,omitempty"` + ID int64 `protobuf:"varint,1,opt,name=ID,proto3" json:"ID,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` @@ -214,15 +214,15 @@ func (m *EventID) XXX_DiscardUnknown() { var xxx_messageInfo_EventID proto.InternalMessageInfo -func (m *EventID) GetID() string { +func (m *EventID) GetID() int64 { if m != nil { return m.ID } - return "" + return 0 } type EventWthID struct { - ID string `protobuf:"bytes,1,opt,name=ID,proto3" json:"ID,omitempty"` + ID int64 `protobuf:"varint,1,opt,name=ID,proto3" json:"ID,omitempty"` Event *Event `protobuf:"bytes,2,opt,name=Event,proto3" json:"Event,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` @@ -254,11 +254,11 @@ func (m *EventWthID) XXX_DiscardUnknown() { var xxx_messageInfo_EventWthID proto.InternalMessageInfo -func (m *EventWthID) GetID() string { +func (m *EventWthID) GetID() int64 { if m != nil { return m.ID } - return "" + return 0 } func (m *EventWthID) GetEvent() *Event { @@ -327,7 +327,7 @@ func init() { func init() { proto.RegisterFile("grpc.proto", fileDescriptor_bedfbfc9b54e5600) } var fileDescriptor_bedfbfc9b54e5600 = []byte{ - // 516 bytes of a gzipped FileDescriptorProto + // 519 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x52, 0xcd, 0x6e, 0xd3, 0x4c, 0x14, 0xad, 0x1d, 0xff, 0x24, 0x37, 0xfa, 0xf2, 0x85, 0x2b, 0x54, 0x5c, 0x53, 0x95, 0xe0, 0x0d, 0x51, 0x90, 0xc6, 0x52, 0xba, 0x40, 0xcd, 0x06, 0x01, 0x13, 0x81, 0x45, 0x09, 0xc2, 0x4a, 0x55, @@ -338,29 +338,29 @@ var fileDescriptor_bedfbfc9b54e5600 = []byte{ 0x92, 0x29, 0xc2, 0xc9, 0x2e, 0xe1, 0x76, 0x96, 0x47, 0x32, 0x4e, 0x13, 0x85, 0x3f, 0xde, 0xc5, 0xc5, 0x24, 0x93, 0x73, 0x05, 0x1e, 0x2b, 0x30, 0xca, 0x62, 0x3f, 0x4a, 0x92, 0x54, 0x92, 0x72, 0x5a, 0xa2, 0xde, 0x2f, 0x0d, 0xcc, 0xfe, 0x17, 0x91, 0x48, 0x6c, 0x80, 0x1e, 0x70, 0x47, 0x6b, - 0x69, 0xed, 0x5a, 0xa8, 0x07, 0x1c, 0x1f, 0x82, 0x39, 0x8c, 0xe5, 0x58, 0x38, 0x3a, 0xb5, 0xca, - 0x02, 0x19, 0x18, 0x3c, 0x92, 0xc2, 0xa9, 0xb4, 0xb4, 0x76, 0xbd, 0xeb, 0xb2, 0xf2, 0x70, 0xb6, - 0x72, 0x66, 0xc3, 0xd5, 0xe8, 0x21, 0xf1, 0xf0, 0x14, 0xec, 0xf3, 0x48, 0x8a, 0xe4, 0x66, 0xee, - 0x18, 0x24, 0x39, 0xda, 0x93, 0x70, 0xb5, 0x4c, 0xb8, 0x62, 0x22, 0x82, 0x31, 0x48, 0xa5, 0x70, - 0x4c, 0x72, 0xa6, 0x7f, 0x3c, 0x04, 0xeb, 0x62, 0x2a, 0xf2, 0x80, 0x3b, 0x16, 0x75, 0x55, 0x85, - 0x67, 0x00, 0x83, 0x54, 0xc6, 0x77, 0xf3, 0xc2, 0xd9, 0xb1, 0xff, 0xe6, 0xb1, 0x45, 0xf6, 0x9e, - 0x43, 0x8d, 0x56, 0x3f, 0x8f, 0xa7, 0x12, 0x4f, 0xc0, 0xa2, 0x62, 0xea, 0x68, 0xad, 0x4a, 0xbb, - 0xde, 0xb5, 0x18, 0x95, 0xa1, 0xea, 0x7a, 0x47, 0x60, 0xd3, 0x5f, 0xc0, 0x77, 0x93, 0xf2, 0x7a, - 0x00, 0x04, 0x5d, 0xca, 0xcf, 0xfb, 0x28, 0x1e, 0xab, 0x80, 0x29, 0xc7, 0xcd, 0xb9, 0x65, 0xd3, - 0xbb, 0x2a, 0xf3, 0x5c, 0xe7, 0xaa, 0xfd, 0x63, 0xae, 0x4f, 0xc1, 0x0c, 0xa3, 0x64, 0x54, 0xde, - 0x4e, 0xa3, 0x5b, 0x67, 0x9f, 0x66, 0x22, 0x9f, 0x53, 0x2b, 0x2c, 0x91, 0x4e, 0x07, 0x60, 0xd3, - 0x44, 0x1b, 0x2a, 0xfc, 0xd5, 0x55, 0xf3, 0x00, 0xab, 0x60, 0x5c, 0xf6, 0xfb, 0xef, 0x9b, 0x1a, - 0xd6, 0xc0, 0xfc, 0xf0, 0x71, 0x30, 0x7c, 0xd7, 0xd4, 0xbb, 0xdf, 0x75, 0x30, 0x8a, 0x17, 0x89, - 0xcf, 0xc0, 0x7a, 0x93, 0x8b, 0xc2, 0x41, 0x0d, 0xea, 0x56, 0x99, 0xda, 0xdb, 0xab, 0x7f, 0xfd, - 0xf1, 0xf3, 0x9b, 0x6e, 0x7a, 0x07, 0x3d, 0xad, 0x83, 0x2f, 0xc1, 0xba, 0xc8, 0x6e, 0x0b, 0x62, - 0x9d, 0x6d, 0xb6, 0x77, 0x0f, 0xf7, 0x26, 0xef, 0x17, 0x6f, 0xd1, 0x6b, 0x92, 0x16, 0x5c, 0xd3, - 0x5f, 0x04, 0x7c, 0x59, 0x1c, 0x70, 0x06, 0x16, 0x17, 0x63, 0x21, 0x05, 0xae, 0x1d, 0xee, 0x55, - 0xff, 0x47, 0x6a, 0xbb, 0x53, 0xaa, 0xb1, 0x07, 0x06, 0xdd, 0xd9, 0x3d, 0x74, 0x17, 0xd8, 0xfa, - 0x5e, 0xbd, 0x06, 0x49, 0xab, 0x68, 0xf9, 0x82, 0x9e, 0x39, 0x03, 0xfb, 0xad, 0x90, 0xaf, 0xe7, - 0x01, 0xdf, 0xf2, 0xdd, 0x16, 0x28, 0x2f, 0x54, 0x5e, 0x2f, 0xa0, 0x46, 0x7c, 0x4a, 0xdd, 0x64, - 0xc5, 0xe7, 0x0f, 0xfa, 0x23, 0xa2, 0x3f, 0xc0, 0xff, 0xfd, 0x45, 0x81, 0x2d, 0xfd, 0x05, 0xe5, - 0xbd, 0xbc, 0xb6, 0x68, 0xa8, 0xd3, 0xdf, 0x01, 0x00, 0x00, 0xff, 0xff, 0xcc, 0x6d, 0x1a, 0xc6, - 0xea, 0x03, 0x00, 0x00, + 0x69, 0xed, 0x4a, 0xa8, 0x07, 0x1c, 0x1f, 0x82, 0x39, 0x8c, 0xe5, 0x58, 0x38, 0x7a, 0x4b, 0x6b, + 0xd7, 0xc2, 0xb2, 0x40, 0x06, 0x06, 0x8f, 0xa4, 0x70, 0x2a, 0x2d, 0xad, 0x5d, 0xef, 0xba, 0xac, + 0x3c, 0x9c, 0xad, 0x9c, 0xd9, 0x70, 0x35, 0x7a, 0x48, 0x3c, 0x3c, 0x05, 0xfb, 0x3c, 0x92, 0x22, + 0xb9, 0x99, 0x3b, 0x06, 0x49, 0x8e, 0xf6, 0x24, 0x5c, 0x2d, 0x13, 0xae, 0x98, 0x88, 0x60, 0x0c, + 0x52, 0x29, 0x1c, 0x93, 0x9c, 0xe9, 0x1f, 0x0f, 0xc1, 0xba, 0x98, 0x8a, 0x3c, 0xe0, 0x8e, 0x45, + 0x23, 0xaa, 0x0a, 0xcf, 0x00, 0x06, 0xa9, 0x8c, 0xef, 0xe6, 0x85, 0xb3, 0x63, 0xff, 0xcd, 0x63, + 0x8b, 0xec, 0x3d, 0x87, 0x1a, 0xad, 0x7e, 0x1e, 0x4f, 0x25, 0x9e, 0x80, 0x45, 0xc5, 0xd4, 0xd1, + 0x5a, 0x95, 0x76, 0xbd, 0x6b, 0x31, 0x2a, 0x43, 0xd5, 0xf5, 0x8e, 0xc0, 0xa6, 0xbf, 0x80, 0xef, + 0x26, 0xe5, 0xf5, 0x00, 0x08, 0xba, 0x94, 0x9f, 0xf7, 0x51, 0x3c, 0x56, 0x01, 0x53, 0x8e, 0x9b, + 0x73, 0xcb, 0xa6, 0x77, 0x55, 0xe6, 0xb9, 0xce, 0x55, 0xfb, 0xc7, 0x5c, 0x9f, 0x82, 0x19, 0x46, + 0xc9, 0xa8, 0xbc, 0x9d, 0x46, 0xb7, 0xce, 0x3e, 0xcd, 0x44, 0x3e, 0xa7, 0x56, 0x58, 0x22, 0x9d, + 0x0e, 0xc0, 0xa6, 0x89, 0x36, 0x54, 0xf8, 0xab, 0xab, 0xe6, 0x01, 0x56, 0xc1, 0xb8, 0xec, 0xf7, + 0xdf, 0x37, 0x35, 0xac, 0x81, 0xf9, 0xe1, 0xe3, 0x60, 0xf8, 0xae, 0xa9, 0x77, 0xbf, 0xeb, 0x60, + 0x14, 0x2f, 0x12, 0x9f, 0x81, 0xf5, 0x26, 0x17, 0x85, 0x83, 0x1a, 0xd4, 0xad, 0x32, 0xb5, 0xb7, + 0x57, 0xff, 0xfa, 0xe3, 0xe7, 0x37, 0xdd, 0xf4, 0x0e, 0x7a, 0x5a, 0x07, 0x5f, 0x82, 0x75, 0x91, + 0xdd, 0x16, 0xc4, 0x3a, 0xdb, 0x6c, 0xef, 0x1e, 0xee, 0x4d, 0xde, 0x2f, 0xde, 0xa2, 0xd7, 0x24, + 0x2d, 0xb8, 0xa6, 0xbf, 0x08, 0xf8, 0xb2, 0x38, 0xe0, 0x0c, 0x2c, 0x2e, 0xc6, 0x42, 0x0a, 0x5c, + 0x3b, 0xdc, 0xab, 0xfe, 0x8f, 0xd4, 0x76, 0xa7, 0x54, 0x63, 0x0f, 0x0c, 0xba, 0xb3, 0x7b, 0xe8, + 0x2e, 0xb0, 0xf5, 0xbd, 0x7a, 0x0d, 0x92, 0x56, 0xd1, 0xf2, 0x05, 0x3d, 0x73, 0x06, 0xf6, 0x5b, + 0x21, 0x5f, 0xcf, 0x03, 0xbe, 0xe5, 0xbb, 0x2d, 0x50, 0x5e, 0xa8, 0xbc, 0x5e, 0x40, 0x8d, 0xf8, + 0x94, 0xba, 0xc9, 0x8a, 0xcf, 0x1f, 0xf4, 0x47, 0x44, 0x7f, 0x80, 0xff, 0xfb, 0x8b, 0x02, 0x5b, + 0xfa, 0x0b, 0xca, 0x7b, 0x79, 0x6d, 0xd1, 0x50, 0xa7, 0xbf, 0x03, 0x00, 0x00, 0xff, 0xff, 0xa5, + 0xa3, 0x2a, 0x4c, 0xea, 0x03, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. diff --git a/hw12_13_14_15_calendar/internal/grpc/grpc.pb.gw.go b/hw12_13_14_15_calendar/internal/grpc/grpc.pb.gw.go index e7a7d31..c809891 100644 --- a/hw12_13_14_15_calendar/internal/grpc/grpc.pb.gw.go +++ b/hw12_13_14_15_calendar/internal/grpc/grpc.pb.gw.go @@ -53,7 +53,7 @@ func request_Grpc_Update_0(ctx context.Context, marshaler runtime.Marshaler, cli return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "ID") } - protoReq.ID, err = runtime.String(val) + protoReq.ID, err = runtime.Int64(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "ID", err) @@ -80,7 +80,7 @@ func request_Grpc_Delete_0(ctx context.Context, marshaler runtime.Marshaler, cli return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "ID") } - protoReq.ID, err = runtime.String(val) + protoReq.ID, err = runtime.Int64(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "ID", err) @@ -116,7 +116,7 @@ func request_Grpc_GetByID_0(ctx context.Context, marshaler runtime.Marshaler, cl return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "ID") } - protoReq.ID, err = runtime.String(val) + protoReq.ID, err = runtime.Int64(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "ID", err) diff --git a/hw12_13_14_15_calendar/internal/grpc/handlers.go b/hw12_13_14_15_calendar/internal/grpc/handlers.go index 1a3f7bb..fac483a 100644 --- a/hw12_13_14_15_calendar/internal/grpc/handlers.go +++ b/hw12_13_14_15_calendar/internal/grpc/handlers.go @@ -13,15 +13,24 @@ type Service struct { func (s Service) Create(ctx context.Context, e *Event) (*EventID, error) { var res EventID - //var tmp = event.Event{e.Title, e.Date.(time.Time), e.Latency, e.Note, e.UserID, e.NotifyTime} - //t, err := s.App.Storage.Create(tmp) - //if err != nil { return nil, err } - //res.ID = string(t) + ce, err := pbevent2event(e) + if err != nil { + return nil, err + } + t, err := s.App.Storage.Create(ce) + if err != nil { + return nil, err + } + res.ID = int64(t) return &res, nil } func (s Service) Update(ctx context.Context, e *EventWthID) (*empty.Empty, error) { - return nil, nil + cid, ce, err := pbeventWitID2eventAndID(e) + if err != nil { + return nil, err + } + return nil, s.App.Storage.Update(cid, ce) } func (s Service) Delete(ctx context.Context, e *EventID) (*empty.Empty, error) { From ac5ab7c6ed924ebe4f86696e11d5cb2bbae897cc Mon Sep 17 00:00:00 2001 From: Andrey Ivanov Date: Fri, 9 Oct 2020 12:30:17 +0300 Subject: [PATCH 09/16] HW13 WIP 008 --- hw12_13_14_15_calendar/cmd/calendar/main.go | 43 ++++++++----------- hw12_13_14_15_calendar/go.mod | 2 +- .../internal/grpc/converters.go | 21 +++++++++ .../internal/grpc/handlers.go | 30 +++++++++++-- .../internal/grpc/server.go | 31 +++++++++++++ 5 files changed, 97 insertions(+), 30 deletions(-) create mode 100644 hw12_13_14_15_calendar/internal/grpc/server.go diff --git a/hw12_13_14_15_calendar/cmd/calendar/main.go b/hw12_13_14_15_calendar/cmd/calendar/main.go index 27b1e5c..f206138 100644 --- a/hw12_13_14_15_calendar/cmd/calendar/main.go +++ b/hw12_13_14_15_calendar/cmd/calendar/main.go @@ -3,7 +3,6 @@ package main import ( "flag" oslog "log" - "net" "os" "os/signal" @@ -14,7 +13,6 @@ import ( "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/logger" internalhttp "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/server/http" store "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/storage" - googrpc "google.golang.org/grpc" ) var configFile string @@ -46,32 +44,27 @@ func main() { calendar := app.New(log, st) serverHTTP := internalhttp.NewServer(calendar, conf.Server.Address, conf.Server.Port) - - listnGrpc, err := net.Listen("tcp", net.JoinHostPort(conf.Grpc.Address, conf.Grpc.Port)) - if err != nil { - log.Fatalf("failed to listen %v", err) - } - serverGRPC := googrpc.NewServer() - grpc.RegisterGrpcServer(serverGRPC, grpc.Service{App: *calendar}) - if err := serverGRPC.Serve(listnGrpc); err != nil { - log.Errorf("failed to start grpc server: " + err.Error()) - os.Exit(1) - } - go func() { - signals := make(chan os.Signal, 1) - signal.Notify(signals) - - <-signals - signal.Stop(signals) - - if err := serverHTTP.Stop(); err != nil { - log.Errorf("failed to stop http server: " + err.Error()) + if err := serverHTTP.Start(); err != nil { + log.Errorf("failed to start http server: " + err.Error()) + os.Exit(1) } }() - if err := serverHTTP.Start(); err != nil { - log.Errorf("failed to start http server: " + err.Error()) - os.Exit(1) + serverGRPC := grpc.New(calendar) + go func() { + if err := serverGRPC.Start(conf); err != nil { + log.Errorf("failed to start grpc server: " + err.Error()) + os.Exit(1) + } + }() + + signals := make(chan os.Signal, 1) + signal.Notify(signals) + <-signals + signal.Stop(signals) + serverGRPC.Stop() + if err := serverHTTP.Stop(); err != nil { + log.Errorf("failed to stop http server: " + err.Error()) } } diff --git a/hw12_13_14_15_calendar/go.mod b/hw12_13_14_15_calendar/go.mod index 1e4228f..3a5d371 100644 --- a/hw12_13_14_15_calendar/go.mod +++ b/hw12_13_14_15_calendar/go.mod @@ -5,13 +5,13 @@ go 1.14 require ( github.com/BurntSushi/toml v0.3.1 github.com/amitrai48/logger v0.0.0-20190214092904-448001c055ec - github.com/daixiang0/gci v0.2.4 // indirect github.com/go-sql-driver/mysql v1.5.0 github.com/golang/protobuf v1.4.2 github.com/grpc-ecosystem/grpc-gateway v1.15.0 github.com/stretchr/testify v1.4.0 go.uber.org/zap v1.15.0 // indirect golang.org/x/net v0.0.0-20200625001655-4c5254603344 + golang.org/x/tools v0.0.0-20200724022722-7017fd6b1305 // indirect google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013 google.golang.org/grpc v1.32.0 google.golang.org/protobuf v1.25.0 // indirect diff --git a/hw12_13_14_15_calendar/internal/grpc/converters.go b/hw12_13_14_15_calendar/internal/grpc/converters.go index 0a12180..8e424e7 100644 --- a/hw12_13_14_15_calendar/internal/grpc/converters.go +++ b/hw12_13_14_15_calendar/internal/grpc/converters.go @@ -1,6 +1,8 @@ package grpc import ( + "time" + "github.com/golang/protobuf/ptypes" "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/storage/event" ) @@ -38,3 +40,22 @@ func pbeventWitID2eventAndID(pbe *EventWthID) (id event.ID, evt event.Event, err } return event.ID(pbe.ID), evt, nil } + +func evtMap2pbEventList(evtMap map[event.ID]event.Event) (*EventList, error) { + var events = &EventList{} + var err error + for k, v := range evtMap { + evt := Event{ID: int64(k), Title: v.Title, Latency: ptypes.DurationProto(v.Latency), Note: v.Note, UserID: v.UserID, NotifyTime: ptypes.DurationProto(v.NotifyTime)} + evt.Date, err = ptypes.TimestampProto(v.Date) + if err != nil { + return nil, err + } + events.Events = append(events.Events, &evt) + } + return events, err +} + +func pbDate2Time(e *Date) (start time.Time, qrange string, err error) { + date, err := ptypes.Timestamp(e.Date) + return date, string(e.Range), err +} diff --git a/hw12_13_14_15_calendar/internal/grpc/handlers.go b/hw12_13_14_15_calendar/internal/grpc/handlers.go index fac483a..11509bc 100644 --- a/hw12_13_14_15_calendar/internal/grpc/handlers.go +++ b/hw12_13_14_15_calendar/internal/grpc/handlers.go @@ -2,9 +2,11 @@ package grpc import ( "context" + "errors" "github.com/golang/protobuf/ptypes/empty" "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/app" + "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/storage/event" ) type Service struct { @@ -33,18 +35,38 @@ func (s Service) Update(ctx context.Context, e *EventWthID) (*empty.Empty, error return nil, s.App.Storage.Update(cid, ce) } +// TODO: Implement func (s Service) Delete(ctx context.Context, e *EventID) (*empty.Empty, error) { - return nil, nil + return nil, s.App.Storage.Delete(event.ID(e.ID)) } +// TODO: Implement func (s Service) List(ctx context.Context, e *empty.Empty) (*EventList, error) { - return nil, nil + tmp, err := s.App.Storage.List() + if err != nil { + return nil, err + } + return evtMap2pbEventList(tmp) } +// TODO: Implement func (s Service) GetByID(ctx context.Context, e *EventID) (*EventList, error) { - return nil, nil + tmp, ok := s.App.Storage.GetByID(event.ID(e.ID)) + if !ok { + return nil, errors.New("event not found") + } + return evtMap2pbEventList(map[event.ID]event.Event{event.ID(e.ID): tmp}) } +// TODO: Implement func (s Service) GetByDate(ctx context.Context, e *Date) (*EventList, error) { - return nil, nil + d, r, err := pbDate2Time(e) + if err != nil { + return nil, err + } + tmp, err := s.App.Storage.GetByDate(d, r) + if err != nil { + return nil, err + } + return evtMap2pbEventList(tmp) } diff --git a/hw12_13_14_15_calendar/internal/grpc/server.go b/hw12_13_14_15_calendar/internal/grpc/server.go new file mode 100644 index 0000000..1076a1f --- /dev/null +++ b/hw12_13_14_15_calendar/internal/grpc/server.go @@ -0,0 +1,31 @@ +package grpc + +import ( + "net" + + "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/app" + "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/config" + googrpc "google.golang.org/grpc" +) + +type Server struct { + s *googrpc.Server + app app.App +} + +func New(app *app.App) Server { + return Server{s: googrpc.NewServer(), app: *app} +} + +func (s *Server) Start(conf config.Config) error { + s.app.Logger.Infof("GRPC server starting") + listnGrpc, err := net.Listen("tcp", net.JoinHostPort(conf.Grpc.Address, conf.Grpc.Port)) + if err != nil { + return err + } + return s.s.Serve(listnGrpc) +} + +func (s *Server) Stop() { + s.s.GracefulStop() +} From f57796664048cbde1e8cda11aeb89be880b7e924 Mon Sep 17 00:00:00 2001 From: Andrey Ivanov Date: Fri, 9 Oct 2020 12:50:01 +0300 Subject: [PATCH 10/16] HW13 WIP 009 --- hw12_13_14_15_calendar/Makefile | 2 +- hw12_13_14_15_calendar/cmd/calendar/main.go | 4 +- .../google/api/annotations.proto | 0 .../google/api/http.proto | 0 .../google/api/httpbody.proto | 0 .../grpcserver.proto} | 3 + .../{grpc => grpcserver}/converters.go | 2 +- .../grpcserver.pb.go} | 132 +++++++++--------- .../grpcserver.pb.gw.go} | 6 +- .../internal/{grpc => grpcserver}/handlers.go | 6 +- .../internal/{grpc => grpcserver}/server.go | 2 +- 11 files changed, 79 insertions(+), 78 deletions(-) rename hw12_13_14_15_calendar/{grpc => grpcserver}/google/api/annotations.proto (100%) rename hw12_13_14_15_calendar/{grpc => grpcserver}/google/api/http.proto (100%) rename hw12_13_14_15_calendar/{grpc => grpcserver}/google/api/httpbody.proto (100%) rename hw12_13_14_15_calendar/{grpc/grpc.proto => grpcserver/grpcserver.proto} (96%) rename hw12_13_14_15_calendar/internal/{grpc => grpcserver}/converters.go (98%) rename hw12_13_14_15_calendar/internal/{grpc/grpc.pb.go => grpcserver/grpcserver.pb.go} (76%) rename hw12_13_14_15_calendar/internal/{grpc/grpc.pb.gw.go => grpcserver/grpcserver.pb.gw.go} (99%) rename hw12_13_14_15_calendar/internal/{grpc => grpcserver}/handlers.go (94%) rename hw12_13_14_15_calendar/internal/{grpc => grpcserver}/server.go (97%) diff --git a/hw12_13_14_15_calendar/Makefile b/hw12_13_14_15_calendar/Makefile index 84c3ed7..b5cd668 100644 --- a/hw12_13_14_15_calendar/Makefile +++ b/hw12_13_14_15_calendar/Makefile @@ -16,6 +16,6 @@ install-lint-deps: (which golangci-lint > /dev/null) || curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(shell go env GOPATH)/bin v1.30.0 generate: - protoc -I ./grpc --go_out=plugins=grpc:./internal/grpc --grpc-gateway_out=logtostderr=true:./internal/grpc ./grpc/grpc.proto + protoc -I ./grpcserver --go_out=plugins=grpc:./internal/grpcserver --grpc-gateway_out=logtostderr=true:./internal/grpcserver ./grpcserver/grpcserver.proto .PHONY: build run test lint \ No newline at end of file diff --git a/hw12_13_14_15_calendar/cmd/calendar/main.go b/hw12_13_14_15_calendar/cmd/calendar/main.go index f206138..30e8acf 100644 --- a/hw12_13_14_15_calendar/cmd/calendar/main.go +++ b/hw12_13_14_15_calendar/cmd/calendar/main.go @@ -9,7 +9,7 @@ import ( _ "github.com/go-sql-driver/mysql" "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/app" "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/config" - "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/grpc" + "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/grpcserver" "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/logger" internalhttp "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/server/http" store "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/storage" @@ -51,7 +51,7 @@ func main() { } }() - serverGRPC := grpc.New(calendar) + serverGRPC := grpcserver.New(calendar) go func() { if err := serverGRPC.Start(conf); err != nil { log.Errorf("failed to start grpc server: " + err.Error()) diff --git a/hw12_13_14_15_calendar/grpc/google/api/annotations.proto b/hw12_13_14_15_calendar/grpcserver/google/api/annotations.proto similarity index 100% rename from hw12_13_14_15_calendar/grpc/google/api/annotations.proto rename to hw12_13_14_15_calendar/grpcserver/google/api/annotations.proto diff --git a/hw12_13_14_15_calendar/grpc/google/api/http.proto b/hw12_13_14_15_calendar/grpcserver/google/api/http.proto similarity index 100% rename from hw12_13_14_15_calendar/grpc/google/api/http.proto rename to hw12_13_14_15_calendar/grpcserver/google/api/http.proto diff --git a/hw12_13_14_15_calendar/grpc/google/api/httpbody.proto b/hw12_13_14_15_calendar/grpcserver/google/api/httpbody.proto similarity index 100% rename from hw12_13_14_15_calendar/grpc/google/api/httpbody.proto rename to hw12_13_14_15_calendar/grpcserver/google/api/httpbody.proto diff --git a/hw12_13_14_15_calendar/grpc/grpc.proto b/hw12_13_14_15_calendar/grpcserver/grpcserver.proto similarity index 96% rename from hw12_13_14_15_calendar/grpc/grpc.proto rename to hw12_13_14_15_calendar/grpcserver/grpcserver.proto index cafcb6b..cd40793 100644 --- a/hw12_13_14_15_calendar/grpc/grpc.proto +++ b/hw12_13_14_15_calendar/grpcserver/grpcserver.proto @@ -1,5 +1,8 @@ syntax = "proto3"; +package grpcserver; + +option go_package = "grpcserver"; import "google/protobuf/timestamp.proto"; import "google/protobuf/duration.proto"; diff --git a/hw12_13_14_15_calendar/internal/grpc/converters.go b/hw12_13_14_15_calendar/internal/grpcserver/converters.go similarity index 98% rename from hw12_13_14_15_calendar/internal/grpc/converters.go rename to hw12_13_14_15_calendar/internal/grpcserver/converters.go index 8e424e7..1b2ea7c 100644 --- a/hw12_13_14_15_calendar/internal/grpc/converters.go +++ b/hw12_13_14_15_calendar/internal/grpcserver/converters.go @@ -1,4 +1,4 @@ -package grpc +package grpcserver import ( "time" diff --git a/hw12_13_14_15_calendar/internal/grpc/grpc.pb.go b/hw12_13_14_15_calendar/internal/grpcserver/grpcserver.pb.go similarity index 76% rename from hw12_13_14_15_calendar/internal/grpc/grpc.pb.go rename to hw12_13_14_15_calendar/internal/grpcserver/grpcserver.pb.go index 967c203..913c7d7 100644 --- a/hw12_13_14_15_calendar/internal/grpc/grpc.pb.go +++ b/hw12_13_14_15_calendar/internal/grpcserver/grpcserver.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. -// source: grpc.proto +// source: grpcserver.proto -package grpc +package grpcserver import ( context "context" @@ -53,7 +53,7 @@ func (x QueryRange) String() string { } func (QueryRange) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_bedfbfc9b54e5600, []int{0} + return fileDescriptor_afa6debe97205904, []int{0} } type Event struct { @@ -73,7 +73,7 @@ func (m *Event) Reset() { *m = Event{} } func (m *Event) String() string { return proto.CompactTextString(m) } func (*Event) ProtoMessage() {} func (*Event) Descriptor() ([]byte, []int) { - return fileDescriptor_bedfbfc9b54e5600, []int{0} + return fileDescriptor_afa6debe97205904, []int{0} } func (m *Event) XXX_Unmarshal(b []byte) error { @@ -154,7 +154,7 @@ func (m *EventList) Reset() { *m = EventList{} } func (m *EventList) String() string { return proto.CompactTextString(m) } func (*EventList) ProtoMessage() {} func (*EventList) Descriptor() ([]byte, []int) { - return fileDescriptor_bedfbfc9b54e5600, []int{1} + return fileDescriptor_afa6debe97205904, []int{1} } func (m *EventList) XXX_Unmarshal(b []byte) error { @@ -193,7 +193,7 @@ func (m *EventID) Reset() { *m = EventID{} } func (m *EventID) String() string { return proto.CompactTextString(m) } func (*EventID) ProtoMessage() {} func (*EventID) Descriptor() ([]byte, []int) { - return fileDescriptor_bedfbfc9b54e5600, []int{2} + return fileDescriptor_afa6debe97205904, []int{2} } func (m *EventID) XXX_Unmarshal(b []byte) error { @@ -233,7 +233,7 @@ func (m *EventWthID) Reset() { *m = EventWthID{} } func (m *EventWthID) String() string { return proto.CompactTextString(m) } func (*EventWthID) ProtoMessage() {} func (*EventWthID) Descriptor() ([]byte, []int) { - return fileDescriptor_bedfbfc9b54e5600, []int{3} + return fileDescriptor_afa6debe97205904, []int{3} } func (m *EventWthID) XXX_Unmarshal(b []byte) error { @@ -270,7 +270,7 @@ func (m *EventWthID) GetEvent() *Event { type Date struct { Date *timestamp.Timestamp `protobuf:"bytes,1,opt,name=Date,proto3" json:"Date,omitempty"` - Range QueryRange `protobuf:"varint,2,opt,name=Range,proto3,enum=QueryRange" json:"Range,omitempty"` + Range QueryRange `protobuf:"varint,2,opt,name=Range,proto3,enum=grpcserver.QueryRange" json:"Range,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` @@ -280,7 +280,7 @@ func (m *Date) Reset() { *m = Date{} } func (m *Date) String() string { return proto.CompactTextString(m) } func (*Date) ProtoMessage() {} func (*Date) Descriptor() ([]byte, []int) { - return fileDescriptor_bedfbfc9b54e5600, []int{4} + return fileDescriptor_afa6debe97205904, []int{4} } func (m *Date) XXX_Unmarshal(b []byte) error { @@ -316,51 +316,53 @@ func (m *Date) GetRange() QueryRange { } func init() { - proto.RegisterEnum("QueryRange", QueryRange_name, QueryRange_value) - proto.RegisterType((*Event)(nil), "Event") - proto.RegisterType((*EventList)(nil), "EventList") - proto.RegisterType((*EventID)(nil), "EventID") - proto.RegisterType((*EventWthID)(nil), "EventWthID") - proto.RegisterType((*Date)(nil), "Date") + proto.RegisterEnum("grpcserver.QueryRange", QueryRange_name, QueryRange_value) + proto.RegisterType((*Event)(nil), "grpcserver.Event") + proto.RegisterType((*EventList)(nil), "grpcserver.EventList") + proto.RegisterType((*EventID)(nil), "grpcserver.EventID") + proto.RegisterType((*EventWthID)(nil), "grpcserver.EventWthID") + proto.RegisterType((*Date)(nil), "grpcserver.Date") } -func init() { proto.RegisterFile("grpc.proto", fileDescriptor_bedfbfc9b54e5600) } +func init() { proto.RegisterFile("grpcserver.proto", fileDescriptor_afa6debe97205904) } -var fileDescriptor_bedfbfc9b54e5600 = []byte{ - // 519 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x52, 0xcd, 0x6e, 0xd3, 0x4c, - 0x14, 0xad, 0x1d, 0xff, 0x24, 0x37, 0xfa, 0xf2, 0x85, 0x2b, 0x54, 0x5c, 0x53, 0x95, 0xe0, 0x0d, - 0x51, 0x90, 0xc6, 0x52, 0xba, 0x40, 0xcd, 0x06, 0x01, 0x13, 0x81, 0x45, 0x09, 0xc2, 0x4a, 0x55, - 0x75, 0xe9, 0xb6, 0xd3, 0x60, 0x29, 0xb1, 0x2d, 0x67, 0x82, 0x14, 0x45, 0xd9, 0xf0, 0x0a, 0xbc, - 0x18, 0x12, 0xaf, 0xc0, 0x4b, 0xb0, 0x43, 0xbe, 0x9e, 0xfc, 0x90, 0xa8, 0x82, 0x95, 0x7d, 0xef, - 0x39, 0x67, 0xce, 0xbd, 0x67, 0x06, 0x60, 0x94, 0x67, 0x37, 0x2c, 0xcb, 0x53, 0x99, 0xba, 0x4f, - 0x46, 0x69, 0x3a, 0x1a, 0x0b, 0x9f, 0xaa, 0xeb, 0xd9, 0x9d, 0x2f, 0xe3, 0x89, 0x98, 0xca, 0x68, - 0x92, 0x29, 0xc2, 0xc9, 0x2e, 0xe1, 0x76, 0x96, 0x47, 0x32, 0x4e, 0x13, 0x85, 0x3f, 0xde, 0xc5, - 0xc5, 0x24, 0x93, 0x73, 0x05, 0x1e, 0x2b, 0x30, 0xca, 0x62, 0x3f, 0x4a, 0x92, 0x54, 0x92, 0x72, - 0x5a, 0xa2, 0xde, 0x2f, 0x0d, 0xcc, 0xfe, 0x17, 0x91, 0x48, 0x6c, 0x80, 0x1e, 0x70, 0x47, 0x6b, - 0x69, 0xed, 0x4a, 0xa8, 0x07, 0x1c, 0x1f, 0x82, 0x39, 0x8c, 0xe5, 0x58, 0x38, 0x7a, 0x4b, 0x6b, - 0xd7, 0xc2, 0xb2, 0x40, 0x06, 0x06, 0x8f, 0xa4, 0x70, 0x2a, 0x2d, 0xad, 0x5d, 0xef, 0xba, 0xac, - 0x3c, 0x9c, 0xad, 0x9c, 0xd9, 0x70, 0x35, 0x7a, 0x48, 0x3c, 0x3c, 0x05, 0xfb, 0x3c, 0x92, 0x22, - 0xb9, 0x99, 0x3b, 0x06, 0x49, 0x8e, 0xf6, 0x24, 0x5c, 0x2d, 0x13, 0xae, 0x98, 0x88, 0x60, 0x0c, - 0x52, 0x29, 0x1c, 0x93, 0x9c, 0xe9, 0x1f, 0x0f, 0xc1, 0xba, 0x98, 0x8a, 0x3c, 0xe0, 0x8e, 0x45, - 0x23, 0xaa, 0x0a, 0xcf, 0x00, 0x06, 0xa9, 0x8c, 0xef, 0xe6, 0x85, 0xb3, 0x63, 0xff, 0xcd, 0x63, - 0x8b, 0xec, 0x3d, 0x87, 0x1a, 0xad, 0x7e, 0x1e, 0x4f, 0x25, 0x9e, 0x80, 0x45, 0xc5, 0xd4, 0xd1, - 0x5a, 0x95, 0x76, 0xbd, 0x6b, 0x31, 0x2a, 0x43, 0xd5, 0xf5, 0x8e, 0xc0, 0xa6, 0xbf, 0x80, 0xef, - 0x26, 0xe5, 0xf5, 0x00, 0x08, 0xba, 0x94, 0x9f, 0xf7, 0x51, 0x3c, 0x56, 0x01, 0x53, 0x8e, 0x9b, - 0x73, 0xcb, 0xa6, 0x77, 0x55, 0xe6, 0xb9, 0xce, 0x55, 0xfb, 0xc7, 0x5c, 0x9f, 0x82, 0x19, 0x46, - 0xc9, 0xa8, 0xbc, 0x9d, 0x46, 0xb7, 0xce, 0x3e, 0xcd, 0x44, 0x3e, 0xa7, 0x56, 0x58, 0x22, 0x9d, - 0x0e, 0xc0, 0xa6, 0x89, 0x36, 0x54, 0xf8, 0xab, 0xab, 0xe6, 0x01, 0x56, 0xc1, 0xb8, 0xec, 0xf7, - 0xdf, 0x37, 0x35, 0xac, 0x81, 0xf9, 0xe1, 0xe3, 0x60, 0xf8, 0xae, 0xa9, 0x77, 0xbf, 0xeb, 0x60, - 0x14, 0x2f, 0x12, 0x9f, 0x81, 0xf5, 0x26, 0x17, 0x85, 0x83, 0x1a, 0xd4, 0xad, 0x32, 0xb5, 0xb7, - 0x57, 0xff, 0xfa, 0xe3, 0xe7, 0x37, 0xdd, 0xf4, 0x0e, 0x7a, 0x5a, 0x07, 0x5f, 0x82, 0x75, 0x91, - 0xdd, 0x16, 0xc4, 0x3a, 0xdb, 0x6c, 0xef, 0x1e, 0xee, 0x4d, 0xde, 0x2f, 0xde, 0xa2, 0xd7, 0x24, - 0x2d, 0xb8, 0xa6, 0xbf, 0x08, 0xf8, 0xb2, 0x38, 0xe0, 0x0c, 0x2c, 0x2e, 0xc6, 0x42, 0x0a, 0x5c, - 0x3b, 0xdc, 0xab, 0xfe, 0x8f, 0xd4, 0x76, 0xa7, 0x54, 0x63, 0x0f, 0x0c, 0xba, 0xb3, 0x7b, 0xe8, - 0x2e, 0xb0, 0xf5, 0xbd, 0x7a, 0x0d, 0x92, 0x56, 0xd1, 0xf2, 0x05, 0x3d, 0x73, 0x06, 0xf6, 0x5b, - 0x21, 0x5f, 0xcf, 0x03, 0xbe, 0xe5, 0xbb, 0x2d, 0x50, 0x5e, 0xa8, 0xbc, 0x5e, 0x40, 0x8d, 0xf8, - 0x94, 0xba, 0xc9, 0x8a, 0xcf, 0x1f, 0xf4, 0x47, 0x44, 0x7f, 0x80, 0xff, 0xfb, 0x8b, 0x02, 0x5b, - 0xfa, 0x0b, 0xca, 0x7b, 0x79, 0x6d, 0xd1, 0x50, 0xa7, 0xbf, 0x03, 0x00, 0x00, 0xff, 0xff, 0xa5, - 0xa3, 0x2a, 0x4c, 0xea, 0x03, 0x00, 0x00, +var fileDescriptor_afa6debe97205904 = []byte{ + // 546 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x54, 0xdd, 0x8a, 0xd3, 0x5c, + 0x14, 0x9d, 0xb4, 0xf9, 0x99, 0xee, 0x7e, 0x5f, 0xcd, 0x6c, 0xb5, 0x66, 0xa2, 0x68, 0xc9, 0x8d, + 0xb5, 0x48, 0x02, 0x1d, 0x10, 0x14, 0xbc, 0x70, 0x3c, 0x41, 0xa3, 0x33, 0x15, 0x43, 0x87, 0x41, + 0xef, 0x32, 0xd3, 0x33, 0x35, 0xd0, 0x26, 0x21, 0x39, 0x1d, 0x28, 0xa5, 0x37, 0xbe, 0x82, 0x8f, + 0xe2, 0xa3, 0xf8, 0x0a, 0xbe, 0x84, 0x77, 0x92, 0x9d, 0xd4, 0x29, 0x4d, 0x8b, 0xde, 0x9d, 0xb3, + 0xd7, 0xda, 0x6b, 0xed, 0x9f, 0x93, 0x80, 0x3e, 0x4e, 0x93, 0xcb, 0x8c, 0xa7, 0xd7, 0x3c, 0xb5, + 0x93, 0x34, 0x16, 0x31, 0xc2, 0x4d, 0xc4, 0x7c, 0x34, 0x8e, 0xe3, 0xf1, 0x84, 0x3b, 0x84, 0x5c, + 0xcc, 0xae, 0x1c, 0x11, 0x4e, 0x79, 0x26, 0x82, 0x69, 0x52, 0x90, 0xcd, 0x87, 0x9b, 0x84, 0xd1, + 0x2c, 0x0d, 0x44, 0x18, 0x47, 0x25, 0x7e, 0x7f, 0x13, 0xe7, 0xd3, 0x44, 0xcc, 0x4b, 0xf0, 0x41, + 0x09, 0x06, 0x49, 0xe8, 0x04, 0x51, 0x14, 0x0b, 0xca, 0xcc, 0x0a, 0xd4, 0xfa, 0x25, 0x81, 0xe2, + 0x5e, 0xf3, 0x48, 0x60, 0x0b, 0x6a, 0x1e, 0x33, 0xa4, 0x8e, 0xd4, 0xad, 0xfb, 0x35, 0x8f, 0xe1, + 0x1d, 0x50, 0x86, 0xa1, 0x98, 0x70, 0xa3, 0xd6, 0x91, 0xba, 0x0d, 0xbf, 0xb8, 0xa0, 0x0d, 0x32, + 0x0b, 0x04, 0x37, 0xea, 0x1d, 0xa9, 0xdb, 0xec, 0x9b, 0x76, 0x21, 0x6e, 0xaf, 0x9c, 0xed, 0xe1, + 0xaa, 0x74, 0x9f, 0x78, 0x78, 0x04, 0xda, 0x49, 0x20, 0x78, 0x74, 0x39, 0x37, 0x64, 0x4a, 0x39, + 0xac, 0xa4, 0xb0, 0xb2, 0x19, 0x7f, 0xc5, 0x44, 0x04, 0x79, 0x10, 0x0b, 0x6e, 0x28, 0xe4, 0x4c, + 0x67, 0x6c, 0x83, 0x7a, 0x96, 0xf1, 0xd4, 0x63, 0x86, 0x4a, 0x25, 0x96, 0x37, 0x7c, 0x0e, 0x30, + 0x88, 0x45, 0x78, 0x35, 0xcf, 0x9d, 0x0d, 0xed, 0x6f, 0x1e, 0x6b, 0x64, 0xeb, 0x19, 0x34, 0xa8, + 0xf5, 0x93, 0x30, 0x13, 0xf8, 0x04, 0x54, 0xba, 0x64, 0x86, 0xd4, 0xa9, 0x77, 0x9b, 0xfd, 0x03, + 0x7b, 0x6d, 0x67, 0x84, 0xf8, 0x25, 0xc1, 0x3a, 0x04, 0x8d, 0x4e, 0x1e, 0xdb, 0x1c, 0x9a, 0xe5, + 0x02, 0x10, 0x74, 0x2e, 0xbe, 0x54, 0x51, 0x7c, 0x5c, 0xce, 0x9a, 0x46, 0xba, 0xd5, 0xa2, 0xc0, + 0xad, 0x51, 0x31, 0xe5, 0x3f, 0xd3, 0x96, 0xfe, 0x71, 0xda, 0x4f, 0x41, 0xf1, 0x83, 0x68, 0x5c, + 0xec, 0xac, 0xd5, 0x6f, 0xaf, 0x1b, 0x7c, 0x9c, 0xf1, 0x74, 0x4e, 0xa8, 0x5f, 0x90, 0x7a, 0x3d, + 0x80, 0x9b, 0x20, 0x6a, 0x50, 0x67, 0xaf, 0x3e, 0xe9, 0x7b, 0xb8, 0x0f, 0xf2, 0xb9, 0xeb, 0xbe, + 0xd7, 0x25, 0x6c, 0x80, 0x72, 0xfa, 0x61, 0x30, 0x7c, 0xab, 0xd7, 0xfa, 0xdf, 0xeb, 0x20, 0xe7, + 0x62, 0xf8, 0x12, 0xd4, 0xd7, 0x29, 0xcf, 0xcd, 0xaa, 0xe5, 0x9b, 0xb7, 0x2b, 0x21, 0x8f, 0x59, + 0xcd, 0xaf, 0x3f, 0x7e, 0x7e, 0xab, 0x29, 0xd6, 0xde, 0x0b, 0xa9, 0x87, 0xef, 0x40, 0x3d, 0x4b, + 0x46, 0x79, 0x7a, 0xbb, 0xc2, 0xa5, 0xa1, 0x99, 0xed, 0x4a, 0x97, 0x6e, 0xfe, 0x9a, 0x2d, 0x9d, + 0x64, 0xc0, 0x54, 0x9c, 0x85, 0xc7, 0x96, 0xb9, 0x16, 0x03, 0x95, 0xf1, 0x09, 0x17, 0x1c, 0xb7, + 0xf9, 0xee, 0x14, 0xfa, 0x9f, 0x84, 0xb4, 0x5e, 0x21, 0x84, 0x2e, 0xc8, 0xf4, 0x00, 0x76, 0xd0, + 0xcd, 0xbb, 0x15, 0xed, 0x9c, 0x6e, 0xb5, 0x48, 0x65, 0x1f, 0x55, 0x87, 0xd3, 0xe7, 0xc3, 0x40, + 0x7b, 0xc3, 0xc5, 0xf1, 0xdc, 0x63, 0xdb, 0xab, 0xd9, 0x21, 0x53, 0x16, 0x83, 0x65, 0x31, 0xa7, + 0xd0, 0x20, 0x15, 0xda, 0xa6, 0xbe, 0x9e, 0x92, 0x47, 0x76, 0x89, 0xdc, 0x23, 0x91, 0x03, 0xbc, + 0xe5, 0x2c, 0x72, 0xda, 0xd2, 0x59, 0xd0, 0x4a, 0x97, 0xc7, 0xff, 0x7d, 0x5e, 0xfb, 0xcf, 0x5c, + 0xa8, 0xd4, 0xd9, 0xd1, 0xef, 0x00, 0x00, 0x00, 0xff, 0xff, 0x78, 0x0d, 0x16, 0xbf, 0x8e, 0x04, + 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -393,7 +395,7 @@ func NewGrpcClient(cc *grpc.ClientConn) GrpcClient { func (c *grpcClient) Create(ctx context.Context, in *Event, opts ...grpc.CallOption) (*EventID, error) { out := new(EventID) - err := c.cc.Invoke(ctx, "/grpc/Create", in, out, opts...) + err := c.cc.Invoke(ctx, "/grpcserver.grpc/Create", in, out, opts...) if err != nil { return nil, err } @@ -402,7 +404,7 @@ func (c *grpcClient) Create(ctx context.Context, in *Event, opts ...grpc.CallOpt func (c *grpcClient) Update(ctx context.Context, in *EventWthID, opts ...grpc.CallOption) (*empty.Empty, error) { out := new(empty.Empty) - err := c.cc.Invoke(ctx, "/grpc/Update", in, out, opts...) + err := c.cc.Invoke(ctx, "/grpcserver.grpc/Update", in, out, opts...) if err != nil { return nil, err } @@ -411,7 +413,7 @@ func (c *grpcClient) Update(ctx context.Context, in *EventWthID, opts ...grpc.Ca func (c *grpcClient) Delete(ctx context.Context, in *EventID, opts ...grpc.CallOption) (*empty.Empty, error) { out := new(empty.Empty) - err := c.cc.Invoke(ctx, "/grpc/Delete", in, out, opts...) + err := c.cc.Invoke(ctx, "/grpcserver.grpc/Delete", in, out, opts...) if err != nil { return nil, err } @@ -420,7 +422,7 @@ func (c *grpcClient) Delete(ctx context.Context, in *EventID, opts ...grpc.CallO func (c *grpcClient) List(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*EventList, error) { out := new(EventList) - err := c.cc.Invoke(ctx, "/grpc/List", in, out, opts...) + err := c.cc.Invoke(ctx, "/grpcserver.grpc/List", in, out, opts...) if err != nil { return nil, err } @@ -429,7 +431,7 @@ func (c *grpcClient) List(ctx context.Context, in *empty.Empty, opts ...grpc.Cal func (c *grpcClient) GetByID(ctx context.Context, in *EventID, opts ...grpc.CallOption) (*EventList, error) { out := new(EventList) - err := c.cc.Invoke(ctx, "/grpc/GetByID", in, out, opts...) + err := c.cc.Invoke(ctx, "/grpcserver.grpc/GetByID", in, out, opts...) if err != nil { return nil, err } @@ -438,7 +440,7 @@ func (c *grpcClient) GetByID(ctx context.Context, in *EventID, opts ...grpc.Call func (c *grpcClient) GetByDate(ctx context.Context, in *Date, opts ...grpc.CallOption) (*EventList, error) { out := new(EventList) - err := c.cc.Invoke(ctx, "/grpc/GetByDate", in, out, opts...) + err := c.cc.Invoke(ctx, "/grpcserver.grpc/GetByDate", in, out, opts...) if err != nil { return nil, err } @@ -492,7 +494,7 @@ func _Grpc_Create_Handler(srv interface{}, ctx context.Context, dec func(interfa } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/grpc/Create", + FullMethod: "/grpcserver.grpc/Create", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GrpcServer).Create(ctx, req.(*Event)) @@ -510,7 +512,7 @@ func _Grpc_Update_Handler(srv interface{}, ctx context.Context, dec func(interfa } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/grpc/Update", + FullMethod: "/grpcserver.grpc/Update", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GrpcServer).Update(ctx, req.(*EventWthID)) @@ -528,7 +530,7 @@ func _Grpc_Delete_Handler(srv interface{}, ctx context.Context, dec func(interfa } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/grpc/Delete", + FullMethod: "/grpcserver.grpc/Delete", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GrpcServer).Delete(ctx, req.(*EventID)) @@ -546,7 +548,7 @@ func _Grpc_List_Handler(srv interface{}, ctx context.Context, dec func(interface } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/grpc/List", + FullMethod: "/grpcserver.grpc/List", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GrpcServer).List(ctx, req.(*empty.Empty)) @@ -564,7 +566,7 @@ func _Grpc_GetByID_Handler(srv interface{}, ctx context.Context, dec func(interf } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/grpc/GetByID", + FullMethod: "/grpcserver.grpc/GetByID", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GrpcServer).GetByID(ctx, req.(*EventID)) @@ -582,7 +584,7 @@ func _Grpc_GetByDate_Handler(srv interface{}, ctx context.Context, dec func(inte } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/grpc/GetByDate", + FullMethod: "/grpcserver.grpc/GetByDate", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GrpcServer).GetByDate(ctx, req.(*Date)) @@ -591,7 +593,7 @@ func _Grpc_GetByDate_Handler(srv interface{}, ctx context.Context, dec func(inte } var _Grpc_serviceDesc = grpc.ServiceDesc{ - ServiceName: "grpc", + ServiceName: "grpcserver.grpc", HandlerType: (*GrpcServer)(nil), Methods: []grpc.MethodDesc{ { @@ -620,5 +622,5 @@ var _Grpc_serviceDesc = grpc.ServiceDesc{ }, }, Streams: []grpc.StreamDesc{}, - Metadata: "grpc.proto", + Metadata: "grpcserver.proto", } diff --git a/hw12_13_14_15_calendar/internal/grpc/grpc.pb.gw.go b/hw12_13_14_15_calendar/internal/grpcserver/grpcserver.pb.gw.go similarity index 99% rename from hw12_13_14_15_calendar/internal/grpc/grpc.pb.gw.go rename to hw12_13_14_15_calendar/internal/grpcserver/grpcserver.pb.gw.go index c809891..2ad6b6b 100644 --- a/hw12_13_14_15_calendar/internal/grpc/grpc.pb.gw.go +++ b/hw12_13_14_15_calendar/internal/grpcserver/grpcserver.pb.gw.go @@ -1,12 +1,12 @@ // Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: grpc.proto +// source: grpcserver.proto /* -Package grpc is a reverse proxy. +Package grpcserver is a reverse proxy. It translates gRPC into RESTful JSON APIs. */ -package grpc +package grpcserver import ( "io" diff --git a/hw12_13_14_15_calendar/internal/grpc/handlers.go b/hw12_13_14_15_calendar/internal/grpcserver/handlers.go similarity index 94% rename from hw12_13_14_15_calendar/internal/grpc/handlers.go rename to hw12_13_14_15_calendar/internal/grpcserver/handlers.go index 11509bc..01706a1 100644 --- a/hw12_13_14_15_calendar/internal/grpc/handlers.go +++ b/hw12_13_14_15_calendar/internal/grpcserver/handlers.go @@ -1,4 +1,4 @@ -package grpc +package grpcserver import ( "context" @@ -35,12 +35,10 @@ func (s Service) Update(ctx context.Context, e *EventWthID) (*empty.Empty, error return nil, s.App.Storage.Update(cid, ce) } -// TODO: Implement func (s Service) Delete(ctx context.Context, e *EventID) (*empty.Empty, error) { return nil, s.App.Storage.Delete(event.ID(e.ID)) } -// TODO: Implement func (s Service) List(ctx context.Context, e *empty.Empty) (*EventList, error) { tmp, err := s.App.Storage.List() if err != nil { @@ -49,7 +47,6 @@ func (s Service) List(ctx context.Context, e *empty.Empty) (*EventList, error) { return evtMap2pbEventList(tmp) } -// TODO: Implement func (s Service) GetByID(ctx context.Context, e *EventID) (*EventList, error) { tmp, ok := s.App.Storage.GetByID(event.ID(e.ID)) if !ok { @@ -58,7 +55,6 @@ func (s Service) GetByID(ctx context.Context, e *EventID) (*EventList, error) { return evtMap2pbEventList(map[event.ID]event.Event{event.ID(e.ID): tmp}) } -// TODO: Implement func (s Service) GetByDate(ctx context.Context, e *Date) (*EventList, error) { d, r, err := pbDate2Time(e) if err != nil { diff --git a/hw12_13_14_15_calendar/internal/grpc/server.go b/hw12_13_14_15_calendar/internal/grpcserver/server.go similarity index 97% rename from hw12_13_14_15_calendar/internal/grpc/server.go rename to hw12_13_14_15_calendar/internal/grpcserver/server.go index 1076a1f..a3fedab 100644 --- a/hw12_13_14_15_calendar/internal/grpc/server.go +++ b/hw12_13_14_15_calendar/internal/grpcserver/server.go @@ -1,4 +1,4 @@ -package grpc +package grpcserver import ( "net" From 19b81ab02a4ccf78b871d2df2542907166d9507d Mon Sep 17 00:00:00 2001 From: Andrey Ivanov Date: Mon, 12 Oct 2020 08:57:43 +0300 Subject: [PATCH 11/16] HW13 WIP 010 --- hw12_13_14_15_calendar/Makefile | 2 +- .../grpcserver/google/api/annotations.proto | 31 -- .../grpcserver/google/api/http.proto | 318 ----------------- .../grpcserver/google/api/httpbody.proto | 78 ---- .../grpcserver/grpcserver.proto | 86 ++--- .../internal/grpcserver/grpcserver.pb.gw.go | 334 ------------------ .../internal/grpcserver/server.go | 1 + 7 files changed, 40 insertions(+), 810 deletions(-) delete mode 100755 hw12_13_14_15_calendar/grpcserver/google/api/annotations.proto delete mode 100755 hw12_13_14_15_calendar/grpcserver/google/api/http.proto delete mode 100755 hw12_13_14_15_calendar/grpcserver/google/api/httpbody.proto delete mode 100644 hw12_13_14_15_calendar/internal/grpcserver/grpcserver.pb.gw.go diff --git a/hw12_13_14_15_calendar/Makefile b/hw12_13_14_15_calendar/Makefile index b5cd668..c055c11 100644 --- a/hw12_13_14_15_calendar/Makefile +++ b/hw12_13_14_15_calendar/Makefile @@ -16,6 +16,6 @@ install-lint-deps: (which golangci-lint > /dev/null) || curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(shell go env GOPATH)/bin v1.30.0 generate: - protoc -I ./grpcserver --go_out=plugins=grpc:./internal/grpcserver --grpc-gateway_out=logtostderr=true:./internal/grpcserver ./grpcserver/grpcserver.proto + protoc -I ./grpcserver --go_out=plugins=grpc:./internal/grpcserver ./grpcserver/grpcserver.proto .PHONY: build run test lint \ No newline at end of file diff --git a/hw12_13_14_15_calendar/grpcserver/google/api/annotations.proto b/hw12_13_14_15_calendar/grpcserver/google/api/annotations.proto deleted file mode 100755 index 18dcf20..0000000 --- a/hw12_13_14_15_calendar/grpcserver/google/api/annotations.proto +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) 2015, Google Inc. -// -// 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/hw12_13_14_15_calendar/grpcserver/google/api/http.proto b/hw12_13_14_15_calendar/grpcserver/google/api/http.proto deleted file mode 100755 index 61168c3..0000000 --- a/hw12_13_14_15_calendar/grpcserver/google/api/http.proto +++ /dev/null @@ -1,318 +0,0 @@ -// Copyright 2018 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 parmeters 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; -} - -// `HttpRule` defines the mapping of an RPC method to one or more HTTP -// REST API methods. The mapping specifies how different portions of the RPC -// request message are mapped to URL path, URL query parameters, and -// HTTP request body. The mapping is typically specified as an -// `google.api.http` annotation on the RPC method, -// see "google/api/annotations.proto" for details. -// -// The mapping consists of a field specifying the path template and -// method kind. The path template can refer to fields in the request -// message, as in the example below which describes a REST GET -// operation on a resource collection of messages: -// -// -// service Messaging { -// rpc GetMessage(GetMessageRequest) returns (Message) { -// option (google.api.http).get = "/v1/messages/{message_id}/{sub.subfield}"; -// } -// } -// message GetMessageRequest { -// message SubMessage { -// string subfield = 1; -// } -// string message_id = 1; // mapped to the URL -// SubMessage sub = 2; // `sub.subfield` is url-mapped -// } -// message Message { -// string text = 1; // content of the resource -// } -// -// The same http annotation can alternatively be expressed inside the -// `GRPC API Configuration` YAML file. -// -// http: -// rules: -// - selector: .Messaging.GetMessage -// get: /v1/messages/{message_id}/{sub.subfield} -// -// This definition enables an automatic, bidrectional mapping of HTTP -// JSON to RPC. Example: -// -// HTTP | RPC -// -----|----- -// `GET /v1/messages/123456/foo` | `GetMessage(message_id: "123456" sub: SubMessage(subfield: "foo"))` -// -// In general, not only fields but also field paths can be referenced -// from a path pattern. Fields mapped to the path pattern cannot be -// repeated and must have a primitive (non-message) type. -// -// Any fields in the request message which are not bound by the path -// pattern automatically become (optional) HTTP query -// parameters. Assume the following definition of the request message: -// -// -// 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 the URL -// int64 revision = 2; // becomes a parameter -// SubMessage sub = 3; // `sub.subfield` becomes a parameter -// } -// -// -// This enables a HTTP JSON to RPC mapping as below: -// -// HTTP | RPC -// -----|----- -// `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 HTTP parameters must have a -// primitive type or a repeated primitive type. Message types are not -// allowed. In the case of a repeated type, the parameter can be -// repeated in the URL, as in `...?param=A¶m=B`. -// -// For HTTP method kinds which 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) = { -// put: "/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 | RPC -// -----|----- -// `PUT /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) = { -// put: "/v1/messages/{message_id}" -// body: "*" -// }; -// } -// } -// message Message { -// string message_id = 1; -// string text = 2; -// } -// -// -// The following HTTP JSON to RPC mapping is enabled: -// -// HTTP | RPC -// -----|----- -// `PUT /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 of -// 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 | RPC -// -----|----- -// `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 -// -// The rules for mapping HTTP path, query parameters, and body fields -// to the request message are as follows: -// -// 1. The `body` field specifies either `*` or a field path, or is -// omitted. If omitted, it indicates there is no HTTP request body. -// 2. Leaf fields (recursive expansion of nested messages in the -// request) can be classified into three types: -// (a) Matched in the URL template. -// (b) Covered by body (if body is `*`, everything except (a) fields; -// else everything under the body field) -// (c) All other fields. -// 3. URL query parameters found in the HTTP request are mapped to (c) fields. -// 4. Any body sent with an HTTP request can contain only (b) fields. -// -// The syntax of the path template is as follows: -// -// Template = "/" Segments [ Verb ] ; -// Segments = Segment { "/" Segment } ; -// Segment = "*" | "**" | LITERAL | Variable ; -// Variable = "{" FieldPath [ "=" Segments ] "}" ; -// FieldPath = IDENT { "." IDENT } ; -// Verb = ":" LITERAL ; -// -// The syntax `*` matches a single path segment. The syntax `**` matches zero -// or more path segments, which must be the last part of the path except the -// `Verb`. The syntax `LITERAL` matches literal text in the path. -// -// 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=*}`. -// -// If a variable contains exactly one path segment, such as `"{var}"` or -// `"{var=*}"`, when such a variable is expanded into a URL path, all characters -// except `[-_.~0-9a-zA-Z]` are percent-encoded. Such variables show up in the -// Discovery Document as `{var}`. -// -// If a variable contains one or more path segments, such as `"{var=foo/*}"` -// or `"{var=**}"`, when such a variable is expanded into a URL path, all -// characters except `[-_.~/0-9a-zA-Z]` are percent-encoded. Such variables -// show up in the Discovery Document as `{+var}`. -// -// NOTE: While the single segment variable matches the semantics of -// [RFC 6570](https://tools.ietf.org/html/rfc6570) Section 3.2.2 -// Simple String Expansion, the multi segment variable **does not** match -// RFC 6570 Reserved Expansion. The reason is that the Reserved Expansion -// does not expand special characters like `?` and `#`, which would lead -// to invalid URLs. -// -// NOTE: the field paths in variables and in the `body` must not refer to -// repeated fields or map fields. -message HttpRule { - // Selects methods 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 { - // Used for listing and getting information about resources. - string get = 2; - - // Used for updating a resource. - string put = 3; - - // Used for creating a resource. - string post = 4; - - // Used for deleting a resource. - string delete = 5; - - // 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 body, or - // `*` for mapping all fields not captured by the path pattern to the HTTP - // body. NOTE: the referred field must not be a repeated field and must be - // present at the top-level of request message type. - string body = 7; - - // Optional. The name of the response field whose value is mapped to the HTTP - // body of response. Other response fields are ignored. When - // not set, the response message will be used as HTTP body of response. - 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 diff --git a/hw12_13_14_15_calendar/grpcserver/google/api/httpbody.proto b/hw12_13_14_15_calendar/grpcserver/google/api/httpbody.proto deleted file mode 100755 index 4428515..0000000 --- a/hw12_13_14_15_calendar/grpcserver/google/api/httpbody.proto +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright 2018 Google LLC. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -syntax = "proto3"; - -package google.api; - -import "google/protobuf/any.proto"; - -option cc_enable_arenas = true; -option go_package = "google.golang.org/genproto/googleapis/api/httpbody;httpbody"; -option java_multiple_files = true; -option java_outer_classname = "HttpBodyProto"; -option java_package = "com.google.api"; -option objc_class_prefix = "GAPI"; - -// Message that represents an arbitrary HTTP body. It should only be used for -// payload formats that can't be represented as JSON, such as raw binary or -// an HTML page. -// -// -// This message can be used both in streaming and non-streaming API methods in -// the request as well as the response. -// -// It can be used as a top-level request field, which is convenient if one -// wants to extract parameters from either the URL or HTTP template into the -// request fields and also want access to the raw HTTP body. -// -// Example: -// -// message GetResourceRequest { -// // A unique request id. -// string request_id = 1; -// -// // The raw HTTP body is bound to this field. -// google.api.HttpBody http_body = 2; -// } -// -// service ResourceService { -// rpc GetResource(GetResourceRequest) returns (google.api.HttpBody); -// rpc UpdateResource(google.api.HttpBody) returns -// (google.protobuf.Empty); -// } -// -// Example with streaming methods: -// -// service CaldavService { -// rpc GetCalendar(stream google.api.HttpBody) -// returns (stream google.api.HttpBody); -// rpc UpdateCalendar(stream google.api.HttpBody) -// returns (stream google.api.HttpBody); -// } -// -// Use of this type only changes how the request and response bodies are -// handled, all other features will continue to work unchanged. -message HttpBody { - // The HTTP Content-Type header value specifying the content type of the body. - string content_type = 1; - - // The HTTP request/response body as raw binary. - bytes data = 2; - - // Application specific response metadata. Must be set in the first response - // for streaming APIs. - repeated google.protobuf.Any extensions = 3; -} \ No newline at end of file diff --git a/hw12_13_14_15_calendar/grpcserver/grpcserver.proto b/hw12_13_14_15_calendar/grpcserver/grpcserver.proto index cd40793..f8e0ff3 100644 --- a/hw12_13_14_15_calendar/grpcserver/grpcserver.proto +++ b/hw12_13_14_15_calendar/grpcserver/grpcserver.proto @@ -7,8 +7,22 @@ option go_package = "grpcserver"; import "google/protobuf/timestamp.proto"; import "google/protobuf/duration.proto"; import "google/protobuf/empty.proto"; -import "google/api/annotations.proto"; + +service grpc { + rpc Create(CreateReq) returns (CreateRsp) {} + rpc Update(UpdateReq) returns (google.protobuf.Empty) {} + rpc Delete(DeleteReq) returns (google.protobuf.Empty) {} + rpc List(google.protobuf.Empty) returns (ListResp) {} + rpc GetByID(GetByIDReq) returns (GetByIDResp) {} + rpc GetByDate(GetByDateReq) returns (GetByDateResp) {} +} + +enum QueryRange { + DAY = 0; + WEEK = 1; + MONTH = 2; +} message Event { int64 ID = 1; string Title = 2; @@ -19,61 +33,37 @@ message Event { google.protobuf.Duration NotifyTime = 7; } -message EventList { - repeated Event Events = 1; +message CreateReq { + string Title = 2; + google.protobuf.Timestamp Date = 3; + google.protobuf.Duration Latency = 4; + string Note = 5; + int64 UserID = 6; + google.protobuf.Duration NotifyTime = 7; } - -message EventID { +message CreateRsp { int64 ID = 1; } - -message EventWthID { +message UpdateReq { int64 ID = 1; Event Event = 2; } - -enum QueryRange { - DAY = 0; - WEEK = 1; - MONTH = 2; +message DeleteReq { + int64 ID = 1; } - -message Date { +message ListResp { + repeated Event Events = 1; +} +message GetByIDReq { + int64 ID = 1; +} +message GetByIDResp { + repeated Event Events = 1; +} +message GetByDateReq { google.protobuf.Timestamp Date = 1; QueryRange Range = 2; } - -service grpc { - rpc Create(Event) returns (EventID) { - option (google.api.http) = { - post: "", - body: "*", - }; - } - rpc Update(EventWthID) returns (google.protobuf.Empty) { - option (google.api.http) = { - put: "/{ID}", - body: "*", - }; - } - rpc Delete(EventID) returns (google.protobuf.Empty) { - option (google.api.http) = { - delete: "/{ID}" - }; - } - rpc List(google.protobuf.Empty) returns (EventList) { - option (google.api.http) = { - get: "/event" - }; - } - rpc GetByID(EventID) returns (EventList) { - option (google.api.http) = { - get: "/{ID}" - }; - } - rpc GetByDate(Date) returns (EventList) { - option (google.api.http) = { - get: "/{Date}/{Range}" - }; - } +message GetByDateResp { + repeated Event Events = 1; } \ No newline at end of file diff --git a/hw12_13_14_15_calendar/internal/grpcserver/grpcserver.pb.gw.go b/hw12_13_14_15_calendar/internal/grpcserver/grpcserver.pb.gw.go deleted file mode 100644 index 2ad6b6b..0000000 --- a/hw12_13_14_15_calendar/internal/grpcserver/grpcserver.pb.gw.go +++ /dev/null @@ -1,334 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: grpcserver.proto - -/* -Package grpcserver is a reverse proxy. - -It translates gRPC into RESTful JSON APIs. -*/ -package grpcserver - -import ( - "io" - "net/http" - - "github.com/golang/protobuf/proto" - "github.com/golang/protobuf/ptypes/empty" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "golang.org/x/net/context" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/status" -) - -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray - -func request_Grpc_Update_0(ctx context.Context, marshaler runtime.Marshaler, client GrpcClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq EventWthID - var metadata runtime.ServerMetadata - - newReader, berr := utilities.IOReaderFactory(req.Body) - if berr != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) - } - if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["ID"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "ID") - } - - protoReq.ID, err = runtime.Int64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "ID", err) - } - - msg, err := client.Update(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func request_Grpc_Delete_0(ctx context.Context, marshaler runtime.Marshaler, client GrpcClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq EventID - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["ID"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "ID") - } - - protoReq.ID, err = runtime.Int64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "ID", err) - } - - msg, err := client.Delete(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func request_Grpc_List_0(ctx context.Context, marshaler runtime.Marshaler, client GrpcClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq empty.Empty - var metadata runtime.ServerMetadata - - msg, err := client.List(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func request_Grpc_GetByID_0(ctx context.Context, marshaler runtime.Marshaler, client GrpcClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq EventID - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["ID"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "ID") - } - - protoReq.ID, err = runtime.Int64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "ID", err) - } - - msg, err := client.GetByID(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func request_Grpc_GetByDate_0(ctx context.Context, marshaler runtime.Marshaler, client GrpcClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq Date - var metadata runtime.ServerMetadata - - var ( - val string - e int32 - ok bool - err error - _ = err - ) - - val, ok = pathParams["Date"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "Date") - } - - protoReq.Date, err = runtime.Timestamp(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "Date", err) - } - - val, ok = pathParams["Range"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "Range") - } - - e, err = runtime.Enum(val, QueryRange_value) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "Range", err) - } - - protoReq.Range = QueryRange(e) - - msg, err := client.GetByDate(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -// RegisterGrpcHandlerFromEndpoint is same as RegisterGrpcHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterGrpcHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return RegisterGrpcHandler(ctx, mux, conn) -} - -// RegisterGrpcHandler registers the http handlers for service Grpc to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterGrpcHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterGrpcHandlerClient(ctx, mux, NewGrpcClient(conn)) -} - -// RegisterGrpcHandlerClient registers the http handlers for service Grpc -// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "GrpcClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "GrpcClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "GrpcClient" to call the correct interceptors. -func RegisterGrpcHandlerClient(ctx context.Context, mux *runtime.ServeMux, client GrpcClient) error { - - mux.Handle("PUT", pattern_Grpc_Update_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) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Grpc_Update_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Grpc_Update_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("DELETE", pattern_Grpc_Delete_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) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Grpc_Delete_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Grpc_Delete_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Grpc_List_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) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Grpc_List_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Grpc_List_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Grpc_GetByID_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) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Grpc_GetByID_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Grpc_GetByID_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Grpc_GetByDate_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) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Grpc_GetByDate_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Grpc_GetByDate_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_Grpc_Update_0 = runtime.MustPattern(runtime.NewPattern(1, []int{1, 0, 4, 1, 5, 0}, []string{"ID"}, "")) - - pattern_Grpc_Delete_0 = runtime.MustPattern(runtime.NewPattern(1, []int{1, 0, 4, 1, 5, 0}, []string{"ID"}, "")) - - pattern_Grpc_List_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0}, []string{"event"}, "")) - - pattern_Grpc_GetByID_0 = runtime.MustPattern(runtime.NewPattern(1, []int{1, 0, 4, 1, 5, 0}, []string{"ID"}, "")) - - pattern_Grpc_GetByDate_0 = runtime.MustPattern(runtime.NewPattern(1, []int{1, 0, 4, 1, 5, 0, 1, 0, 4, 1, 5, 1}, []string{"Date", "Range"}, "")) -) - -var ( - forward_Grpc_Update_0 = runtime.ForwardResponseMessage - - forward_Grpc_Delete_0 = runtime.ForwardResponseMessage - - forward_Grpc_List_0 = runtime.ForwardResponseMessage - - forward_Grpc_GetByID_0 = runtime.ForwardResponseMessage - - forward_Grpc_GetByDate_0 = runtime.ForwardResponseMessage -) diff --git a/hw12_13_14_15_calendar/internal/grpcserver/server.go b/hw12_13_14_15_calendar/internal/grpcserver/server.go index a3fedab..4c455b1 100644 --- a/hw12_13_14_15_calendar/internal/grpcserver/server.go +++ b/hw12_13_14_15_calendar/internal/grpcserver/server.go @@ -20,6 +20,7 @@ func New(app *app.App) Server { func (s *Server) Start(conf config.Config) error { s.app.Logger.Infof("GRPC server starting") listnGrpc, err := net.Listen("tcp", net.JoinHostPort(conf.Grpc.Address, conf.Grpc.Port)) + RegisterGrpcServer(s.s, &Service{}) if err != nil { return err } From 2ae42a6b0f5361a9b6c62e007dd258b86a33f4b8 Mon Sep 17 00:00:00 2001 From: Andrey Ivanov Date: Mon, 12 Oct 2020 17:19:04 +0300 Subject: [PATCH 12/16] HW13 WIP 010 --- hw12_13_14_15_calendar/go.mod | 6 +- .../internal/config/config.go | 45 +- .../internal/grpcserver/converters.go | 13 +- .../internal/grpcserver/grpcserver.pb.go | 547 +++++++++++++----- .../internal/grpcserver/handlers.go | 65 ++- .../internal/grpcserver/handlers_test.go | 49 ++ 6 files changed, 518 insertions(+), 207 deletions(-) create mode 100644 hw12_13_14_15_calendar/internal/grpcserver/handlers_test.go diff --git a/hw12_13_14_15_calendar/go.mod b/hw12_13_14_15_calendar/go.mod index 3a5d371..595c804 100644 --- a/hw12_13_14_15_calendar/go.mod +++ b/hw12_13_14_15_calendar/go.mod @@ -5,14 +5,16 @@ go 1.14 require ( github.com/BurntSushi/toml v0.3.1 github.com/amitrai48/logger v0.0.0-20190214092904-448001c055ec + github.com/dmitryt/otus-golang-hw/hw12_13_14_15_calendar v0.0.0-20200916093948-5ca8860569b6 github.com/go-sql-driver/mysql v1.5.0 github.com/golang/protobuf v1.4.2 github.com/grpc-ecosystem/grpc-gateway v1.15.0 - github.com/stretchr/testify v1.4.0 + github.com/rs/zerolog v1.20.0 + github.com/stretchr/testify v1.6.1 go.uber.org/zap v1.15.0 // indirect golang.org/x/net v0.0.0-20200625001655-4c5254603344 golang.org/x/tools v0.0.0-20200724022722-7017fd6b1305 // indirect - google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013 + google.golang.org/genproto v0.0.0-20200815001618-f69a88009b70 google.golang.org/grpc v1.32.0 google.golang.org/protobuf v1.25.0 // indirect gopkg.in/yaml.v2 v2.3.0 // indirect diff --git a/hw12_13_14_15_calendar/internal/config/config.go b/hw12_13_14_15_calendar/internal/config/config.go index ae97302..5d6ad25 100644 --- a/hw12_13_14_15_calendar/internal/config/config.go +++ b/hw12_13_14_15_calendar/internal/config/config.go @@ -8,27 +8,30 @@ import ( ) type Config struct { - Server struct { - Address string - Port string - } - Grpc struct { - Address string - Port string - } - Logger struct { - File string - Level string - MuteStdout bool - } - Storage struct { - InMemory bool - SQLHost string - SQLPort string - SQLDbase string - SQLUser string - SQLPass string - } + Server Server + Grpc Server + Logger Logger + Storage Storage +} + +type Server struct { + Address string + Port string +} + +type Logger struct { + File string + Level string + MuteStdout bool +} + +type Storage struct { + InMemory bool + SQLHost string + SQLPort string + SQLDbase string + SQLUser string + SQLPass string } // Confita может быти и хороша, но она не возвращает ошибки, если не может распарсить файл в структуру. Мне не нравится такая "молчаливость". diff --git a/hw12_13_14_15_calendar/internal/grpcserver/converters.go b/hw12_13_14_15_calendar/internal/grpcserver/converters.go index 1b2ea7c..a7f6684 100644 --- a/hw12_13_14_15_calendar/internal/grpcserver/converters.go +++ b/hw12_13_14_15_calendar/internal/grpcserver/converters.go @@ -7,7 +7,7 @@ import ( "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/storage/event" ) -func pbevent2event(pbe *Event) (res event.Event, err error) { +func (s Service) buildStorageEvent (pbe *CreateReq) (res event.Event, err error) { res = event.Event{Title: pbe.Title, Note: pbe.Note, UserID: pbe.UserID} res.Date, err = ptypes.Timestamp(pbe.Date) if err != nil { @@ -24,7 +24,7 @@ func pbevent2event(pbe *Event) (res event.Event, err error) { return res, nil } -func pbeventWitID2eventAndID(pbe *EventWthID) (id event.ID, evt event.Event, err error) { +func (s Service) buildStorageEventAndID(pbe *UpdateReq) (id event.ID, evt event.Event, err error) { evt = event.Event{Title: pbe.Event.Title, Note: pbe.Event.Note, UserID: pbe.Event.UserID} evt.Date, err = ptypes.Timestamp(pbe.Event.Date) if err != nil { @@ -41,8 +41,9 @@ func pbeventWitID2eventAndID(pbe *EventWthID) (id event.ID, evt event.Event, err return event.ID(pbe.ID), evt, nil } -func evtMap2pbEventList(evtMap map[event.ID]event.Event) (*EventList, error) { - var events = &EventList{} + +func (s Service) buildEventList(evtMap map[event.ID]event.Event) ([]*Event, error) { + var events = []*Event{} var err error for k, v := range evtMap { evt := Event{ID: int64(k), Title: v.Title, Latency: ptypes.DurationProto(v.Latency), Note: v.Note, UserID: v.UserID, NotifyTime: ptypes.DurationProto(v.NotifyTime)} @@ -50,12 +51,12 @@ func evtMap2pbEventList(evtMap map[event.ID]event.Event) (*EventList, error) { if err != nil { return nil, err } - events.Events = append(events.Events, &evt) + events = append(events, &evt) } return events, err } -func pbDate2Time(e *Date) (start time.Time, qrange string, err error) { +func (s Service) buildTimeAndRange(e *GetByDateReq) (start time.Time, qrange string, err error) { date, err := ptypes.Timestamp(e.Date) return date, string(e.Range), err } diff --git a/hw12_13_14_15_calendar/internal/grpcserver/grpcserver.pb.go b/hw12_13_14_15_calendar/internal/grpcserver/grpcserver.pb.go index 913c7d7..e1d1153 100644 --- a/hw12_13_14_15_calendar/internal/grpcserver/grpcserver.pb.go +++ b/hw12_13_14_15_calendar/internal/grpcserver/grpcserver.pb.go @@ -10,7 +10,6 @@ import ( duration "github.com/golang/protobuf/ptypes/duration" empty "github.com/golang/protobuf/ptypes/empty" timestamp "github.com/golang/protobuf/ptypes/timestamp" - _ "google.golang.org/genproto/googleapis/api/annotations" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" @@ -143,85 +142,125 @@ func (m *Event) GetNotifyTime() *duration.Duration { return nil } -type EventList struct { - Events []*Event `protobuf:"bytes,1,rep,name=Events,proto3" json:"Events,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` +type CreateReq struct { + Title string `protobuf:"bytes,2,opt,name=Title,proto3" json:"Title,omitempty"` + Date *timestamp.Timestamp `protobuf:"bytes,3,opt,name=Date,proto3" json:"Date,omitempty"` + Latency *duration.Duration `protobuf:"bytes,4,opt,name=Latency,proto3" json:"Latency,omitempty"` + Note string `protobuf:"bytes,5,opt,name=Note,proto3" json:"Note,omitempty"` + UserID int64 `protobuf:"varint,6,opt,name=UserID,proto3" json:"UserID,omitempty"` + NotifyTime *duration.Duration `protobuf:"bytes,7,opt,name=NotifyTime,proto3" json:"NotifyTime,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (m *EventList) Reset() { *m = EventList{} } -func (m *EventList) String() string { return proto.CompactTextString(m) } -func (*EventList) ProtoMessage() {} -func (*EventList) Descriptor() ([]byte, []int) { +func (m *CreateReq) Reset() { *m = CreateReq{} } +func (m *CreateReq) String() string { return proto.CompactTextString(m) } +func (*CreateReq) ProtoMessage() {} +func (*CreateReq) Descriptor() ([]byte, []int) { return fileDescriptor_afa6debe97205904, []int{1} } -func (m *EventList) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EventList.Unmarshal(m, b) +func (m *CreateReq) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_CreateReq.Unmarshal(m, b) } -func (m *EventList) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EventList.Marshal(b, m, deterministic) +func (m *CreateReq) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_CreateReq.Marshal(b, m, deterministic) } -func (m *EventList) XXX_Merge(src proto.Message) { - xxx_messageInfo_EventList.Merge(m, src) +func (m *CreateReq) XXX_Merge(src proto.Message) { + xxx_messageInfo_CreateReq.Merge(m, src) } -func (m *EventList) XXX_Size() int { - return xxx_messageInfo_EventList.Size(m) +func (m *CreateReq) XXX_Size() int { + return xxx_messageInfo_CreateReq.Size(m) } -func (m *EventList) XXX_DiscardUnknown() { - xxx_messageInfo_EventList.DiscardUnknown(m) +func (m *CreateReq) XXX_DiscardUnknown() { + xxx_messageInfo_CreateReq.DiscardUnknown(m) } -var xxx_messageInfo_EventList proto.InternalMessageInfo +var xxx_messageInfo_CreateReq proto.InternalMessageInfo -func (m *EventList) GetEvents() []*Event { +func (m *CreateReq) GetTitle() string { if m != nil { - return m.Events + return m.Title + } + return "" +} + +func (m *CreateReq) GetDate() *timestamp.Timestamp { + if m != nil { + return m.Date } return nil } -type EventID struct { +func (m *CreateReq) GetLatency() *duration.Duration { + if m != nil { + return m.Latency + } + return nil +} + +func (m *CreateReq) GetNote() string { + if m != nil { + return m.Note + } + return "" +} + +func (m *CreateReq) GetUserID() int64 { + if m != nil { + return m.UserID + } + return 0 +} + +func (m *CreateReq) GetNotifyTime() *duration.Duration { + if m != nil { + return m.NotifyTime + } + return nil +} + +type CreateRsp struct { ID int64 `protobuf:"varint,1,opt,name=ID,proto3" json:"ID,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } -func (m *EventID) Reset() { *m = EventID{} } -func (m *EventID) String() string { return proto.CompactTextString(m) } -func (*EventID) ProtoMessage() {} -func (*EventID) Descriptor() ([]byte, []int) { +func (m *CreateRsp) Reset() { *m = CreateRsp{} } +func (m *CreateRsp) String() string { return proto.CompactTextString(m) } +func (*CreateRsp) ProtoMessage() {} +func (*CreateRsp) Descriptor() ([]byte, []int) { return fileDescriptor_afa6debe97205904, []int{2} } -func (m *EventID) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EventID.Unmarshal(m, b) +func (m *CreateRsp) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_CreateRsp.Unmarshal(m, b) } -func (m *EventID) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EventID.Marshal(b, m, deterministic) +func (m *CreateRsp) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_CreateRsp.Marshal(b, m, deterministic) } -func (m *EventID) XXX_Merge(src proto.Message) { - xxx_messageInfo_EventID.Merge(m, src) +func (m *CreateRsp) XXX_Merge(src proto.Message) { + xxx_messageInfo_CreateRsp.Merge(m, src) } -func (m *EventID) XXX_Size() int { - return xxx_messageInfo_EventID.Size(m) +func (m *CreateRsp) XXX_Size() int { + return xxx_messageInfo_CreateRsp.Size(m) } -func (m *EventID) XXX_DiscardUnknown() { - xxx_messageInfo_EventID.DiscardUnknown(m) +func (m *CreateRsp) XXX_DiscardUnknown() { + xxx_messageInfo_CreateRsp.DiscardUnknown(m) } -var xxx_messageInfo_EventID proto.InternalMessageInfo +var xxx_messageInfo_CreateRsp proto.InternalMessageInfo -func (m *EventID) GetID() int64 { +func (m *CreateRsp) GetID() int64 { if m != nil { return m.ID } return 0 } -type EventWthID struct { +type UpdateReq struct { ID int64 `protobuf:"varint,1,opt,name=ID,proto3" json:"ID,omitempty"` Event *Event `protobuf:"bytes,2,opt,name=Event,proto3" json:"Event,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` @@ -229,46 +268,202 @@ type EventWthID struct { XXX_sizecache int32 `json:"-"` } -func (m *EventWthID) Reset() { *m = EventWthID{} } -func (m *EventWthID) String() string { return proto.CompactTextString(m) } -func (*EventWthID) ProtoMessage() {} -func (*EventWthID) Descriptor() ([]byte, []int) { +func (m *UpdateReq) Reset() { *m = UpdateReq{} } +func (m *UpdateReq) String() string { return proto.CompactTextString(m) } +func (*UpdateReq) ProtoMessage() {} +func (*UpdateReq) Descriptor() ([]byte, []int) { return fileDescriptor_afa6debe97205904, []int{3} } -func (m *EventWthID) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EventWthID.Unmarshal(m, b) +func (m *UpdateReq) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_UpdateReq.Unmarshal(m, b) } -func (m *EventWthID) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EventWthID.Marshal(b, m, deterministic) +func (m *UpdateReq) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_UpdateReq.Marshal(b, m, deterministic) } -func (m *EventWthID) XXX_Merge(src proto.Message) { - xxx_messageInfo_EventWthID.Merge(m, src) +func (m *UpdateReq) XXX_Merge(src proto.Message) { + xxx_messageInfo_UpdateReq.Merge(m, src) } -func (m *EventWthID) XXX_Size() int { - return xxx_messageInfo_EventWthID.Size(m) +func (m *UpdateReq) XXX_Size() int { + return xxx_messageInfo_UpdateReq.Size(m) } -func (m *EventWthID) XXX_DiscardUnknown() { - xxx_messageInfo_EventWthID.DiscardUnknown(m) +func (m *UpdateReq) XXX_DiscardUnknown() { + xxx_messageInfo_UpdateReq.DiscardUnknown(m) } -var xxx_messageInfo_EventWthID proto.InternalMessageInfo +var xxx_messageInfo_UpdateReq proto.InternalMessageInfo -func (m *EventWthID) GetID() int64 { +func (m *UpdateReq) GetID() int64 { if m != nil { return m.ID } return 0 } -func (m *EventWthID) GetEvent() *Event { +func (m *UpdateReq) GetEvent() *Event { if m != nil { return m.Event } return nil } -type Date struct { +type DeleteReq struct { + ID int64 `protobuf:"varint,1,opt,name=ID,proto3" json:"ID,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *DeleteReq) Reset() { *m = DeleteReq{} } +func (m *DeleteReq) String() string { return proto.CompactTextString(m) } +func (*DeleteReq) ProtoMessage() {} +func (*DeleteReq) Descriptor() ([]byte, []int) { + return fileDescriptor_afa6debe97205904, []int{4} +} + +func (m *DeleteReq) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_DeleteReq.Unmarshal(m, b) +} +func (m *DeleteReq) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_DeleteReq.Marshal(b, m, deterministic) +} +func (m *DeleteReq) XXX_Merge(src proto.Message) { + xxx_messageInfo_DeleteReq.Merge(m, src) +} +func (m *DeleteReq) XXX_Size() int { + return xxx_messageInfo_DeleteReq.Size(m) +} +func (m *DeleteReq) XXX_DiscardUnknown() { + xxx_messageInfo_DeleteReq.DiscardUnknown(m) +} + +var xxx_messageInfo_DeleteReq proto.InternalMessageInfo + +func (m *DeleteReq) GetID() int64 { + if m != nil { + return m.ID + } + return 0 +} + +type ListResp struct { + Events []*Event `protobuf:"bytes,1,rep,name=Events,proto3" json:"Events,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *ListResp) Reset() { *m = ListResp{} } +func (m *ListResp) String() string { return proto.CompactTextString(m) } +func (*ListResp) ProtoMessage() {} +func (*ListResp) Descriptor() ([]byte, []int) { + return fileDescriptor_afa6debe97205904, []int{5} +} + +func (m *ListResp) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_ListResp.Unmarshal(m, b) +} +func (m *ListResp) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_ListResp.Marshal(b, m, deterministic) +} +func (m *ListResp) XXX_Merge(src proto.Message) { + xxx_messageInfo_ListResp.Merge(m, src) +} +func (m *ListResp) XXX_Size() int { + return xxx_messageInfo_ListResp.Size(m) +} +func (m *ListResp) XXX_DiscardUnknown() { + xxx_messageInfo_ListResp.DiscardUnknown(m) +} + +var xxx_messageInfo_ListResp proto.InternalMessageInfo + +func (m *ListResp) GetEvents() []*Event { + if m != nil { + return m.Events + } + return nil +} + +type GetByIDReq struct { + ID int64 `protobuf:"varint,1,opt,name=ID,proto3" json:"ID,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *GetByIDReq) Reset() { *m = GetByIDReq{} } +func (m *GetByIDReq) String() string { return proto.CompactTextString(m) } +func (*GetByIDReq) ProtoMessage() {} +func (*GetByIDReq) Descriptor() ([]byte, []int) { + return fileDescriptor_afa6debe97205904, []int{6} +} + +func (m *GetByIDReq) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_GetByIDReq.Unmarshal(m, b) +} +func (m *GetByIDReq) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_GetByIDReq.Marshal(b, m, deterministic) +} +func (m *GetByIDReq) XXX_Merge(src proto.Message) { + xxx_messageInfo_GetByIDReq.Merge(m, src) +} +func (m *GetByIDReq) XXX_Size() int { + return xxx_messageInfo_GetByIDReq.Size(m) +} +func (m *GetByIDReq) XXX_DiscardUnknown() { + xxx_messageInfo_GetByIDReq.DiscardUnknown(m) +} + +var xxx_messageInfo_GetByIDReq proto.InternalMessageInfo + +func (m *GetByIDReq) GetID() int64 { + if m != nil { + return m.ID + } + return 0 +} + +type GetByIDResp struct { + Events []*Event `protobuf:"bytes,1,rep,name=Events,proto3" json:"Events,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *GetByIDResp) Reset() { *m = GetByIDResp{} } +func (m *GetByIDResp) String() string { return proto.CompactTextString(m) } +func (*GetByIDResp) ProtoMessage() {} +func (*GetByIDResp) Descriptor() ([]byte, []int) { + return fileDescriptor_afa6debe97205904, []int{7} +} + +func (m *GetByIDResp) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_GetByIDResp.Unmarshal(m, b) +} +func (m *GetByIDResp) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_GetByIDResp.Marshal(b, m, deterministic) +} +func (m *GetByIDResp) XXX_Merge(src proto.Message) { + xxx_messageInfo_GetByIDResp.Merge(m, src) +} +func (m *GetByIDResp) XXX_Size() int { + return xxx_messageInfo_GetByIDResp.Size(m) +} +func (m *GetByIDResp) XXX_DiscardUnknown() { + xxx_messageInfo_GetByIDResp.DiscardUnknown(m) +} + +var xxx_messageInfo_GetByIDResp proto.InternalMessageInfo + +func (m *GetByIDResp) GetEvents() []*Event { + if m != nil { + return m.Events + } + return nil +} + +type GetByDateReq struct { Date *timestamp.Timestamp `protobuf:"bytes,1,opt,name=Date,proto3" json:"Date,omitempty"` Range QueryRange `protobuf:"varint,2,opt,name=Range,proto3,enum=grpcserver.QueryRange" json:"Range,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` @@ -276,93 +471,135 @@ type Date struct { XXX_sizecache int32 `json:"-"` } -func (m *Date) Reset() { *m = Date{} } -func (m *Date) String() string { return proto.CompactTextString(m) } -func (*Date) ProtoMessage() {} -func (*Date) Descriptor() ([]byte, []int) { - return fileDescriptor_afa6debe97205904, []int{4} +func (m *GetByDateReq) Reset() { *m = GetByDateReq{} } +func (m *GetByDateReq) String() string { return proto.CompactTextString(m) } +func (*GetByDateReq) ProtoMessage() {} +func (*GetByDateReq) Descriptor() ([]byte, []int) { + return fileDescriptor_afa6debe97205904, []int{8} } -func (m *Date) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Date.Unmarshal(m, b) +func (m *GetByDateReq) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_GetByDateReq.Unmarshal(m, b) } -func (m *Date) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Date.Marshal(b, m, deterministic) +func (m *GetByDateReq) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_GetByDateReq.Marshal(b, m, deterministic) } -func (m *Date) XXX_Merge(src proto.Message) { - xxx_messageInfo_Date.Merge(m, src) +func (m *GetByDateReq) XXX_Merge(src proto.Message) { + xxx_messageInfo_GetByDateReq.Merge(m, src) } -func (m *Date) XXX_Size() int { - return xxx_messageInfo_Date.Size(m) +func (m *GetByDateReq) XXX_Size() int { + return xxx_messageInfo_GetByDateReq.Size(m) } -func (m *Date) XXX_DiscardUnknown() { - xxx_messageInfo_Date.DiscardUnknown(m) +func (m *GetByDateReq) XXX_DiscardUnknown() { + xxx_messageInfo_GetByDateReq.DiscardUnknown(m) } -var xxx_messageInfo_Date proto.InternalMessageInfo +var xxx_messageInfo_GetByDateReq proto.InternalMessageInfo -func (m *Date) GetDate() *timestamp.Timestamp { +func (m *GetByDateReq) GetDate() *timestamp.Timestamp { if m != nil { return m.Date } return nil } -func (m *Date) GetRange() QueryRange { +func (m *GetByDateReq) GetRange() QueryRange { if m != nil { return m.Range } return QueryRange_DAY } +type GetByDateResp struct { + Events []*Event `protobuf:"bytes,1,rep,name=Events,proto3" json:"Events,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *GetByDateResp) Reset() { *m = GetByDateResp{} } +func (m *GetByDateResp) String() string { return proto.CompactTextString(m) } +func (*GetByDateResp) ProtoMessage() {} +func (*GetByDateResp) Descriptor() ([]byte, []int) { + return fileDescriptor_afa6debe97205904, []int{9} +} + +func (m *GetByDateResp) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_GetByDateResp.Unmarshal(m, b) +} +func (m *GetByDateResp) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_GetByDateResp.Marshal(b, m, deterministic) +} +func (m *GetByDateResp) XXX_Merge(src proto.Message) { + xxx_messageInfo_GetByDateResp.Merge(m, src) +} +func (m *GetByDateResp) XXX_Size() int { + return xxx_messageInfo_GetByDateResp.Size(m) +} +func (m *GetByDateResp) XXX_DiscardUnknown() { + xxx_messageInfo_GetByDateResp.DiscardUnknown(m) +} + +var xxx_messageInfo_GetByDateResp proto.InternalMessageInfo + +func (m *GetByDateResp) GetEvents() []*Event { + if m != nil { + return m.Events + } + return nil +} + func init() { proto.RegisterEnum("grpcserver.QueryRange", QueryRange_name, QueryRange_value) proto.RegisterType((*Event)(nil), "grpcserver.Event") - proto.RegisterType((*EventList)(nil), "grpcserver.EventList") - proto.RegisterType((*EventID)(nil), "grpcserver.EventID") - proto.RegisterType((*EventWthID)(nil), "grpcserver.EventWthID") - proto.RegisterType((*Date)(nil), "grpcserver.Date") + proto.RegisterType((*CreateReq)(nil), "grpcserver.CreateReq") + proto.RegisterType((*CreateRsp)(nil), "grpcserver.CreateRsp") + proto.RegisterType((*UpdateReq)(nil), "grpcserver.UpdateReq") + proto.RegisterType((*DeleteReq)(nil), "grpcserver.DeleteReq") + proto.RegisterType((*ListResp)(nil), "grpcserver.ListResp") + proto.RegisterType((*GetByIDReq)(nil), "grpcserver.GetByIDReq") + proto.RegisterType((*GetByIDResp)(nil), "grpcserver.GetByIDResp") + proto.RegisterType((*GetByDateReq)(nil), "grpcserver.GetByDateReq") + proto.RegisterType((*GetByDateResp)(nil), "grpcserver.GetByDateResp") } func init() { proto.RegisterFile("grpcserver.proto", fileDescriptor_afa6debe97205904) } var fileDescriptor_afa6debe97205904 = []byte{ - // 546 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x54, 0xdd, 0x8a, 0xd3, 0x5c, - 0x14, 0x9d, 0xb4, 0xf9, 0x99, 0xee, 0x7e, 0x5f, 0xcd, 0x6c, 0xb5, 0x66, 0xa2, 0x68, 0xc9, 0x8d, - 0xb5, 0x48, 0x02, 0x1d, 0x10, 0x14, 0xbc, 0x70, 0x3c, 0x41, 0xa3, 0x33, 0x15, 0x43, 0x87, 0x41, - 0xef, 0x32, 0xd3, 0x33, 0x35, 0xd0, 0x26, 0x21, 0x39, 0x1d, 0x28, 0xa5, 0x37, 0xbe, 0x82, 0x8f, - 0xe2, 0xa3, 0xf8, 0x0a, 0xbe, 0x84, 0x77, 0x92, 0x9d, 0xd4, 0x29, 0x4d, 0x8b, 0xde, 0x9d, 0xb3, - 0xd7, 0xda, 0x6b, 0xed, 0x9f, 0x93, 0x80, 0x3e, 0x4e, 0x93, 0xcb, 0x8c, 0xa7, 0xd7, 0x3c, 0xb5, - 0x93, 0x34, 0x16, 0x31, 0xc2, 0x4d, 0xc4, 0x7c, 0x34, 0x8e, 0xe3, 0xf1, 0x84, 0x3b, 0x84, 0x5c, - 0xcc, 0xae, 0x1c, 0x11, 0x4e, 0x79, 0x26, 0x82, 0x69, 0x52, 0x90, 0xcd, 0x87, 0x9b, 0x84, 0xd1, - 0x2c, 0x0d, 0x44, 0x18, 0x47, 0x25, 0x7e, 0x7f, 0x13, 0xe7, 0xd3, 0x44, 0xcc, 0x4b, 0xf0, 0x41, - 0x09, 0x06, 0x49, 0xe8, 0x04, 0x51, 0x14, 0x0b, 0xca, 0xcc, 0x0a, 0xd4, 0xfa, 0x25, 0x81, 0xe2, - 0x5e, 0xf3, 0x48, 0x60, 0x0b, 0x6a, 0x1e, 0x33, 0xa4, 0x8e, 0xd4, 0xad, 0xfb, 0x35, 0x8f, 0xe1, - 0x1d, 0x50, 0x86, 0xa1, 0x98, 0x70, 0xa3, 0xd6, 0x91, 0xba, 0x0d, 0xbf, 0xb8, 0xa0, 0x0d, 0x32, - 0x0b, 0x04, 0x37, 0xea, 0x1d, 0xa9, 0xdb, 0xec, 0x9b, 0x76, 0x21, 0x6e, 0xaf, 0x9c, 0xed, 0xe1, - 0xaa, 0x74, 0x9f, 0x78, 0x78, 0x04, 0xda, 0x49, 0x20, 0x78, 0x74, 0x39, 0x37, 0x64, 0x4a, 0x39, - 0xac, 0xa4, 0xb0, 0xb2, 0x19, 0x7f, 0xc5, 0x44, 0x04, 0x79, 0x10, 0x0b, 0x6e, 0x28, 0xe4, 0x4c, - 0x67, 0x6c, 0x83, 0x7a, 0x96, 0xf1, 0xd4, 0x63, 0x86, 0x4a, 0x25, 0x96, 0x37, 0x7c, 0x0e, 0x30, - 0x88, 0x45, 0x78, 0x35, 0xcf, 0x9d, 0x0d, 0xed, 0x6f, 0x1e, 0x6b, 0x64, 0xeb, 0x19, 0x34, 0xa8, - 0xf5, 0x93, 0x30, 0x13, 0xf8, 0x04, 0x54, 0xba, 0x64, 0x86, 0xd4, 0xa9, 0x77, 0x9b, 0xfd, 0x03, - 0x7b, 0x6d, 0x67, 0x84, 0xf8, 0x25, 0xc1, 0x3a, 0x04, 0x8d, 0x4e, 0x1e, 0xdb, 0x1c, 0x9a, 0xe5, - 0x02, 0x10, 0x74, 0x2e, 0xbe, 0x54, 0x51, 0x7c, 0x5c, 0xce, 0x9a, 0x46, 0xba, 0xd5, 0xa2, 0xc0, - 0xad, 0x51, 0x31, 0xe5, 0x3f, 0xd3, 0x96, 0xfe, 0x71, 0xda, 0x4f, 0x41, 0xf1, 0x83, 0x68, 0x5c, - 0xec, 0xac, 0xd5, 0x6f, 0xaf, 0x1b, 0x7c, 0x9c, 0xf1, 0x74, 0x4e, 0xa8, 0x5f, 0x90, 0x7a, 0x3d, - 0x80, 0x9b, 0x20, 0x6a, 0x50, 0x67, 0xaf, 0x3e, 0xe9, 0x7b, 0xb8, 0x0f, 0xf2, 0xb9, 0xeb, 0xbe, - 0xd7, 0x25, 0x6c, 0x80, 0x72, 0xfa, 0x61, 0x30, 0x7c, 0xab, 0xd7, 0xfa, 0xdf, 0xeb, 0x20, 0xe7, - 0x62, 0xf8, 0x12, 0xd4, 0xd7, 0x29, 0xcf, 0xcd, 0xaa, 0xe5, 0x9b, 0xb7, 0x2b, 0x21, 0x8f, 0x59, - 0xcd, 0xaf, 0x3f, 0x7e, 0x7e, 0xab, 0x29, 0xd6, 0xde, 0x0b, 0xa9, 0x87, 0xef, 0x40, 0x3d, 0x4b, - 0x46, 0x79, 0x7a, 0xbb, 0xc2, 0xa5, 0xa1, 0x99, 0xed, 0x4a, 0x97, 0x6e, 0xfe, 0x9a, 0x2d, 0x9d, - 0x64, 0xc0, 0x54, 0x9c, 0x85, 0xc7, 0x96, 0xb9, 0x16, 0x03, 0x95, 0xf1, 0x09, 0x17, 0x1c, 0xb7, - 0xf9, 0xee, 0x14, 0xfa, 0x9f, 0x84, 0xb4, 0x5e, 0x21, 0x84, 0x2e, 0xc8, 0xf4, 0x00, 0x76, 0xd0, - 0xcd, 0xbb, 0x15, 0xed, 0x9c, 0x6e, 0xb5, 0x48, 0x65, 0x1f, 0x55, 0x87, 0xd3, 0xe7, 0xc3, 0x40, - 0x7b, 0xc3, 0xc5, 0xf1, 0xdc, 0x63, 0xdb, 0xab, 0xd9, 0x21, 0x53, 0x16, 0x83, 0x65, 0x31, 0xa7, - 0xd0, 0x20, 0x15, 0xda, 0xa6, 0xbe, 0x9e, 0x92, 0x47, 0x76, 0x89, 0xdc, 0x23, 0x91, 0x03, 0xbc, - 0xe5, 0x2c, 0x72, 0xda, 0xd2, 0x59, 0xd0, 0x4a, 0x97, 0xc7, 0xff, 0x7d, 0x5e, 0xfb, 0xcf, 0x5c, - 0xa8, 0xd4, 0xd9, 0xd1, 0xef, 0x00, 0x00, 0x00, 0xff, 0xff, 0x78, 0x0d, 0x16, 0xbf, 0x8e, 0x04, - 0x00, 0x00, + // 525 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe4, 0x54, 0xdf, 0x6b, 0xd3, 0x50, + 0x14, 0x5e, 0xda, 0x24, 0x5d, 0x4e, 0xe7, 0xa8, 0x87, 0x59, 0xb3, 0x4c, 0xb4, 0xe4, 0xc5, 0x3a, + 0x24, 0x83, 0x0e, 0x65, 0x13, 0x5f, 0xac, 0xb7, 0x68, 0x71, 0x56, 0x0c, 0x1d, 0xa2, 0x6f, 0xd9, + 0x76, 0x56, 0x02, 0x6d, 0x13, 0x93, 0xdb, 0x41, 0xfe, 0x68, 0xc1, 0x57, 0xdf, 0x24, 0xf7, 0x26, + 0x69, 0xda, 0x66, 0xea, 0x9e, 0x7d, 0x4b, 0xee, 0xf7, 0xe3, 0x9c, 0x7b, 0xce, 0xc7, 0x85, 0xd6, + 0x24, 0x0a, 0x2f, 0x63, 0x8a, 0x6e, 0x28, 0x72, 0xc2, 0x28, 0xe0, 0x01, 0xc2, 0xf2, 0xc4, 0x7a, + 0x32, 0x09, 0x82, 0xc9, 0x94, 0x8e, 0x04, 0x72, 0xb1, 0xb8, 0x3e, 0xe2, 0xfe, 0x8c, 0x62, 0xee, + 0xcd, 0x42, 0x49, 0xb6, 0x1e, 0xaf, 0x13, 0xae, 0x16, 0x91, 0xc7, 0xfd, 0x60, 0x9e, 0xe1, 0x07, + 0xeb, 0x38, 0xcd, 0x42, 0x9e, 0x48, 0xd0, 0xfe, 0xa5, 0x80, 0x36, 0xb8, 0xa1, 0x39, 0xc7, 0x5d, + 0xa8, 0x0d, 0x99, 0xa9, 0x74, 0x94, 0x6e, 0xdd, 0xad, 0x0d, 0x19, 0xee, 0x81, 0x36, 0xf6, 0xf9, + 0x94, 0xcc, 0x5a, 0x47, 0xe9, 0x1a, 0xae, 0xfc, 0x41, 0x07, 0x54, 0xe6, 0x71, 0x32, 0xeb, 0x1d, + 0xa5, 0xdb, 0xec, 0x59, 0x8e, 0xf4, 0x76, 0x72, 0x6f, 0x67, 0x9c, 0x37, 0xe7, 0x0a, 0x1e, 0x1e, + 0x43, 0xe3, 0xcc, 0xe3, 0x34, 0xbf, 0x4c, 0x4c, 0x55, 0x48, 0xf6, 0x37, 0x24, 0x2c, 0x6b, 0xd7, + 0xcd, 0x99, 0x88, 0xa0, 0x8e, 0x02, 0x4e, 0xa6, 0x26, 0x2a, 0x8b, 0x6f, 0x6c, 0x83, 0x7e, 0x1e, + 0x53, 0x34, 0x64, 0xa6, 0x2e, 0x5a, 0xcc, 0xfe, 0xf0, 0x14, 0x60, 0x14, 0x70, 0xff, 0x3a, 0x49, + 0x2b, 0x9b, 0x8d, 0xbf, 0xd5, 0x28, 0x91, 0xed, 0x1f, 0x0a, 0x18, 0x6f, 0x23, 0xf2, 0x38, 0xb9, + 0xf4, 0xfd, 0x3f, 0xb8, 0xef, 0x41, 0x71, 0xdd, 0x38, 0x5c, 0x5f, 0xb7, 0xcd, 0xc0, 0x38, 0x0f, + 0xaf, 0xb2, 0x59, 0xac, 0x67, 0xe1, 0x69, 0x16, 0x12, 0x31, 0x9b, 0x66, 0xef, 0xbe, 0x53, 0x4a, + 0xac, 0x00, 0x5c, 0x89, 0xa7, 0x25, 0x18, 0x4d, 0xa9, 0xd2, 0xc5, 0x7e, 0x01, 0xdb, 0x67, 0x7e, + 0xcc, 0x5d, 0x8a, 0x43, 0x7c, 0x06, 0xba, 0x50, 0xc4, 0xa6, 0xd2, 0xa9, 0x57, 0x5b, 0x66, 0x04, + 0xfb, 0x11, 0xc0, 0x3b, 0xe2, 0xfd, 0x64, 0xc8, 0xaa, 0x4c, 0x4f, 0xa0, 0x59, 0xa0, 0x77, 0xf3, + 0x9d, 0xc2, 0x8e, 0x50, 0xb2, 0xec, 0xd2, 0xf9, 0xaa, 0x95, 0x7f, 0x5c, 0xf5, 0x73, 0xd0, 0x5c, + 0x6f, 0x3e, 0x91, 0x81, 0xd9, 0xed, 0xb5, 0xcb, 0x95, 0x3e, 0x2f, 0x28, 0x4a, 0x04, 0xea, 0x4a, + 0x92, 0xfd, 0x0a, 0xee, 0x95, 0xaa, 0xdd, 0xa9, 0xd3, 0xc3, 0x43, 0x80, 0xa5, 0x21, 0x36, 0xa0, + 0xce, 0xde, 0x7c, 0x6d, 0x6d, 0xe1, 0x36, 0xa8, 0x5f, 0x06, 0x83, 0x0f, 0x2d, 0x05, 0x0d, 0xd0, + 0x3e, 0x7e, 0x1a, 0x8d, 0xdf, 0xb7, 0x6a, 0xbd, 0x9f, 0x35, 0x50, 0x53, 0x23, 0x3c, 0x01, 0x5d, + 0x6e, 0x1b, 0x1f, 0x94, 0x9d, 0x8b, 0xc0, 0x5b, 0x55, 0xc7, 0x71, 0x68, 0x6f, 0xe1, 0x29, 0xe8, + 0x32, 0x0a, 0xab, 0xca, 0x22, 0x1e, 0x56, 0x7b, 0x63, 0x36, 0x83, 0xf4, 0x49, 0x91, 0x52, 0xb9, + 0xff, 0x55, 0x69, 0x91, 0x89, 0x3f, 0x48, 0x5f, 0x82, 0x9a, 0xa6, 0x03, 0x6f, 0x61, 0x58, 0x7b, + 0x65, 0xc3, 0x3c, 0x47, 0xf6, 0x16, 0xbe, 0x86, 0x46, 0x16, 0x00, 0x5c, 0x59, 0xc1, 0x32, 0x33, + 0xd6, 0xc3, 0xca, 0x73, 0xa1, 0xee, 0x83, 0x51, 0xac, 0x05, 0xcd, 0x0d, 0x5e, 0x96, 0x0d, 0x6b, + 0xff, 0x16, 0x24, 0xf5, 0xe8, 0xef, 0x7c, 0x2b, 0xbd, 0xd7, 0x17, 0xba, 0xe8, 0xfb, 0xf8, 0x77, + 0x00, 0x00, 0x00, 0xff, 0xff, 0x60, 0x63, 0x06, 0xc6, 0xd6, 0x05, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -377,12 +614,12 @@ const _ = grpc.SupportPackageIsVersion4 // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type GrpcClient interface { - Create(ctx context.Context, in *Event, opts ...grpc.CallOption) (*EventID, error) - Update(ctx context.Context, in *EventWthID, opts ...grpc.CallOption) (*empty.Empty, error) - Delete(ctx context.Context, in *EventID, opts ...grpc.CallOption) (*empty.Empty, error) - List(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*EventList, error) - GetByID(ctx context.Context, in *EventID, opts ...grpc.CallOption) (*EventList, error) - GetByDate(ctx context.Context, in *Date, opts ...grpc.CallOption) (*EventList, error) + Create(ctx context.Context, in *CreateReq, opts ...grpc.CallOption) (*CreateRsp, error) + Update(ctx context.Context, in *UpdateReq, opts ...grpc.CallOption) (*empty.Empty, error) + Delete(ctx context.Context, in *DeleteReq, opts ...grpc.CallOption) (*empty.Empty, error) + List(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*ListResp, error) + GetByID(ctx context.Context, in *GetByIDReq, opts ...grpc.CallOption) (*GetByIDResp, error) + GetByDate(ctx context.Context, in *GetByDateReq, opts ...grpc.CallOption) (*GetByDateResp, error) } type grpcClient struct { @@ -393,8 +630,8 @@ func NewGrpcClient(cc *grpc.ClientConn) GrpcClient { return &grpcClient{cc} } -func (c *grpcClient) Create(ctx context.Context, in *Event, opts ...grpc.CallOption) (*EventID, error) { - out := new(EventID) +func (c *grpcClient) Create(ctx context.Context, in *CreateReq, opts ...grpc.CallOption) (*CreateRsp, error) { + out := new(CreateRsp) err := c.cc.Invoke(ctx, "/grpcserver.grpc/Create", in, out, opts...) if err != nil { return nil, err @@ -402,7 +639,7 @@ func (c *grpcClient) Create(ctx context.Context, in *Event, opts ...grpc.CallOpt return out, nil } -func (c *grpcClient) Update(ctx context.Context, in *EventWthID, opts ...grpc.CallOption) (*empty.Empty, error) { +func (c *grpcClient) Update(ctx context.Context, in *UpdateReq, opts ...grpc.CallOption) (*empty.Empty, error) { out := new(empty.Empty) err := c.cc.Invoke(ctx, "/grpcserver.grpc/Update", in, out, opts...) if err != nil { @@ -411,7 +648,7 @@ func (c *grpcClient) Update(ctx context.Context, in *EventWthID, opts ...grpc.Ca return out, nil } -func (c *grpcClient) Delete(ctx context.Context, in *EventID, opts ...grpc.CallOption) (*empty.Empty, error) { +func (c *grpcClient) Delete(ctx context.Context, in *DeleteReq, opts ...grpc.CallOption) (*empty.Empty, error) { out := new(empty.Empty) err := c.cc.Invoke(ctx, "/grpcserver.grpc/Delete", in, out, opts...) if err != nil { @@ -420,8 +657,8 @@ func (c *grpcClient) Delete(ctx context.Context, in *EventID, opts ...grpc.CallO return out, nil } -func (c *grpcClient) List(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*EventList, error) { - out := new(EventList) +func (c *grpcClient) List(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*ListResp, error) { + out := new(ListResp) err := c.cc.Invoke(ctx, "/grpcserver.grpc/List", in, out, opts...) if err != nil { return nil, err @@ -429,8 +666,8 @@ func (c *grpcClient) List(ctx context.Context, in *empty.Empty, opts ...grpc.Cal return out, nil } -func (c *grpcClient) GetByID(ctx context.Context, in *EventID, opts ...grpc.CallOption) (*EventList, error) { - out := new(EventList) +func (c *grpcClient) GetByID(ctx context.Context, in *GetByIDReq, opts ...grpc.CallOption) (*GetByIDResp, error) { + out := new(GetByIDResp) err := c.cc.Invoke(ctx, "/grpcserver.grpc/GetByID", in, out, opts...) if err != nil { return nil, err @@ -438,8 +675,8 @@ func (c *grpcClient) GetByID(ctx context.Context, in *EventID, opts ...grpc.Call return out, nil } -func (c *grpcClient) GetByDate(ctx context.Context, in *Date, opts ...grpc.CallOption) (*EventList, error) { - out := new(EventList) +func (c *grpcClient) GetByDate(ctx context.Context, in *GetByDateReq, opts ...grpc.CallOption) (*GetByDateResp, error) { + out := new(GetByDateResp) err := c.cc.Invoke(ctx, "/grpcserver.grpc/GetByDate", in, out, opts...) if err != nil { return nil, err @@ -449,34 +686,34 @@ func (c *grpcClient) GetByDate(ctx context.Context, in *Date, opts ...grpc.CallO // GrpcServer is the server API for Grpc service. type GrpcServer interface { - Create(context.Context, *Event) (*EventID, error) - Update(context.Context, *EventWthID) (*empty.Empty, error) - Delete(context.Context, *EventID) (*empty.Empty, error) - List(context.Context, *empty.Empty) (*EventList, error) - GetByID(context.Context, *EventID) (*EventList, error) - GetByDate(context.Context, *Date) (*EventList, error) + Create(context.Context, *CreateReq) (*CreateRsp, error) + Update(context.Context, *UpdateReq) (*empty.Empty, error) + Delete(context.Context, *DeleteReq) (*empty.Empty, error) + List(context.Context, *empty.Empty) (*ListResp, error) + GetByID(context.Context, *GetByIDReq) (*GetByIDResp, error) + GetByDate(context.Context, *GetByDateReq) (*GetByDateResp, error) } // UnimplementedGrpcServer can be embedded to have forward compatible implementations. type UnimplementedGrpcServer struct { } -func (*UnimplementedGrpcServer) Create(ctx context.Context, req *Event) (*EventID, error) { +func (*UnimplementedGrpcServer) Create(ctx context.Context, req *CreateReq) (*CreateRsp, error) { return nil, status.Errorf(codes.Unimplemented, "method Create not implemented") } -func (*UnimplementedGrpcServer) Update(ctx context.Context, req *EventWthID) (*empty.Empty, error) { +func (*UnimplementedGrpcServer) Update(ctx context.Context, req *UpdateReq) (*empty.Empty, error) { return nil, status.Errorf(codes.Unimplemented, "method Update not implemented") } -func (*UnimplementedGrpcServer) Delete(ctx context.Context, req *EventID) (*empty.Empty, error) { +func (*UnimplementedGrpcServer) Delete(ctx context.Context, req *DeleteReq) (*empty.Empty, error) { return nil, status.Errorf(codes.Unimplemented, "method Delete not implemented") } -func (*UnimplementedGrpcServer) List(ctx context.Context, req *empty.Empty) (*EventList, error) { +func (*UnimplementedGrpcServer) List(ctx context.Context, req *empty.Empty) (*ListResp, error) { return nil, status.Errorf(codes.Unimplemented, "method List not implemented") } -func (*UnimplementedGrpcServer) GetByID(ctx context.Context, req *EventID) (*EventList, error) { +func (*UnimplementedGrpcServer) GetByID(ctx context.Context, req *GetByIDReq) (*GetByIDResp, error) { return nil, status.Errorf(codes.Unimplemented, "method GetByID not implemented") } -func (*UnimplementedGrpcServer) GetByDate(ctx context.Context, req *Date) (*EventList, error) { +func (*UnimplementedGrpcServer) GetByDate(ctx context.Context, req *GetByDateReq) (*GetByDateResp, error) { return nil, status.Errorf(codes.Unimplemented, "method GetByDate not implemented") } @@ -485,7 +722,7 @@ func RegisterGrpcServer(s *grpc.Server, srv GrpcServer) { } func _Grpc_Create_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Event) + in := new(CreateReq) if err := dec(in); err != nil { return nil, err } @@ -497,13 +734,13 @@ func _Grpc_Create_Handler(srv interface{}, ctx context.Context, dec func(interfa FullMethod: "/grpcserver.grpc/Create", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(GrpcServer).Create(ctx, req.(*Event)) + return srv.(GrpcServer).Create(ctx, req.(*CreateReq)) } return interceptor(ctx, in, info, handler) } func _Grpc_Update_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(EventWthID) + in := new(UpdateReq) if err := dec(in); err != nil { return nil, err } @@ -515,13 +752,13 @@ func _Grpc_Update_Handler(srv interface{}, ctx context.Context, dec func(interfa FullMethod: "/grpcserver.grpc/Update", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(GrpcServer).Update(ctx, req.(*EventWthID)) + return srv.(GrpcServer).Update(ctx, req.(*UpdateReq)) } return interceptor(ctx, in, info, handler) } func _Grpc_Delete_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(EventID) + in := new(DeleteReq) if err := dec(in); err != nil { return nil, err } @@ -533,7 +770,7 @@ func _Grpc_Delete_Handler(srv interface{}, ctx context.Context, dec func(interfa FullMethod: "/grpcserver.grpc/Delete", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(GrpcServer).Delete(ctx, req.(*EventID)) + return srv.(GrpcServer).Delete(ctx, req.(*DeleteReq)) } return interceptor(ctx, in, info, handler) } @@ -557,7 +794,7 @@ func _Grpc_List_Handler(srv interface{}, ctx context.Context, dec func(interface } func _Grpc_GetByID_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(EventID) + in := new(GetByIDReq) if err := dec(in); err != nil { return nil, err } @@ -569,13 +806,13 @@ func _Grpc_GetByID_Handler(srv interface{}, ctx context.Context, dec func(interf FullMethod: "/grpcserver.grpc/GetByID", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(GrpcServer).GetByID(ctx, req.(*EventID)) + return srv.(GrpcServer).GetByID(ctx, req.(*GetByIDReq)) } return interceptor(ctx, in, info, handler) } func _Grpc_GetByDate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Date) + in := new(GetByDateReq) if err := dec(in); err != nil { return nil, err } @@ -587,7 +824,7 @@ func _Grpc_GetByDate_Handler(srv interface{}, ctx context.Context, dec func(inte FullMethod: "/grpcserver.grpc/GetByDate", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(GrpcServer).GetByDate(ctx, req.(*Date)) + return srv.(GrpcServer).GetByDate(ctx, req.(*GetByDateReq)) } return interceptor(ctx, in, info, handler) } diff --git a/hw12_13_14_15_calendar/internal/grpcserver/handlers.go b/hw12_13_14_15_calendar/internal/grpcserver/handlers.go index 01706a1..5469b22 100644 --- a/hw12_13_14_15_calendar/internal/grpcserver/handlers.go +++ b/hw12_13_14_15_calendar/internal/grpcserver/handlers.go @@ -2,7 +2,8 @@ package grpcserver import ( "context" - "errors" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" "github.com/golang/protobuf/ptypes/empty" "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/app" @@ -13,56 +14,74 @@ type Service struct { App app.App } -func (s Service) Create(ctx context.Context, e *Event) (*EventID, error) { - var res EventID - ce, err := pbevent2event(e) +func (s Service) Create(ctx context.Context, e *CreateReq) (*CreateRsp, error) { + var res CreateRsp + ce, err := s.buildStorageEvent(e) if err != nil { - return nil, err + return nil, status.Errorf(codes.Internal, "inconvertible") } t, err := s.App.Storage.Create(ce) if err != nil { - return nil, err + return nil, status.Errorf(codes.Internal, "storage error: can't create event") } res.ID = int64(t) return &res, nil } -func (s Service) Update(ctx context.Context, e *EventWthID) (*empty.Empty, error) { - cid, ce, err := pbeventWitID2eventAndID(e) +func (s Service) Update(ctx context.Context, e *UpdateReq) (*empty.Empty, error) { + cid, ce, err := s.buildStorageEventAndID(e) if err != nil { - return nil, err + return nil, status.Errorf(codes.Internal, "inconvertible") } - return nil, s.App.Storage.Update(cid, ce) + if s.App.Storage.Update(cid, ce)!= nil { + return nil, status.Errorf(codes.Internal, "storage error: can't update event") + } + return nil, nil } -func (s Service) Delete(ctx context.Context, e *EventID) (*empty.Empty, error) { - return nil, s.App.Storage.Delete(event.ID(e.ID)) +func (s Service) Delete(ctx context.Context, e *DeleteReq) (*empty.Empty, error) { + if s.App.Storage.Delete(event.ID(e.ID)) != nil { + return nil, status.Errorf(codes.Internal, "storage error: can't update event") + } + return nil, nil } -func (s Service) List(ctx context.Context, e *empty.Empty) (*EventList, error) { +func (s Service) List(ctx context.Context, e *empty.Empty) (*ListResp, error) { tmp, err := s.App.Storage.List() if err != nil { - return nil, err + return nil, status.Errorf(codes.Internal, "storage error: can't get list of events") } - return evtMap2pbEventList(tmp) + l,err := s.buildEventList(tmp) + if err != nil { + return nil, status.Errorf(codes.Internal, "inconvertible") + } + return &ListResp{Events: l},nil } -func (s Service) GetByID(ctx context.Context, e *EventID) (*EventList, error) { +func (s Service) GetByID(ctx context.Context, e *GetByIDReq) (*GetByIDResp, error) { tmp, ok := s.App.Storage.GetByID(event.ID(e.ID)) if !ok { - return nil, errors.New("event not found") + return nil, status.Errorf(codes.NotFound, "event not found") } - return evtMap2pbEventList(map[event.ID]event.Event{event.ID(e.ID): tmp}) + l,err := s.buildEventList(map[event.ID]event.Event{event.ID(e.ID): tmp}) + if err != nil { + return nil, status.Errorf(codes.Internal, "inconvertible") + } + return &GetByIDResp{Events: l},nil } -func (s Service) GetByDate(ctx context.Context, e *Date) (*EventList, error) { - d, r, err := pbDate2Time(e) +func (s Service) GetByDate(ctx context.Context, e *GetByDateReq) (*GetByDateResp, error) { + d, r, err := s.buildTimeAndRange(e) if err != nil { - return nil, err + return nil, status.Errorf(codes.Internal, "inconvertible") } tmp, err := s.App.Storage.GetByDate(d, r) if err != nil { - return nil, err + return nil, status.Errorf(codes.Internal, "storage error: can't get list of events") } - return evtMap2pbEventList(tmp) + l,err := s.buildEventList(tmp) + if err != nil { + return nil, status.Errorf(codes.Internal, "inconvertible") + } + return &GetByDateResp{Events: l},nil } diff --git a/hw12_13_14_15_calendar/internal/grpcserver/handlers_test.go b/hw12_13_14_15_calendar/internal/grpcserver/handlers_test.go new file mode 100644 index 0000000..95c2d6e --- /dev/null +++ b/hw12_13_14_15_calendar/internal/grpcserver/handlers_test.go @@ -0,0 +1,49 @@ +package grpcserver + +import ( + "github.com/golang/protobuf/ptypes" + "github.com/stretchr/testify/require" + "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/app" + "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/config" + "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/logger" + store "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/storage" + "testing" + "time" +) +var conf = config.Config{Server: config.Server{ Address: "localhost", Port: "50511" }, Grpc: config.Server{Address: "localhost", Port: "50512"}, Logger: config.Logger{File: "calendar.log", Level: "INFO", MuteStdout: false}, Storage: config.Storage{InMemory: true, SQLHost: "", SQLPort: "", SQLDbase: "", SQLUser: "", SQLPass: ""}} + +var storeConf = store.Config(conf.Storage) + +func TestService(t *testing.T) { + log, err := logger.New(conf) + require.NoError(t,err, "can't create logger") + srv := Service{App: *app.New(log, store.NewStore(storeConf))} + tm, _ := time.Parse("02.01.2006", "01.02.2003") + cdate, err := ptypes.TimestampProto(tm) + require.NoError(t,err, "can't convert time to proto") +// Create + step1, err := srv.Create(nil, &CreateReq{Title: "Test event", Date: cdate, Latency: ptypes.DurationProto(time.Hour*24), Note: "First gen", UserID: 1111, NotifyTime: ptypes.DurationProto(time.Minute*5)}) + require.NoError(t,err, "can,t create event") + require.NotEqual(t,step1.ID,0, "message ID may not be a \"0\"") +// GetByID + step2, err := srv.GetByID(nil,&GetByIDReq{ID: step1.ID}) + require.NoError(t,err, "can't get event by id") + require.Equal(t, 1, len(step2.Events), "length of slice in responce must be a \"1\"") + require.Equal(t, &Event{ID: 1,Title: "Test event", Date: cdate, Latency: ptypes.DurationProto(time.Hour*24), Note: "First gen", UserID: 1111, NotifyTime: ptypes.DurationProto(time.Minute*5)},step2.Events[0], "request contains invalid data") +// Update + _, err = srv.Update(nil,&UpdateReq{ID: step1.ID, Event: &Event{Title: "Updated event", Date: cdate, Latency: ptypes.DurationProto(time.Hour*48), Note: "Updated gen", UserID: 2222, NotifyTime: ptypes.DurationProto(time.Minute*10)}}) + require.NoError(t,err, "can't update event") +// List + step3, err := srv.List(nil, nil) + require.NoError(t,err, "problem with list") + require.Equal(t, 1, len(step3.Events), "length of slice in responce must be a \"1\"") + require.Equal(t, &Event{ID: 1,Title: "Updated event", Date: cdate, Latency: ptypes.DurationProto(time.Hour*48), Note: "Updated gen", UserID: 2222, NotifyTime: ptypes.DurationProto(time.Minute*10)},step3.Events[0], "request contains invalid data") +// GetByDate + step4, err := srv.GetByDate(nil,&GetByDateReq{Date: cdate, Range: 1}) + require.NoError(t,err, "problem with GetByDate") + require.Equal(t, 1, len(step4.Events), "length of slice in responce must be a \"1\"") + require.Equal(t, &Event{ID: 1,Title: "Updated event", Date: cdate, Latency: ptypes.DurationProto(time.Hour*48), Note: "Updated gen", UserID: 2222, NotifyTime: ptypes.DurationProto(time.Minute*10)},step4.Events[0], "request contains invalid data") +// Delete +// List + +} \ No newline at end of file From 5fcfd7e7d6403dc1d0caf049b0f62e51625522a6 Mon Sep 17 00:00:00 2001 From: Andrey Ivanov Date: Mon, 12 Oct 2020 19:00:59 +0300 Subject: [PATCH 13/16] HW13 Completed --- hw12_13_14_15_calendar/go.mod | 1 + .../internal/config/config.go | 6 +- .../internal/grpcserver/converters.go | 5 +- .../internal/grpcserver/handlers.go | 18 +++--- .../internal/grpcserver/handlers_test.go | 60 +++++++++++-------- .../internal/storage/memory/memory.go | 14 ++++- 6 files changed, 61 insertions(+), 43 deletions(-) diff --git a/hw12_13_14_15_calendar/go.mod b/hw12_13_14_15_calendar/go.mod index 595c804..3a4d9fe 100644 --- a/hw12_13_14_15_calendar/go.mod +++ b/hw12_13_14_15_calendar/go.mod @@ -5,6 +5,7 @@ go 1.14 require ( github.com/BurntSushi/toml v0.3.1 github.com/amitrai48/logger v0.0.0-20190214092904-448001c055ec + github.com/daixiang0/gci v0.2.4 // indirect github.com/dmitryt/otus-golang-hw/hw12_13_14_15_calendar v0.0.0-20200916093948-5ca8860569b6 github.com/go-sql-driver/mysql v1.5.0 github.com/golang/protobuf v1.4.2 diff --git a/hw12_13_14_15_calendar/internal/config/config.go b/hw12_13_14_15_calendar/internal/config/config.go index 5d6ad25..30440bc 100644 --- a/hw12_13_14_15_calendar/internal/config/config.go +++ b/hw12_13_14_15_calendar/internal/config/config.go @@ -8,9 +8,9 @@ import ( ) type Config struct { - Server Server - Grpc Server - Logger Logger + Server Server + Grpc Server + Logger Logger Storage Storage } diff --git a/hw12_13_14_15_calendar/internal/grpcserver/converters.go b/hw12_13_14_15_calendar/internal/grpcserver/converters.go index a7f6684..14713ba 100644 --- a/hw12_13_14_15_calendar/internal/grpcserver/converters.go +++ b/hw12_13_14_15_calendar/internal/grpcserver/converters.go @@ -7,7 +7,7 @@ import ( "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/storage/event" ) -func (s Service) buildStorageEvent (pbe *CreateReq) (res event.Event, err error) { +func (s Service) buildStorageEvent(pbe *CreateReq) (res event.Event, err error) { res = event.Event{Title: pbe.Title, Note: pbe.Note, UserID: pbe.UserID} res.Date, err = ptypes.Timestamp(pbe.Date) if err != nil { @@ -41,7 +41,6 @@ func (s Service) buildStorageEventAndID(pbe *UpdateReq) (id event.ID, evt event. return event.ID(pbe.ID), evt, nil } - func (s Service) buildEventList(evtMap map[event.ID]event.Event) ([]*Event, error) { var events = []*Event{} var err error @@ -58,5 +57,5 @@ func (s Service) buildEventList(evtMap map[event.ID]event.Event) ([]*Event, erro func (s Service) buildTimeAndRange(e *GetByDateReq) (start time.Time, qrange string, err error) { date, err := ptypes.Timestamp(e.Date) - return date, string(e.Range), err + return date, e.Range.String(), err } diff --git a/hw12_13_14_15_calendar/internal/grpcserver/handlers.go b/hw12_13_14_15_calendar/internal/grpcserver/handlers.go index 5469b22..28f1ace 100644 --- a/hw12_13_14_15_calendar/internal/grpcserver/handlers.go +++ b/hw12_13_14_15_calendar/internal/grpcserver/handlers.go @@ -2,12 +2,12 @@ package grpcserver import ( "context" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" "github.com/golang/protobuf/ptypes/empty" "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/app" "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/storage/event" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) type Service struct { @@ -33,7 +33,7 @@ func (s Service) Update(ctx context.Context, e *UpdateReq) (*empty.Empty, error) if err != nil { return nil, status.Errorf(codes.Internal, "inconvertible") } - if s.App.Storage.Update(cid, ce)!= nil { + if s.App.Storage.Update(cid, ce) != nil { return nil, status.Errorf(codes.Internal, "storage error: can't update event") } return nil, nil @@ -51,11 +51,11 @@ func (s Service) List(ctx context.Context, e *empty.Empty) (*ListResp, error) { if err != nil { return nil, status.Errorf(codes.Internal, "storage error: can't get list of events") } - l,err := s.buildEventList(tmp) + l, err := s.buildEventList(tmp) if err != nil { return nil, status.Errorf(codes.Internal, "inconvertible") } - return &ListResp{Events: l},nil + return &ListResp{Events: l}, nil } func (s Service) GetByID(ctx context.Context, e *GetByIDReq) (*GetByIDResp, error) { @@ -63,11 +63,11 @@ func (s Service) GetByID(ctx context.Context, e *GetByIDReq) (*GetByIDResp, erro if !ok { return nil, status.Errorf(codes.NotFound, "event not found") } - l,err := s.buildEventList(map[event.ID]event.Event{event.ID(e.ID): tmp}) + l, err := s.buildEventList(map[event.ID]event.Event{event.ID(e.ID): tmp}) if err != nil { return nil, status.Errorf(codes.Internal, "inconvertible") } - return &GetByIDResp{Events: l},nil + return &GetByIDResp{Events: l}, nil } func (s Service) GetByDate(ctx context.Context, e *GetByDateReq) (*GetByDateResp, error) { @@ -79,9 +79,9 @@ func (s Service) GetByDate(ctx context.Context, e *GetByDateReq) (*GetByDateResp if err != nil { return nil, status.Errorf(codes.Internal, "storage error: can't get list of events") } - l,err := s.buildEventList(tmp) + l, err := s.buildEventList(tmp) if err != nil { return nil, status.Errorf(codes.Internal, "inconvertible") } - return &GetByDateResp{Events: l},nil + return &GetByDateResp{Events: l}, nil } diff --git a/hw12_13_14_15_calendar/internal/grpcserver/handlers_test.go b/hw12_13_14_15_calendar/internal/grpcserver/handlers_test.go index 95c2d6e..ac99c3f 100644 --- a/hw12_13_14_15_calendar/internal/grpcserver/handlers_test.go +++ b/hw12_13_14_15_calendar/internal/grpcserver/handlers_test.go @@ -7,43 +7,53 @@ import ( "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/config" "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/logger" store "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/storage" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" "testing" "time" ) -var conf = config.Config{Server: config.Server{ Address: "localhost", Port: "50511" }, Grpc: config.Server{Address: "localhost", Port: "50512"}, Logger: config.Logger{File: "calendar.log", Level: "INFO", MuteStdout: false}, Storage: config.Storage{InMemory: true, SQLHost: "", SQLPort: "", SQLDbase: "", SQLUser: "", SQLPass: ""}} + +var conf = config.Config{Server: config.Server{Address: "localhost", Port: "50511"}, Grpc: config.Server{Address: "localhost", Port: "50512"}, Logger: config.Logger{File: "calendar.log", Level: "INFO", MuteStdout: false}, Storage: config.Storage{InMemory: true, SQLHost: "", SQLPort: "", SQLDbase: "", SQLUser: "", SQLPass: ""}} var storeConf = store.Config(conf.Storage) func TestService(t *testing.T) { log, err := logger.New(conf) - require.NoError(t,err, "can't create logger") + require.NoError(t, err, "can't create logger") srv := Service{App: *app.New(log, store.NewStore(storeConf))} tm, _ := time.Parse("02.01.2006", "01.02.2003") cdate, err := ptypes.TimestampProto(tm) - require.NoError(t,err, "can't convert time to proto") -// Create - step1, err := srv.Create(nil, &CreateReq{Title: "Test event", Date: cdate, Latency: ptypes.DurationProto(time.Hour*24), Note: "First gen", UserID: 1111, NotifyTime: ptypes.DurationProto(time.Minute*5)}) - require.NoError(t,err, "can,t create event") - require.NotEqual(t,step1.ID,0, "message ID may not be a \"0\"") -// GetByID - step2, err := srv.GetByID(nil,&GetByIDReq{ID: step1.ID}) - require.NoError(t,err, "can't get event by id") + require.NoError(t, err, "can't convert time to proto") + // Create + step1, err := srv.Create(nil, &CreateReq{Title: "Test event", Date: cdate, Latency: ptypes.DurationProto(time.Hour * 24), Note: "First gen", UserID: 1111, NotifyTime: ptypes.DurationProto(time.Minute * 5)}) + require.NoError(t, err, "can,t create event") + require.NotEqual(t, step1.ID, 0, "message ID may not be a \"0\"") + // GetByID + step2, err := srv.GetByID(nil, &GetByIDReq{ID: step1.ID}) + require.NoError(t, err, "can't get event by id") require.Equal(t, 1, len(step2.Events), "length of slice in responce must be a \"1\"") - require.Equal(t, &Event{ID: 1,Title: "Test event", Date: cdate, Latency: ptypes.DurationProto(time.Hour*24), Note: "First gen", UserID: 1111, NotifyTime: ptypes.DurationProto(time.Minute*5)},step2.Events[0], "request contains invalid data") -// Update - _, err = srv.Update(nil,&UpdateReq{ID: step1.ID, Event: &Event{Title: "Updated event", Date: cdate, Latency: ptypes.DurationProto(time.Hour*48), Note: "Updated gen", UserID: 2222, NotifyTime: ptypes.DurationProto(time.Minute*10)}}) - require.NoError(t,err, "can't update event") -// List + require.Equal(t, &Event{ID: 1, Title: "Test event", Date: cdate, Latency: ptypes.DurationProto(time.Hour * 24), Note: "First gen", UserID: 1111, NotifyTime: ptypes.DurationProto(time.Minute * 5)}, step2.Events[0], "request contains invalid data") + // Update + _, err = srv.Update(nil, &UpdateReq{ID: step1.ID, Event: &Event{Title: "Updated event", Date: cdate, Latency: ptypes.DurationProto(time.Hour * 48), Note: "Updated gen", UserID: 2222, NotifyTime: ptypes.DurationProto(time.Minute * 10)}}) + require.NoError(t, err, "can't update event") + // List step3, err := srv.List(nil, nil) - require.NoError(t,err, "problem with list") + require.NoError(t, err, "problem with list after Update") require.Equal(t, 1, len(step3.Events), "length of slice in responce must be a \"1\"") - require.Equal(t, &Event{ID: 1,Title: "Updated event", Date: cdate, Latency: ptypes.DurationProto(time.Hour*48), Note: "Updated gen", UserID: 2222, NotifyTime: ptypes.DurationProto(time.Minute*10)},step3.Events[0], "request contains invalid data") -// GetByDate - step4, err := srv.GetByDate(nil,&GetByDateReq{Date: cdate, Range: 1}) - require.NoError(t,err, "problem with GetByDate") + require.Equal(t, &Event{ID: 1, Title: "Updated event", Date: cdate, Latency: ptypes.DurationProto(time.Hour * 48), Note: "Updated gen", UserID: 2222, NotifyTime: ptypes.DurationProto(time.Minute * 10)}, step3.Events[0], "request contains invalid data") + // GetByDate + step4, err := srv.GetByDate(nil, &GetByDateReq{Date: cdate, Range: 0}) + require.NoError(t, err, "problem with GetByDate") require.Equal(t, 1, len(step4.Events), "length of slice in responce must be a \"1\"") - require.Equal(t, &Event{ID: 1,Title: "Updated event", Date: cdate, Latency: ptypes.DurationProto(time.Hour*48), Note: "Updated gen", UserID: 2222, NotifyTime: ptypes.DurationProto(time.Minute*10)},step4.Events[0], "request contains invalid data") -// Delete -// List - -} \ No newline at end of file + require.Equal(t, &Event{ID: 1, Title: "Updated event", Date: cdate, Latency: ptypes.DurationProto(time.Hour * 48), Note: "Updated gen", UserID: 2222, NotifyTime: ptypes.DurationProto(time.Minute * 10)}, step4.Events[0], "request contains invalid data") + // Delete + _, err = srv.Delete(nil, &DeleteReq{ID: step4.Events[0].ID}) + require.NoError(t, err, "problem with Delete") + // List + step5, err := srv.List(nil, nil) + require.NoError(t, err, "problem with list after Delete") + require.Equal(t, 0, len(step5.Events), "length of slice in responce must be a \"0\"") + // GetByID + _, err = srv.GetByID(nil, &GetByIDReq{ID: step4.Events[0].ID}) + require.Error(t, err, status.Errorf(codes.NotFound, "event not found")) +} diff --git a/hw12_13_14_15_calendar/internal/storage/memory/memory.go b/hw12_13_14_15_calendar/internal/storage/memory/memory.go index 09bff9b..4a1d909 100644 --- a/hw12_13_14_15_calendar/internal/storage/memory/memory.go +++ b/hw12_13_14_15_calendar/internal/storage/memory/memory.go @@ -56,9 +56,9 @@ func (s *Storage) GetByDate(startDate time.Time, rng string) (map[event.ID]event defer s.Mu.Unlock() res := make(map[event.ID]event.Event) for k, v := range s.Events { - if (v.Date.After(startDate) && v.Date.Before(endDate)) || - (v.Date.Add(v.Latency).Before(v.Date) && v.Date.Add(v.Latency).After(v.Date)) || - (v.Date.Before(startDate)) && (v.Date.Add(v.Latency).After(endDate)) { + if afterOrEqual(v.Date, startDate) && beforeOrEqual(v.Date, endDate) || + beforeOrEqual(v.Date.Add(v.Latency), v.Date) && afterOrEqual(v.Date.Add(v.Latency), v.Date) || + (beforeOrEqual(v.Date, startDate) && afterOrEqual(v.Date.Add(v.Latency), endDate)) { res[k] = v } } @@ -77,3 +77,11 @@ func getEndDate(startDate time.Time, rng string) time.Time { return startDate } } + +func afterOrEqual(time1 time.Time, time2 time.Time) bool { + return time1.Equal(time2) || time1.After(time2) +} + +func beforeOrEqual(time1 time.Time, time2 time.Time) bool { + return time1.Equal(time2) || time1.Before(time2) +} From 70564467636bfd0b10bd4a6956c54d0c54985f89 Mon Sep 17 00:00:00 2001 From: Andrey Ivanov Date: Thu, 12 Nov 2020 14:26:09 +0300 Subject: [PATCH 14/16] HW13 WIP 011 --- hw12_13_14_15_calendar/Makefile | 3 +- hw12_13_14_15_calendar/go.sum | 283 ++++++++++++++++++ .../internal/grpcserver/converters.go | 6 +- .../internal/grpcserver/handlers_test.go | 172 ++++++++--- 4 files changed, 419 insertions(+), 45 deletions(-) create mode 100644 hw12_13_14_15_calendar/go.sum diff --git a/hw12_13_14_15_calendar/Makefile b/hw12_13_14_15_calendar/Makefile index c055c11..29bfcd5 100644 --- a/hw12_13_14_15_calendar/Makefile +++ b/hw12_13_14_15_calendar/Makefile @@ -16,6 +16,7 @@ install-lint-deps: (which golangci-lint > /dev/null) || curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(shell go env GOPATH)/bin v1.30.0 generate: - protoc -I ./grpcserver --go_out=plugins=grpc:./internal/grpcserver ./grpcserver/grpcserver.proto + protoc -I ./grpcserver --go_out=plugins=grpc:./internal/grpcserver --grpc-gateway_out=logtostderr=true:./internal/grpcserver ./grpcserver/grpcserver.proto + .PHONY: build run test lint \ No newline at end of file diff --git a/hw12_13_14_15_calendar/go.sum b/hw12_13_14_15_calendar/go.sum new file mode 100644 index 0000000..047cc37 --- /dev/null +++ b/hw12_13_14_15_calendar/go.sum @@ -0,0 +1,283 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= +github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= +github.com/amitrai48/logger v0.0.0-20190214092904-448001c055ec h1:tDOPo9NAXCjvoK35HgZyzQSNLmb3chZqN2tnO273Bro= +github.com/amitrai48/logger v0.0.0-20190214092904-448001c055ec/go.mod h1:RZEHP3cxXvQlMuMjkpdh6qXA4b0CpjxnUBNxOpR0r30= +github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= +github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/daixiang0/gci v0.2.4/go.mod h1:+AV8KmHTGxxwp/pY84TLQfFKp2vuKXXJVzF3kD/hfR4= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dmitryt/otus-golang-hw/hw12_13_14_15_calendar v0.0.0-20200916093948-5ca8860569b6/go.mod h1:f//zKg1isd70tsJVPWphzKLXd7pvW4Owmtobh4uhuCQ= +github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= +github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= +github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= +github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= +github.com/go-playground/validator/v10 v10.3.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI= +github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= +github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs= +github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= +github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= +github.com/golang/protobuf v1.4.2 h1:+Z5KGCizgyZCbGh1KZqA0fcLLkwbsjIzS4aV2v7wJX0= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0 h1:/QaMHBdZ26BB3SSst0Iwl10Epc+xhTquomWX0oZEB6w= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/renameio v0.1.0 h1:GOZbcHa3HfsPKPlmyPyN2KEohoMXOhdMbHrvbpl2QaA= +github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/grpc-ecosystem/go-grpc-middleware v1.2.1/go.mod h1:EaizFBKfUKtMIF5iaDEhniwNedqGo9FuLFzppDr3uwI= +github.com/grpc-ecosystem/grpc-gateway v1.14.7/go.mod h1:oYZKL012gGh6LMyg/xA7Q2yq6j8bu0wa+9w14EEthWU= +github.com/grpc-ecosystem/grpc-gateway v1.15.0 h1:ntPNC9TD/6l2XDenJZe6T5lSMg95thpV9sGAqHX4WU8= +github.com/grpc-ecosystem/grpc-gateway v1.15.0/go.mod h1:vO11I9oWA+KsxmfFQPhLnnIb1VDE24M+pdxZFiuZcA8= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/ilyakaznacheev/cleanenv v1.2.5/go.mod h1:/i3yhzwZ3s7hacNERGFwvlhwXMDcaqwIzmayEhbRplk= +github.com/imdario/mergo v0.3.11/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= +github.com/jmoiron/sqlx v1.2.0/go.mod h1:1FEQNm3xlJgrMD+FBdI9+xvCksHtbpVBBw5dYhBSsks= +github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg= +github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q= +github.com/kisielk/gotool v1.0.0 h1:AV2c/EiW3KqPNT9ZKl07ehoAGi4C5/01Cfbblndcapg= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= +github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1 h1:VkoXIwSboBpnk99O/KFauAEILuNHv5DVFKZMBN/gUgw= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= +github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/lib/pq v1.8.0/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= +github.com/mattn/go-sqlite3 v1.9.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= +github.com/onsi/ginkgo v1.14.1/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY= +github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= +github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= +github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= +github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pressly/goose v2.6.0+incompatible/go.mod h1:m+QHWCqxR3k8D9l7qfzuC/djtlfzxr34mozWDYEu1z8= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= +github.com/rogpeppe/go-internal v1.3.0 h1:RR9dF3JtopPvtkroDZuVD7qquD0bnHlKSqaQhgwt8yk= +github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/rs/xid v1.2.1/go.mod h1:+uKXf+4Djp6Md1KODXJxgGQPKngRmWyn10oCKFzNHOQ= +github.com/rs/zerolog v1.15.0/go.mod h1:xYTKnLHcpfU2225ny5qZjxnj9NvkumZYjJHlAThCjNc= +github.com/rs/zerolog v1.20.0/go.mod h1:IzD0RJ65iWH0w97OQQebJEvTZYvsCUm9WVLWBQrJRjo= +github.com/sirupsen/logrus v1.3.0 h1:hI/7Q+DtNZ2kINb6qt/lS+IyXnHQe9e90POfeewL/ME= +github.com/sirupsen/logrus v1.3.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= +github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4= +github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/streadway/amqp v1.0.0/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1 h1:2vfRuCMp5sSVIDSqO8oNnWJq7mPa6KVP3iPIwFBuy8A= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/zenazn/goji v0.9.0/go.mod h1:7S9M489iMyHBNxwZnk9/EHS098H4/F6TATF2mIxtB1Q= +go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= +go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= +go.uber.org/atomic v1.6.0 h1:Ezj3JGmsOnG1MoRWQkPBsKLe9DwWD9QeXzTRzzldNVk= +go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= +go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= +go.uber.org/multierr v1.5.0 h1:KCa4XfM8CWFCpxXRGok+Q0SS/0XBhMDbHHGABQLvD2A= +go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU= +go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee h1:0mgffUl7nfd+FpvXMVz4IDEaUSmT1ysygQC7qYo7sG4= +go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= +go.uber.org/zap v1.9.1/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= +go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= +go.uber.org/zap v1.15.0 h1:ZZCA22JRF2gQE5FoNmhmrf7jeJJ2uhqDUNRYKm8dvmM= +go.uber.org/zap v1.15.0/go.mod h1:Mb2vm2krFEG5DV0W9qcHBYFtp/Wku1cvYaqPsS/WYfc= +golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529 h1:iMGN4xG0cnqj3t+zOM8wUB0BiPKHEwSxEZCvzcbZuvk= +golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20200331195152-e8c3332aa8e5/go.mod h1:4M0jN8W1tt0AVLNr8HDosyJCDCDuyL9N9+3m7wDWgKw= +golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= +golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de h1:5hukYrvBGR8/eNkX5mdUezrA6JiaEZDtJb9Ei+1LlBs= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= +golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e h1:JgcxKXxCjrA2tyDP/aNU9K0Ck5Czfk6C7e2tMw7+bSI= +golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.3.0 h1:RM4zey1++hCTbCVQfnWeKs9/IEsaBLA8vTkd0WVtmH4= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859 h1:R/3boaszxrf1GEUWTVDzSKVwLmSJpwZ1yqXm8j0v2QI= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20191002035440-2ec189313ef0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200421231249-e086a090c8fd/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200625001655-4c5254603344 h1:vGXIOMxbNfDTk/aXCmfdLgkrSV+Z2tcbze+pEc3v5W4= +golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58 h1:8gQV6CLnAEikrhgkHFbMAEhagSSnXWGV915qUMm9mrU= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190412213103-97732733099d h1:+R4KGOnez64A81RvjARKc4UT5/tI9ujCIVX+P5KiHuI= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd h1:xhmwyvizuTgC2qz7ZlMluP20uW+C3Rm0FD/WLDX8884= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200420163511-1957bb5e6d1f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200909081042-eff7692f9009/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190425163242-31fd60d6bfdc/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190828213141-aed303cbaa74/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5 h1:hKsoRgsbwY1NafxrwTs+k64bikrLBkAgPir1TNCj3Zs= +golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200724022722-7017fd6b1305 h1:yaM5S0KcY0lIoZo7Fl+oi91b/DdlU2zuWpfHrpWbCS0= +golang.org/x/tools v0.0.0-20200724022722-7017fd6b1305/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7 h1:9zdDQZ7Thm29KFXgAX/+yaf3eVbP7djjWp/dXAppNCc= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20200423170343-7949de9c1215/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013 h1:+kGHl1aib/qcwaRi1CbqBZ1rk19r85MNUf8HaBghugY= +google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= +google.golang.org/genproto v0.0.0-20200815001618-f69a88009b70 h1:wboULUXGF3c5qdUnKp+6gLAccE6PRpa/czkYvQ4UXv8= +google.golang.org/genproto v0.0.0-20200815001618-f69a88009b70/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= +google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= +google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.32.0 h1:zWTV+LMdc3kaiJMSTOFz2UgSBgx8RNQoTGiZu3fR9S0= +google.golang.org/grpc v1.32.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.0 h1:4MY060fB1DLGMB/7MBTLnwQUY6+F09GEiz6SsrNqyzM= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4= +google.golang.org/protobuf v1.25.0 h1:Ejskq+SyPohKW+1uil0JJMtmHCgJPJ/qWTxr8qp+R4c= +google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/errgo.v2 v2.1.0 h1:0vLT13EuvQ0hNvakwLuFZ/jYrLp5F3kcWHXdRggjCE8= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/natefinch/lumberjack.v2 v2.0.0 h1:1Lc07Kr7qY4U2YPouBjpCLxpiyxIVoxqXgkXLknAOE8= +gopkg.in/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU= +gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.1-2019.2.3 h1:3JgtbtFHMiCmsznwGVTUWbgGov+pVqnlf1dEJTNAXeM= +honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= +olympos.io/encoding/edn v0.0.0-20200308123125-93e3b8dd0e24/go.mod h1:oVgVk4OWVDi43qWBEyGhXgYxt7+ED4iYNpTngSLX2Iw= diff --git a/hw12_13_14_15_calendar/internal/grpcserver/converters.go b/hw12_13_14_15_calendar/internal/grpcserver/converters.go index 14713ba..0c6c67c 100644 --- a/hw12_13_14_15_calendar/internal/grpcserver/converters.go +++ b/hw12_13_14_15_calendar/internal/grpcserver/converters.go @@ -42,15 +42,17 @@ func (s Service) buildStorageEventAndID(pbe *UpdateReq) (id event.ID, evt event. } func (s Service) buildEventList(evtMap map[event.ID]event.Event) ([]*Event, error) { - var events = []*Event{} + events := make([]*Event, len(evtMap)) var err error + var i int for k, v := range evtMap { evt := Event{ID: int64(k), Title: v.Title, Latency: ptypes.DurationProto(v.Latency), Note: v.Note, UserID: v.UserID, NotifyTime: ptypes.DurationProto(v.NotifyTime)} evt.Date, err = ptypes.TimestampProto(v.Date) if err != nil { return nil, err } - events = append(events, &evt) + events[i] = &evt + i++ } return events, err } diff --git a/hw12_13_14_15_calendar/internal/grpcserver/handlers_test.go b/hw12_13_14_15_calendar/internal/grpcserver/handlers_test.go index ac99c3f..c7d2756 100644 --- a/hw12_13_14_15_calendar/internal/grpcserver/handlers_test.go +++ b/hw12_13_14_15_calendar/internal/grpcserver/handlers_test.go @@ -2,13 +2,13 @@ package grpcserver import ( "github.com/golang/protobuf/ptypes" - "github.com/stretchr/testify/require" + "github.com/golang/protobuf/ptypes/timestamp" + "github.com/stretchr/testify/suite" "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/app" "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/config" "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/logger" store "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/storage" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" + oslog "log" "testing" "time" ) @@ -17,43 +17,131 @@ var conf = config.Config{Server: config.Server{Address: "localhost", Port: "5051 var storeConf = store.Config(conf.Storage) -func TestService(t *testing.T) { - log, err := logger.New(conf) - require.NoError(t, err, "can't create logger") - srv := Service{App: *app.New(log, store.NewStore(storeConf))} - tm, _ := time.Parse("02.01.2006", "01.02.2003") - cdate, err := ptypes.TimestampProto(tm) - require.NoError(t, err, "can't convert time to proto") - // Create - step1, err := srv.Create(nil, &CreateReq{Title: "Test event", Date: cdate, Latency: ptypes.DurationProto(time.Hour * 24), Note: "First gen", UserID: 1111, NotifyTime: ptypes.DurationProto(time.Minute * 5)}) - require.NoError(t, err, "can,t create event") - require.NotEqual(t, step1.ID, 0, "message ID may not be a \"0\"") - // GetByID - step2, err := srv.GetByID(nil, &GetByIDReq{ID: step1.ID}) - require.NoError(t, err, "can't get event by id") - require.Equal(t, 1, len(step2.Events), "length of slice in responce must be a \"1\"") - require.Equal(t, &Event{ID: 1, Title: "Test event", Date: cdate, Latency: ptypes.DurationProto(time.Hour * 24), Note: "First gen", UserID: 1111, NotifyTime: ptypes.DurationProto(time.Minute * 5)}, step2.Events[0], "request contains invalid data") - // Update - _, err = srv.Update(nil, &UpdateReq{ID: step1.ID, Event: &Event{Title: "Updated event", Date: cdate, Latency: ptypes.DurationProto(time.Hour * 48), Note: "Updated gen", UserID: 2222, NotifyTime: ptypes.DurationProto(time.Minute * 10)}}) - require.NoError(t, err, "can't update event") - // List - step3, err := srv.List(nil, nil) - require.NoError(t, err, "problem with list after Update") - require.Equal(t, 1, len(step3.Events), "length of slice in responce must be a \"1\"") - require.Equal(t, &Event{ID: 1, Title: "Updated event", Date: cdate, Latency: ptypes.DurationProto(time.Hour * 48), Note: "Updated gen", UserID: 2222, NotifyTime: ptypes.DurationProto(time.Minute * 10)}, step3.Events[0], "request contains invalid data") - // GetByDate - step4, err := srv.GetByDate(nil, &GetByDateReq{Date: cdate, Range: 0}) - require.NoError(t, err, "problem with GetByDate") - require.Equal(t, 1, len(step4.Events), "length of slice in responce must be a \"1\"") - require.Equal(t, &Event{ID: 1, Title: "Updated event", Date: cdate, Latency: ptypes.DurationProto(time.Hour * 48), Note: "Updated gen", UserID: 2222, NotifyTime: ptypes.DurationProto(time.Minute * 10)}, step4.Events[0], "request contains invalid data") - // Delete - _, err = srv.Delete(nil, &DeleteReq{ID: step4.Events[0].ID}) - require.NoError(t, err, "problem with Delete") - // List - step5, err := srv.List(nil, nil) - require.NoError(t, err, "problem with list after Delete") - require.Equal(t, 0, len(step5.Events), "length of slice in responce must be a \"0\"") - // GetByID - _, err = srv.GetByID(nil, &GetByIDReq{ID: step4.Events[0].ID}) - require.Error(t, err, status.Errorf(codes.NotFound, "event not found")) +var testEvt1 = Event{Title: "Test event 1", Date: buildTimestampWraped("01.01.2001"), Latency: ptypes.DurationProto(time.Hour * 24 * 1), Note: "First gen", UserID: 1111, NotifyTime: ptypes.DurationProto(time.Minute * 10)} +var testEvt2 = Event{Title: "Test event 2", Date: buildTimestampWraped("02.02.2002"), Latency: ptypes.DurationProto(time.Hour * 24 * 2), Note: "Second gen", UserID: 2222, NotifyTime: ptypes.DurationProto(time.Minute * 20)} +var testEvt3 = Event{Title: "Test event 3", Date: buildTimestampWraped("03.03.2003"), Latency: ptypes.DurationProto(time.Hour * 24 * 3), Note: "Third gen", UserID: 3333, NotifyTime: ptypes.DurationProto(time.Minute * 30)} + +func TestCalendarSuite(t *testing.T) { + suite.Run(t, new(TestSuite)) +} + +type TestSuite struct { + suite.Suite + srv Service +} + +func (suite *TestSuite) SetupTest() { + log, err := logger.New(conf) + if err != nil { + oslog.Fatal("can't init logger") + } + suite.srv = Service{App: *app.New(log, store.NewStore(storeConf))} +} + +func (s *TestSuite) TestCreateEvent() { + controlEvent := testEvt1 + s.createEvent(&controlEvent) + createdEvent := s.getEventByDate(controlEvent.Date) + s.Equal(&controlEvent, createdEvent[0]) +} + +func (s *TestSuite) TestUpdateEvent() { + oldEvent := testEvt1 + s.createEvent(&oldEvent) + newEvent := testEvt2 + s.updateEvent(oldEvent, newEvent) + updatedEvent := s.getEventByID(oldEvent.ID) + s.Equal(newEvent.Title, updatedEvent.Title) +} + +func (s *TestSuite) TestDeleteEvent() { + testEvent := testEvt1 + s.createEvent(&testEvent) + createdEvent := s.getEventByDate(testEvent.Date) + s.Equal(&testEvent, createdEvent[0]) + s.deleteEvent(createdEvent[0].ID) + controlEvent := s.getEventByDate(testEvent.Date) + s.Equal(0, len(controlEvent)) +} + +func (s *TestSuite) TestListEvent() { + testEvent := testEvt1 + s.createEvent(&testEvent) + eventList := s.listEvents() + s.Equal(1, len(eventList)) + s.Equal(testEvt1.Title, eventList[0].Title) +} + +func (s *TestSuite) TestGetEventByID() { + testEvent := testEvt1 + s.createEvent(&testEvent) + eventList := s.getEventByID(testEvent.ID) + s.Equal(testEvent.Title, eventList.Title) +} + +func (s *TestSuite) TestGetEventByDate() { + testEvent := testEvt1 + s.createEvent(&testEvent) + eventList := s.getEventByDate(testEvent.Date) + s.Equal(1, len(eventList)) + s.Equal(testEvent.Title, eventList[0].Title) +} + +func (s *TestSuite) createEvent(ev *Event) { + createdEvent, err := s.srv.Create(nil, eventToCreateRequest(*ev)) + s.NoError(err, "can,t create event") + s.NotEqual(createdEvent.ID, 0, `message ID may not be a "0"`) + ev.ID = createdEvent.ID +} + +func (s *TestSuite) updateEvent(oldEvent Event, newEvent Event) { + _, err := s.srv.Update(nil, eventToUpdateRequest(oldEvent, newEvent)) + s.NoError(err, "can,t update event") +} + +func (s *TestSuite) deleteEvent(i int64) { + _, err := s.srv.Delete(nil, &DeleteReq{ID: i}) + s.NoError(err, "can,t delete event") +} + +func (s *TestSuite) listEvents() []*Event { + r, err := s.srv.List(nil, nil) + s.NoError(err, "can't list events") + return r.Events + +} + +func (s *TestSuite) getEventByID(i int64) Event { + r, err := s.srv.GetByID(nil, idToGetByIDRequest(i)) + s.NoError(err, "can't get event by id") + s.Equal(1, len(r.Events), "length of slice in responce must be a \"1\"") + return *r.Events[0] +} + +func (s *TestSuite) getEventByDate(d *timestamp.Timestamp) []*Event { + r, err := s.srv.GetByDate(nil, tstampToGetByDateRequest(d)) + s.NoError(err, "can't get event by date") + return r.Events +} + +func eventToCreateRequest(ev Event) (req *CreateReq) { + return &CreateReq{Title: ev.Title, Date: ev.Date, Latency: ev.Latency, Note: ev.Note, UserID: ev.UserID, NotifyTime: ev.NotifyTime} +} + +func eventToUpdateRequest(oldEvent Event, newEvent Event) (req *UpdateReq) { + return &UpdateReq{ID: oldEvent.ID, Event: &Event{Title: newEvent.Title, Date: newEvent.Date, Latency: newEvent.Latency, Note: newEvent.Note, UserID: newEvent.UserID, NotifyTime: newEvent.NotifyTime}} +} + +func idToGetByIDRequest(i int64) *GetByIDReq { + return &GetByIDReq{ID: i} +} + +func tstampToGetByDateRequest(t *timestamp.Timestamp) *GetByDateReq { + return &GetByDateReq{Date: t, Range: 0} +} + +func buildTimestampWraped(in string) *timestamp.Timestamp { + tm, _ := time.Parse("02.01.2006", in) + cdate, _ := ptypes.TimestampProto(tm) + return cdate } From bf51b3e364bc2b1ea43050fe767289cccb977adc Mon Sep 17 00:00:00 2001 From: Andrey Ivanov Date: Thu, 12 Nov 2020 18:36:25 +0300 Subject: [PATCH 15/16] HW13 Completed --- hw12_13_14_15_calendar/cmd/calendar/main.go | 33 ++++++++++++++++++- hw12_13_14_15_calendar/configs/config.toml | 4 +++ hw12_13_14_15_calendar/go.sum | 14 ++++++++ .../internal/config/config.go | 3 +- .../internal/grpcserver/handlers_test.go | 2 +- .../internal/grpcserver/server.go | 2 +- 6 files changed, 54 insertions(+), 4 deletions(-) diff --git a/hw12_13_14_15_calendar/cmd/calendar/main.go b/hw12_13_14_15_calendar/cmd/calendar/main.go index 30e8acf..0a567d0 100644 --- a/hw12_13_14_15_calendar/cmd/calendar/main.go +++ b/hw12_13_14_15_calendar/cmd/calendar/main.go @@ -1,10 +1,17 @@ package main import ( + "context" "flag" + "github.com/dmitryt/otus-golang-hw/hw12_13_14_15_calendar/service/server" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "google.golang.org/grpc" oslog "log" + "net" + "net/http" "os" "os/signal" + "syscall" _ "github.com/go-sql-driver/mysql" "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/app" @@ -59,8 +66,32 @@ func main() { } }() + grpcDiler, err := grpc.Dial(net.JoinHostPort(conf.HTTP.Address, conf.HTTP.Port), grpc.WithInsecure()) + if err != nil { + log.Errorf("can't dial grpc server: " + err.Error()) + os.Exit(1) + } + defer grpcDiler.Close() + + grpcGwRouter := runtime.NewServeMux() + + if err = server.RegisterCalendarHandler(context.Background(), grpcGwRouter, grpcDiler); err != nil { + log.Errorf("can't register handlers for grpc-gateway: " + err.Error()) + os.Exit(1) + } + + mux := http.NewServeMux() + mux.Handle("/", grpcGwRouter) + go func() { + log.Infof("start webAPI server") + if err := http.ListenAndServe(net.JoinHostPort(conf.HTTP.Address, conf.HTTP.Port), mux); err != nil { + log.Errorf("failed to start webAPI server: " + err.Error()) + os.Exit(1) + } + }() + signals := make(chan os.Signal, 1) - signal.Notify(signals) + signal.Notify(signals,syscall.SIGINT, syscall.SIGHUP) <-signals signal.Stop(signals) serverGRPC.Stop() diff --git a/hw12_13_14_15_calendar/configs/config.toml b/hw12_13_14_15_calendar/configs/config.toml index a94e212..d6b1cda 100644 --- a/hw12_13_14_15_calendar/configs/config.toml +++ b/hw12_13_14_15_calendar/configs/config.toml @@ -6,6 +6,10 @@ Port = "8080" Address = "localhost" Port = "50051" +[Http] +Address = "localhost" +Port = "50051" + [Logger] File = "./calendar.log" Level = "INFO" diff --git a/hw12_13_14_15_calendar/go.sum b/hw12_13_14_15_calendar/go.sum index 047cc37..81a18a5 100644 --- a/hw12_13_14_15_calendar/go.sum +++ b/hw12_13_14_15_calendar/go.sum @@ -16,6 +16,7 @@ github.com/daixiang0/gci v0.2.4/go.mod h1:+AV8KmHTGxxwp/pY84TLQfFKp2vuKXXJVzF3kD github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dmitryt/otus-golang-hw/hw12_13_14_15_calendar v0.0.0-20200916093948-5ca8860569b6 h1:kbX6KBmjfEYzBbEk2/bfAXgocxhzFQXH+5Tpr7gNg0k= github.com/dmitryt/otus-golang-hw/hw12_13_14_15_calendar v0.0.0-20200916093948-5ca8860569b6/go.mod h1:f//zKg1isd70tsJVPWphzKLXd7pvW4Owmtobh4uhuCQ= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= @@ -28,8 +29,11 @@ github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2 github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q= github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= +github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no= github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= +github.com/go-playground/validator/v10 v10.3.0 h1:nZU+7q+yJoFmwvNgv/LnPUkwPal62+b2xXj0AU1Es7o= github.com/go-playground/validator/v10 v10.3.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI= github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs= @@ -58,14 +62,19 @@ github.com/google/go-cmp v0.5.0 h1:/QaMHBdZ26BB3SSst0Iwl10Epc+xhTquomWX0oZEB6w= github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/renameio v0.1.0 h1:GOZbcHa3HfsPKPlmyPyN2KEohoMXOhdMbHrvbpl2QaA= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/grpc-ecosystem/go-grpc-middleware v1.2.1 h1:V59tBiPuMkySHwJkuq/OYkK0WnOLwCwD3UkTbEMr12U= github.com/grpc-ecosystem/go-grpc-middleware v1.2.1/go.mod h1:EaizFBKfUKtMIF5iaDEhniwNedqGo9FuLFzppDr3uwI= github.com/grpc-ecosystem/grpc-gateway v1.14.7/go.mod h1:oYZKL012gGh6LMyg/xA7Q2yq6j8bu0wa+9w14EEthWU= github.com/grpc-ecosystem/grpc-gateway v1.15.0 h1:ntPNC9TD/6l2XDenJZe6T5lSMg95thpV9sGAqHX4WU8= github.com/grpc-ecosystem/grpc-gateway v1.15.0/go.mod h1:vO11I9oWA+KsxmfFQPhLnnIb1VDE24M+pdxZFiuZcA8= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/ilyakaznacheev/cleanenv v1.2.5 h1:/SlcF9GaIvefWqFJzsccGG/NJdoaAwb7Mm7ImzhO3DM= github.com/ilyakaznacheev/cleanenv v1.2.5/go.mod h1:/i3yhzwZ3s7hacNERGFwvlhwXMDcaqwIzmayEhbRplk= +github.com/imdario/mergo v0.3.11 h1:3tnifQM4i+fbajXKBHXWEH+KvNHqojZ778UH75j3bGA= github.com/imdario/mergo v0.3.11/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= +github.com/jmoiron/sqlx v1.2.0 h1:41Ip0zITnmWNR/vHV+S4m+VoUivnWY5E4OJfLZjCJMA= github.com/jmoiron/sqlx v1.2.0/go.mod h1:1FEQNm3xlJgrMD+FBdI9+xvCksHtbpVBBw5dYhBSsks= +github.com/joho/godotenv v1.3.0 h1:Zjp+RcGpHhGlrMbJzXTrZZPrWj+1vfm90La1wgB6Bhc= github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg= github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q= github.com/kisielk/gotool v1.0.0 h1:AV2c/EiW3KqPNT9ZKl07ehoAGi4C5/01Cfbblndcapg= @@ -80,8 +89,10 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y= github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/lib/pq v1.8.0 h1:9xohqzkUwzR4Ga4ivdTcawVS89YSDVxXMa3xJX3cGzg= github.com/lib/pq v1.8.0/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/mattn/go-sqlite3 v1.9.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= @@ -104,6 +115,7 @@ github.com/rogpeppe/go-internal v1.3.0 h1:RR9dF3JtopPvtkroDZuVD7qquD0bnHlKSqaQhg github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rs/xid v1.2.1/go.mod h1:+uKXf+4Djp6Md1KODXJxgGQPKngRmWyn10oCKFzNHOQ= github.com/rs/zerolog v1.15.0/go.mod h1:xYTKnLHcpfU2225ny5qZjxnj9NvkumZYjJHlAThCjNc= +github.com/rs/zerolog v1.20.0 h1:38k9hgtUBdxFwE34yS8rTHmHBa4eN16E4DJlv177LNs= github.com/rs/zerolog v1.20.0/go.mod h1:IzD0RJ65iWH0w97OQQebJEvTZYvsCUm9WVLWBQrJRjo= github.com/sirupsen/logrus v1.3.0 h1:hI/7Q+DtNZ2kINb6qt/lS+IyXnHQe9e90POfeewL/ME= github.com/sirupsen/logrus v1.3.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= @@ -199,6 +211,7 @@ golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd h1:xhmwyvizuTgC2qz7ZlMluP20u golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200420163511-1957bb5e6d1f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200909081042-eff7692f9009 h1:W0lCpv29Hv0UaM1LXb9QlBHLNP8UFfcKjblhVCWftOM= golang.org/x/sys v0.0.0-20200909081042-eff7692f9009/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -280,4 +293,5 @@ honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWh honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.1-2019.2.3 h1:3JgtbtFHMiCmsznwGVTUWbgGov+pVqnlf1dEJTNAXeM= honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= +olympos.io/encoding/edn v0.0.0-20200308123125-93e3b8dd0e24 h1:sreVOrDp0/ezb0CHKVek/l7YwpxPJqv+jT3izfSphA4= olympos.io/encoding/edn v0.0.0-20200308123125-93e3b8dd0e24/go.mod h1:oVgVk4OWVDi43qWBEyGhXgYxt7+ED4iYNpTngSLX2Iw= diff --git a/hw12_13_14_15_calendar/internal/config/config.go b/hw12_13_14_15_calendar/internal/config/config.go index 30440bc..3fb0378 100644 --- a/hw12_13_14_15_calendar/internal/config/config.go +++ b/hw12_13_14_15_calendar/internal/config/config.go @@ -9,7 +9,8 @@ import ( type Config struct { Server Server - Grpc Server + GRPC Server + HTTP Server Logger Logger Storage Storage } diff --git a/hw12_13_14_15_calendar/internal/grpcserver/handlers_test.go b/hw12_13_14_15_calendar/internal/grpcserver/handlers_test.go index c7d2756..dea031a 100644 --- a/hw12_13_14_15_calendar/internal/grpcserver/handlers_test.go +++ b/hw12_13_14_15_calendar/internal/grpcserver/handlers_test.go @@ -13,7 +13,7 @@ import ( "time" ) -var conf = config.Config{Server: config.Server{Address: "localhost", Port: "50511"}, Grpc: config.Server{Address: "localhost", Port: "50512"}, Logger: config.Logger{File: "calendar.log", Level: "INFO", MuteStdout: false}, Storage: config.Storage{InMemory: true, SQLHost: "", SQLPort: "", SQLDbase: "", SQLUser: "", SQLPass: ""}} +var conf = config.Config{Server: config.Server{Address: "localhost", Port: "50511"}, GRPC: config.Server{Address: "localhost", Port: "50512"}, Logger: config.Logger{File: "calendar.log", Level: "INFO", MuteStdout: false}, Storage: config.Storage{InMemory: true, SQLHost: "", SQLPort: "", SQLDbase: "", SQLUser: "", SQLPass: ""}} var storeConf = store.Config(conf.Storage) diff --git a/hw12_13_14_15_calendar/internal/grpcserver/server.go b/hw12_13_14_15_calendar/internal/grpcserver/server.go index 4c455b1..7a3411a 100644 --- a/hw12_13_14_15_calendar/internal/grpcserver/server.go +++ b/hw12_13_14_15_calendar/internal/grpcserver/server.go @@ -19,7 +19,7 @@ func New(app *app.App) Server { func (s *Server) Start(conf config.Config) error { s.app.Logger.Infof("GRPC server starting") - listnGrpc, err := net.Listen("tcp", net.JoinHostPort(conf.Grpc.Address, conf.Grpc.Port)) + listnGrpc, err := net.Listen("tcp", net.JoinHostPort(conf.GRPC.Address, conf.GRPC.Port)) RegisterGrpcServer(s.s, &Service{}) if err != nil { return err From b72c769dc8d7e7374796e8ef88f6dac71ff0104f Mon Sep 17 00:00:00 2001 From: Andrey Ivanov Date: Sat, 14 Nov 2020 19:28:18 +0300 Subject: [PATCH 16/16] HW13 Completed --- hw12_13_14_15_calendar/cmd/calendar/main.go | 17 +- hw12_13_14_15_calendar/configs/config.toml | 8 +- hw12_13_14_15_calendar/go.sum | 1 + .../grpcserver/google/api/annotations.proto | 31 ++ .../grpcserver/google/api/http.proto | 318 +++++++++++++++ .../grpcserver/google/api/httpbody.proto | 78 ++++ .../grpcserver/grpcserver.proto | 39 +- .../internal/config/config.go | 1 - .../internal/grpcserver/grpcserver.pb.go | 74 ++-- .../internal/grpcserver/grpcserver.pb.gw.go | 375 ++++++++++++++++++ .../internal/grpcserver/handlers_test.go | 14 +- .../internal/server/http/http.go | 33 -- 12 files changed, 891 insertions(+), 98 deletions(-) create mode 100755 hw12_13_14_15_calendar/grpcserver/google/api/annotations.proto create mode 100755 hw12_13_14_15_calendar/grpcserver/google/api/http.proto create mode 100755 hw12_13_14_15_calendar/grpcserver/google/api/httpbody.proto create mode 100644 hw12_13_14_15_calendar/internal/grpcserver/grpcserver.pb.gw.go delete mode 100644 hw12_13_14_15_calendar/internal/server/http/http.go diff --git a/hw12_13_14_15_calendar/cmd/calendar/main.go b/hw12_13_14_15_calendar/cmd/calendar/main.go index 0a567d0..1a4ffe1 100644 --- a/hw12_13_14_15_calendar/cmd/calendar/main.go +++ b/hw12_13_14_15_calendar/cmd/calendar/main.go @@ -3,7 +3,6 @@ package main import ( "context" "flag" - "github.com/dmitryt/otus-golang-hw/hw12_13_14_15_calendar/service/server" "github.com/grpc-ecosystem/grpc-gateway/runtime" "google.golang.org/grpc" oslog "log" @@ -18,7 +17,6 @@ import ( "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/config" "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/grpcserver" "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/logger" - internalhttp "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/server/http" store "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/storage" ) @@ -50,14 +48,6 @@ func main() { calendar := app.New(log, st) - serverHTTP := internalhttp.NewServer(calendar, conf.Server.Address, conf.Server.Port) - go func() { - if err := serverHTTP.Start(); err != nil { - log.Errorf("failed to start http server: " + err.Error()) - os.Exit(1) - } - }() - serverGRPC := grpcserver.New(calendar) go func() { if err := serverGRPC.Start(conf); err != nil { @@ -75,7 +65,7 @@ func main() { grpcGwRouter := runtime.NewServeMux() - if err = server.RegisterCalendarHandler(context.Background(), grpcGwRouter, grpcDiler); err != nil { + if err = grpcserver.RegisterGrpcHandler(context.Background(), grpcGwRouter, grpcDiler); err != nil { log.Errorf("can't register handlers for grpc-gateway: " + err.Error()) os.Exit(1) } @@ -91,11 +81,8 @@ func main() { }() signals := make(chan os.Signal, 1) - signal.Notify(signals,syscall.SIGINT, syscall.SIGHUP) + signal.Notify(signals,syscall.SIGINT) <-signals signal.Stop(signals) serverGRPC.Stop() - if err := serverHTTP.Stop(); err != nil { - log.Errorf("failed to stop http server: " + err.Error()) - } } diff --git a/hw12_13_14_15_calendar/configs/config.toml b/hw12_13_14_15_calendar/configs/config.toml index d6b1cda..4e7bb55 100644 --- a/hw12_13_14_15_calendar/configs/config.toml +++ b/hw12_13_14_15_calendar/configs/config.toml @@ -1,14 +1,10 @@ -[Server] -Address = "localhost" -Port = "8080" - [Grpc] Address = "localhost" Port = "50051" -[Http] +[HTTP] Address = "localhost" -Port = "50051" +Port = "50052" [Logger] File = "./calendar.log" diff --git a/hw12_13_14_15_calendar/go.sum b/hw12_13_14_15_calendar/go.sum index 81a18a5..500aaee 100644 --- a/hw12_13_14_15_calendar/go.sum +++ b/hw12_13_14_15_calendar/go.sum @@ -131,6 +131,7 @@ github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJy github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/tiburon-777/HW_OTUS v0.0.0-20200927064133-fc19ac2e8966 h1:LjBeW5xHnZQP7ZlViMBSaKP+HJhLSkOdSj7K7lXdbzg= github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/zenazn/goji v0.9.0/go.mod h1:7S9M489iMyHBNxwZnk9/EHS098H4/F6TATF2mIxtB1Q= go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= diff --git a/hw12_13_14_15_calendar/grpcserver/google/api/annotations.proto b/hw12_13_14_15_calendar/grpcserver/google/api/annotations.proto new file mode 100755 index 0000000..18dcf20 --- /dev/null +++ b/hw12_13_14_15_calendar/grpcserver/google/api/annotations.proto @@ -0,0 +1,31 @@ +// Copyright (c) 2015, Google Inc. +// +// 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/hw12_13_14_15_calendar/grpcserver/google/api/http.proto b/hw12_13_14_15_calendar/grpcserver/google/api/http.proto new file mode 100755 index 0000000..61168c3 --- /dev/null +++ b/hw12_13_14_15_calendar/grpcserver/google/api/http.proto @@ -0,0 +1,318 @@ +// Copyright 2018 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 parmeters 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; +} + +// `HttpRule` defines the mapping of an RPC method to one or more HTTP +// REST API methods. The mapping specifies how different portions of the RPC +// request message are mapped to URL path, URL query parameters, and +// HTTP request body. The mapping is typically specified as an +// `google.api.http` annotation on the RPC method, +// see "google/api/annotations.proto" for details. +// +// The mapping consists of a field specifying the path template and +// method kind. The path template can refer to fields in the request +// message, as in the example below which describes a REST GET +// operation on a resource collection of messages: +// +// +// service Messaging { +// rpc GetMessage(GetMessageRequest) returns (Message) { +// option (google.api.http).get = "/v1/messages/{message_id}/{sub.subfield}"; +// } +// } +// message GetMessageRequest { +// message SubMessage { +// string subfield = 1; +// } +// string message_id = 1; // mapped to the URL +// SubMessage sub = 2; // `sub.subfield` is url-mapped +// } +// message Message { +// string text = 1; // content of the resource +// } +// +// The same http annotation can alternatively be expressed inside the +// `GRPC API Configuration` YAML file. +// +// http: +// rules: +// - selector: .Messaging.GetMessage +// get: /v1/messages/{message_id}/{sub.subfield} +// +// This definition enables an automatic, bidrectional mapping of HTTP +// JSON to RPC. Example: +// +// HTTP | RPC +// -----|----- +// `GET /v1/messages/123456/foo` | `GetMessage(message_id: "123456" sub: SubMessage(subfield: "foo"))` +// +// In general, not only fields but also field paths can be referenced +// from a path pattern. Fields mapped to the path pattern cannot be +// repeated and must have a primitive (non-message) type. +// +// Any fields in the request message which are not bound by the path +// pattern automatically become (optional) HTTP query +// parameters. Assume the following definition of the request message: +// +// +// 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 the URL +// int64 revision = 2; // becomes a parameter +// SubMessage sub = 3; // `sub.subfield` becomes a parameter +// } +// +// +// This enables a HTTP JSON to RPC mapping as below: +// +// HTTP | RPC +// -----|----- +// `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 HTTP parameters must have a +// primitive type or a repeated primitive type. Message types are not +// allowed. In the case of a repeated type, the parameter can be +// repeated in the URL, as in `...?param=A¶m=B`. +// +// For HTTP method kinds which 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) = { +// put: "/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 | RPC +// -----|----- +// `PUT /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) = { +// put: "/v1/messages/{message_id}" +// body: "*" +// }; +// } +// } +// message Message { +// string message_id = 1; +// string text = 2; +// } +// +// +// The following HTTP JSON to RPC mapping is enabled: +// +// HTTP | RPC +// -----|----- +// `PUT /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 of +// 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 | RPC +// -----|----- +// `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 +// +// The rules for mapping HTTP path, query parameters, and body fields +// to the request message are as follows: +// +// 1. The `body` field specifies either `*` or a field path, or is +// omitted. If omitted, it indicates there is no HTTP request body. +// 2. Leaf fields (recursive expansion of nested messages in the +// request) can be classified into three types: +// (a) Matched in the URL template. +// (b) Covered by body (if body is `*`, everything except (a) fields; +// else everything under the body field) +// (c) All other fields. +// 3. URL query parameters found in the HTTP request are mapped to (c) fields. +// 4. Any body sent with an HTTP request can contain only (b) fields. +// +// The syntax of the path template is as follows: +// +// Template = "/" Segments [ Verb ] ; +// Segments = Segment { "/" Segment } ; +// Segment = "*" | "**" | LITERAL | Variable ; +// Variable = "{" FieldPath [ "=" Segments ] "}" ; +// FieldPath = IDENT { "." IDENT } ; +// Verb = ":" LITERAL ; +// +// The syntax `*` matches a single path segment. The syntax `**` matches zero +// or more path segments, which must be the last part of the path except the +// `Verb`. The syntax `LITERAL` matches literal text in the path. +// +// 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=*}`. +// +// If a variable contains exactly one path segment, such as `"{var}"` or +// `"{var=*}"`, when such a variable is expanded into a URL path, all characters +// except `[-_.~0-9a-zA-Z]` are percent-encoded. Such variables show up in the +// Discovery Document as `{var}`. +// +// If a variable contains one or more path segments, such as `"{var=foo/*}"` +// or `"{var=**}"`, when such a variable is expanded into a URL path, all +// characters except `[-_.~/0-9a-zA-Z]` are percent-encoded. Such variables +// show up in the Discovery Document as `{+var}`. +// +// NOTE: While the single segment variable matches the semantics of +// [RFC 6570](https://tools.ietf.org/html/rfc6570) Section 3.2.2 +// Simple String Expansion, the multi segment variable **does not** match +// RFC 6570 Reserved Expansion. The reason is that the Reserved Expansion +// does not expand special characters like `?` and `#`, which would lead +// to invalid URLs. +// +// NOTE: the field paths in variables and in the `body` must not refer to +// repeated fields or map fields. +message HttpRule { + // Selects methods 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 { + // Used for listing and getting information about resources. + string get = 2; + + // Used for updating a resource. + string put = 3; + + // Used for creating a resource. + string post = 4; + + // Used for deleting a resource. + string delete = 5; + + // 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 body, or + // `*` for mapping all fields not captured by the path pattern to the HTTP + // body. NOTE: the referred field must not be a repeated field and must be + // present at the top-level of request message type. + string body = 7; + + // Optional. The name of the response field whose value is mapped to the HTTP + // body of response. Other response fields are ignored. When + // not set, the response message will be used as HTTP body of response. + 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 diff --git a/hw12_13_14_15_calendar/grpcserver/google/api/httpbody.proto b/hw12_13_14_15_calendar/grpcserver/google/api/httpbody.proto new file mode 100755 index 0000000..4428515 --- /dev/null +++ b/hw12_13_14_15_calendar/grpcserver/google/api/httpbody.proto @@ -0,0 +1,78 @@ +// Copyright 2018 Google LLC. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +syntax = "proto3"; + +package google.api; + +import "google/protobuf/any.proto"; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/api/httpbody;httpbody"; +option java_multiple_files = true; +option java_outer_classname = "HttpBodyProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +// Message that represents an arbitrary HTTP body. It should only be used for +// payload formats that can't be represented as JSON, such as raw binary or +// an HTML page. +// +// +// This message can be used both in streaming and non-streaming API methods in +// the request as well as the response. +// +// It can be used as a top-level request field, which is convenient if one +// wants to extract parameters from either the URL or HTTP template into the +// request fields and also want access to the raw HTTP body. +// +// Example: +// +// message GetResourceRequest { +// // A unique request id. +// string request_id = 1; +// +// // The raw HTTP body is bound to this field. +// google.api.HttpBody http_body = 2; +// } +// +// service ResourceService { +// rpc GetResource(GetResourceRequest) returns (google.api.HttpBody); +// rpc UpdateResource(google.api.HttpBody) returns +// (google.protobuf.Empty); +// } +// +// Example with streaming methods: +// +// service CaldavService { +// rpc GetCalendar(stream google.api.HttpBody) +// returns (stream google.api.HttpBody); +// rpc UpdateCalendar(stream google.api.HttpBody) +// returns (stream google.api.HttpBody); +// } +// +// Use of this type only changes how the request and response bodies are +// handled, all other features will continue to work unchanged. +message HttpBody { + // The HTTP Content-Type header value specifying the content type of the body. + string content_type = 1; + + // The HTTP request/response body as raw binary. + bytes data = 2; + + // Application specific response metadata. Must be set in the first response + // for streaming APIs. + repeated google.protobuf.Any extensions = 3; +} \ No newline at end of file diff --git a/hw12_13_14_15_calendar/grpcserver/grpcserver.proto b/hw12_13_14_15_calendar/grpcserver/grpcserver.proto index f8e0ff3..e37a601 100644 --- a/hw12_13_14_15_calendar/grpcserver/grpcserver.proto +++ b/hw12_13_14_15_calendar/grpcserver/grpcserver.proto @@ -7,15 +7,42 @@ option go_package = "grpcserver"; import "google/protobuf/timestamp.proto"; import "google/protobuf/duration.proto"; import "google/protobuf/empty.proto"; +import "google/api/annotations.proto"; service grpc { - rpc Create(CreateReq) returns (CreateRsp) {} - rpc Update(UpdateReq) returns (google.protobuf.Empty) {} - rpc Delete(DeleteReq) returns (google.protobuf.Empty) {} - rpc List(google.protobuf.Empty) returns (ListResp) {} - rpc GetByID(GetByIDReq) returns (GetByIDResp) {} - rpc GetByDate(GetByDateReq) returns (GetByDateResp) {} + rpc Create(CreateReq) returns (CreateRsp) { + option (google.api.http) = { + post: "/events", + body: "*", + }; + } + rpc Update(UpdateReq) returns (google.protobuf.Empty) { + option (google.api.http) = { + put: "/events/{ID}", + body: "*", + }; + } + rpc Delete(DeleteReq) returns (google.protobuf.Empty) { + option (google.api.http) = { + delete: "/events/{ID}" + }; + } + rpc List(google.protobuf.Empty) returns (ListResp) { + option (google.api.http) = { + get: "/events" + }; + } + rpc GetByID(GetByIDReq) returns (GetByIDResp) { + option (google.api.http) = { + get: "/events/{ID}" + }; + } + rpc GetByDate(GetByDateReq) returns (GetByDateResp) { + option (google.api.http) = { + post: "/events/{Range}/{Date}" + }; + } } enum QueryRange { diff --git a/hw12_13_14_15_calendar/internal/config/config.go b/hw12_13_14_15_calendar/internal/config/config.go index 3fb0378..bf7e135 100644 --- a/hw12_13_14_15_calendar/internal/config/config.go +++ b/hw12_13_14_15_calendar/internal/config/config.go @@ -8,7 +8,6 @@ import ( ) type Config struct { - Server Server GRPC Server HTTP Server Logger Logger diff --git a/hw12_13_14_15_calendar/internal/grpcserver/grpcserver.pb.go b/hw12_13_14_15_calendar/internal/grpcserver/grpcserver.pb.go index e1d1153..910758a 100644 --- a/hw12_13_14_15_calendar/internal/grpcserver/grpcserver.pb.go +++ b/hw12_13_14_15_calendar/internal/grpcserver/grpcserver.pb.go @@ -10,6 +10,7 @@ import ( duration "github.com/golang/protobuf/ptypes/duration" empty "github.com/golang/protobuf/ptypes/empty" timestamp "github.com/golang/protobuf/ptypes/timestamp" + _ "google.golang.org/genproto/googleapis/api/annotations" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" @@ -566,40 +567,45 @@ func init() { func init() { proto.RegisterFile("grpcserver.proto", fileDescriptor_afa6debe97205904) } var fileDescriptor_afa6debe97205904 = []byte{ - // 525 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe4, 0x54, 0xdf, 0x6b, 0xd3, 0x50, - 0x14, 0x5e, 0xda, 0x24, 0x5d, 0x4e, 0xe7, 0xa8, 0x87, 0x59, 0xb3, 0x4c, 0xb4, 0xe4, 0xc5, 0x3a, - 0x24, 0x83, 0x0e, 0x65, 0x13, 0x5f, 0xac, 0xb7, 0x68, 0x71, 0x56, 0x0c, 0x1d, 0xa2, 0x6f, 0xd9, - 0x76, 0x56, 0x02, 0x6d, 0x13, 0x93, 0xdb, 0x41, 0xfe, 0x68, 0xc1, 0x57, 0xdf, 0x24, 0xf7, 0x26, - 0x69, 0xda, 0x66, 0xea, 0x9e, 0x7d, 0x4b, 0xee, 0xf7, 0xe3, 0x9c, 0x7b, 0xce, 0xc7, 0x85, 0xd6, - 0x24, 0x0a, 0x2f, 0x63, 0x8a, 0x6e, 0x28, 0x72, 0xc2, 0x28, 0xe0, 0x01, 0xc2, 0xf2, 0xc4, 0x7a, - 0x32, 0x09, 0x82, 0xc9, 0x94, 0x8e, 0x04, 0x72, 0xb1, 0xb8, 0x3e, 0xe2, 0xfe, 0x8c, 0x62, 0xee, - 0xcd, 0x42, 0x49, 0xb6, 0x1e, 0xaf, 0x13, 0xae, 0x16, 0x91, 0xc7, 0xfd, 0x60, 0x9e, 0xe1, 0x07, - 0xeb, 0x38, 0xcd, 0x42, 0x9e, 0x48, 0xd0, 0xfe, 0xa5, 0x80, 0x36, 0xb8, 0xa1, 0x39, 0xc7, 0x5d, - 0xa8, 0x0d, 0x99, 0xa9, 0x74, 0x94, 0x6e, 0xdd, 0xad, 0x0d, 0x19, 0xee, 0x81, 0x36, 0xf6, 0xf9, - 0x94, 0xcc, 0x5a, 0x47, 0xe9, 0x1a, 0xae, 0xfc, 0x41, 0x07, 0x54, 0xe6, 0x71, 0x32, 0xeb, 0x1d, - 0xa5, 0xdb, 0xec, 0x59, 0x8e, 0xf4, 0x76, 0x72, 0x6f, 0x67, 0x9c, 0x37, 0xe7, 0x0a, 0x1e, 0x1e, - 0x43, 0xe3, 0xcc, 0xe3, 0x34, 0xbf, 0x4c, 0x4c, 0x55, 0x48, 0xf6, 0x37, 0x24, 0x2c, 0x6b, 0xd7, - 0xcd, 0x99, 0x88, 0xa0, 0x8e, 0x02, 0x4e, 0xa6, 0x26, 0x2a, 0x8b, 0x6f, 0x6c, 0x83, 0x7e, 0x1e, - 0x53, 0x34, 0x64, 0xa6, 0x2e, 0x5a, 0xcc, 0xfe, 0xf0, 0x14, 0x60, 0x14, 0x70, 0xff, 0x3a, 0x49, - 0x2b, 0x9b, 0x8d, 0xbf, 0xd5, 0x28, 0x91, 0xed, 0x1f, 0x0a, 0x18, 0x6f, 0x23, 0xf2, 0x38, 0xb9, - 0xf4, 0xfd, 0x3f, 0xb8, 0xef, 0x41, 0x71, 0xdd, 0x38, 0x5c, 0x5f, 0xb7, 0xcd, 0xc0, 0x38, 0x0f, - 0xaf, 0xb2, 0x59, 0xac, 0x67, 0xe1, 0x69, 0x16, 0x12, 0x31, 0x9b, 0x66, 0xef, 0xbe, 0x53, 0x4a, - 0xac, 0x00, 0x5c, 0x89, 0xa7, 0x25, 0x18, 0x4d, 0xa9, 0xd2, 0xc5, 0x7e, 0x01, 0xdb, 0x67, 0x7e, - 0xcc, 0x5d, 0x8a, 0x43, 0x7c, 0x06, 0xba, 0x50, 0xc4, 0xa6, 0xd2, 0xa9, 0x57, 0x5b, 0x66, 0x04, - 0xfb, 0x11, 0xc0, 0x3b, 0xe2, 0xfd, 0x64, 0xc8, 0xaa, 0x4c, 0x4f, 0xa0, 0x59, 0xa0, 0x77, 0xf3, - 0x9d, 0xc2, 0x8e, 0x50, 0xb2, 0xec, 0xd2, 0xf9, 0xaa, 0x95, 0x7f, 0x5c, 0xf5, 0x73, 0xd0, 0x5c, - 0x6f, 0x3e, 0x91, 0x81, 0xd9, 0xed, 0xb5, 0xcb, 0x95, 0x3e, 0x2f, 0x28, 0x4a, 0x04, 0xea, 0x4a, - 0x92, 0xfd, 0x0a, 0xee, 0x95, 0xaa, 0xdd, 0xa9, 0xd3, 0xc3, 0x43, 0x80, 0xa5, 0x21, 0x36, 0xa0, - 0xce, 0xde, 0x7c, 0x6d, 0x6d, 0xe1, 0x36, 0xa8, 0x5f, 0x06, 0x83, 0x0f, 0x2d, 0x05, 0x0d, 0xd0, - 0x3e, 0x7e, 0x1a, 0x8d, 0xdf, 0xb7, 0x6a, 0xbd, 0x9f, 0x35, 0x50, 0x53, 0x23, 0x3c, 0x01, 0x5d, - 0x6e, 0x1b, 0x1f, 0x94, 0x9d, 0x8b, 0xc0, 0x5b, 0x55, 0xc7, 0x71, 0x68, 0x6f, 0xe1, 0x29, 0xe8, - 0x32, 0x0a, 0xab, 0xca, 0x22, 0x1e, 0x56, 0x7b, 0x63, 0x36, 0x83, 0xf4, 0x49, 0x91, 0x52, 0xb9, - 0xff, 0x55, 0x69, 0x91, 0x89, 0x3f, 0x48, 0x5f, 0x82, 0x9a, 0xa6, 0x03, 0x6f, 0x61, 0x58, 0x7b, - 0x65, 0xc3, 0x3c, 0x47, 0xf6, 0x16, 0xbe, 0x86, 0x46, 0x16, 0x00, 0x5c, 0x59, 0xc1, 0x32, 0x33, - 0xd6, 0xc3, 0xca, 0x73, 0xa1, 0xee, 0x83, 0x51, 0xac, 0x05, 0xcd, 0x0d, 0x5e, 0x96, 0x0d, 0x6b, - 0xff, 0x16, 0x24, 0xf5, 0xe8, 0xef, 0x7c, 0x2b, 0xbd, 0xd7, 0x17, 0xba, 0xe8, 0xfb, 0xf8, 0x77, - 0x00, 0x00, 0x00, 0xff, 0xff, 0x60, 0x63, 0x06, 0xc6, 0xd6, 0x05, 0x00, 0x00, + // 608 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe4, 0x95, 0x4f, 0x6f, 0xd3, 0x4c, + 0x10, 0xc6, 0x5f, 0x27, 0x8e, 0x53, 0x4f, 0xf3, 0x96, 0x74, 0x14, 0x52, 0xd7, 0xad, 0x4a, 0xb4, + 0x17, 0x42, 0x84, 0x6c, 0x29, 0x15, 0x12, 0xf4, 0x46, 0x71, 0x04, 0x81, 0x36, 0x14, 0x2b, 0x15, + 0x82, 0x13, 0x6e, 0xbb, 0x8d, 0x2c, 0x25, 0xb6, 0xb1, 0x37, 0x95, 0xa2, 0x2a, 0x17, 0xbe, 0x02, + 0x1f, 0x8d, 0xaf, 0xc0, 0x15, 0xee, 0xdc, 0x90, 0xd7, 0x6b, 0xc7, 0xf9, 0x27, 0xe8, 0x99, 0x5b, + 0x76, 0x9f, 0x99, 0xdf, 0xcc, 0xec, 0x3c, 0x8a, 0xa1, 0x3a, 0x08, 0x83, 0xcb, 0x88, 0x86, 0x37, + 0x34, 0x34, 0x82, 0xd0, 0x67, 0x3e, 0xc2, 0xec, 0x46, 0x7f, 0x30, 0xf0, 0xfd, 0xc1, 0x90, 0x9a, + 0x5c, 0xb9, 0x18, 0x5f, 0x9b, 0xcc, 0x1d, 0xd1, 0x88, 0x39, 0xa3, 0x20, 0x09, 0xd6, 0x0f, 0x16, + 0x03, 0xae, 0xc6, 0xa1, 0xc3, 0x5c, 0xdf, 0x13, 0xfa, 0xde, 0xa2, 0x4e, 0x47, 0x01, 0x9b, 0x08, + 0x71, 0x5f, 0x88, 0x4e, 0xe0, 0x9a, 0x8e, 0xe7, 0xf9, 0x8c, 0x67, 0x46, 0x89, 0x4a, 0x7e, 0x49, + 0x50, 0xea, 0xdc, 0x50, 0x8f, 0xe1, 0x16, 0x14, 0xba, 0x96, 0x26, 0x35, 0xa4, 0x66, 0xd1, 0x2e, + 0x74, 0x2d, 0xac, 0x41, 0xa9, 0xef, 0xb2, 0x21, 0xd5, 0x0a, 0x0d, 0xa9, 0xa9, 0xda, 0xc9, 0x01, + 0x0d, 0x90, 0x2d, 0x87, 0x51, 0xad, 0xd8, 0x90, 0x9a, 0x9b, 0x6d, 0xdd, 0x48, 0xe0, 0x46, 0x5a, + 0xd9, 0xe8, 0xa7, 0xad, 0xdb, 0x3c, 0x0e, 0x0f, 0xa1, 0x7c, 0xe2, 0x30, 0xea, 0x5d, 0x4e, 0x34, + 0x99, 0xa7, 0xec, 0x2e, 0xa5, 0x58, 0x62, 0x18, 0x3b, 0x8d, 0x44, 0x04, 0xb9, 0xe7, 0x33, 0xaa, + 0x95, 0x78, 0x65, 0xfe, 0x1b, 0xeb, 0xa0, 0x9c, 0x47, 0x34, 0xec, 0x5a, 0x9a, 0xc2, 0x5b, 0x14, + 0x27, 0x7c, 0x06, 0xd0, 0xf3, 0x99, 0x7b, 0x3d, 0x89, 0x2b, 0x6b, 0xe5, 0x3f, 0xd5, 0xc8, 0x05, + 0x93, 0x1f, 0x12, 0xa8, 0x2f, 0x42, 0xea, 0x30, 0x6a, 0xd3, 0xcf, 0xff, 0xc0, 0xbc, 0x7b, 0xd9, + 0xb8, 0x51, 0xb0, 0xb8, 0x6e, 0x62, 0x81, 0x7a, 0x1e, 0x5c, 0x89, 0xb7, 0x58, 0xf4, 0xc2, 0x43, + 0x61, 0x12, 0xfe, 0x36, 0x9b, 0xed, 0x6d, 0x23, 0xe7, 0x67, 0x2e, 0xd8, 0x89, 0x1e, 0x97, 0xb0, + 0xe8, 0x90, 0xae, 0xa4, 0x90, 0x27, 0xb0, 0x71, 0xe2, 0x46, 0xcc, 0xa6, 0x51, 0x80, 0x8f, 0x40, + 0xe1, 0x19, 0x91, 0x26, 0x35, 0x8a, 0xab, 0x91, 0x22, 0x80, 0xec, 0x03, 0xbc, 0xa4, 0xec, 0x78, + 0xd2, 0xb5, 0x56, 0x41, 0x9f, 0xc2, 0x66, 0xa6, 0xde, 0x8d, 0x3b, 0x84, 0x0a, 0xcf, 0xb4, 0xc4, + 0xd0, 0xe9, 0xaa, 0xa5, 0xbf, 0x5c, 0xf5, 0x63, 0x28, 0xd9, 0x8e, 0x37, 0x48, 0x0c, 0xb3, 0xd5, + 0xae, 0xe7, 0x2b, 0xbd, 0x1b, 0xd3, 0x70, 0xc2, 0x55, 0x3b, 0x09, 0x22, 0x47, 0xf0, 0x7f, 0xae, + 0xda, 0x9d, 0x3a, 0x6d, 0xb5, 0x00, 0x66, 0x40, 0x2c, 0x43, 0xd1, 0x7a, 0xfe, 0xa1, 0xfa, 0x1f, + 0x6e, 0x80, 0xfc, 0xbe, 0xd3, 0x79, 0x53, 0x95, 0x50, 0x85, 0xd2, 0xe9, 0xdb, 0x5e, 0xff, 0x55, + 0xb5, 0xd0, 0xfe, 0x59, 0x04, 0x39, 0x06, 0xe1, 0x6b, 0x50, 0x92, 0x6d, 0xe3, 0xfd, 0x3c, 0x39, + 0x33, 0xbc, 0xbe, 0xea, 0x3a, 0x0a, 0x08, 0x7e, 0xf9, 0xf6, 0xfd, 0x6b, 0xa1, 0x42, 0xca, 0x26, + 0xe5, 0xd5, 0x8f, 0xa4, 0x16, 0x9e, 0x81, 0x92, 0x98, 0x63, 0x9e, 0x95, 0x19, 0x46, 0xaf, 0x2f, + 0xbd, 0x56, 0x27, 0xfe, 0x0b, 0x22, 0x3b, 0x1c, 0xb6, 0xad, 0x57, 0x04, 0xcc, 0xbc, 0xed, 0x5a, + 0xd3, 0x98, 0x78, 0x0a, 0x4a, 0x62, 0x94, 0x79, 0x62, 0x66, 0x9e, 0xb5, 0xc4, 0x1a, 0x27, 0x6e, + 0xb5, 0xe6, 0x88, 0xd8, 0x01, 0x39, 0xb6, 0x16, 0xae, 0xc9, 0xd2, 0x6b, 0xf9, 0x22, 0xa9, 0x09, + 0xc9, 0x3d, 0xce, 0x52, 0x31, 0x1d, 0x15, 0xcf, 0xa0, 0x2c, 0xcc, 0x84, 0x73, 0xeb, 0x9c, 0xf9, + 0x4f, 0xdf, 0x59, 0x79, 0x1f, 0x05, 0x69, 0x63, 0x38, 0xdf, 0xd8, 0x27, 0x50, 0xb3, 0xb5, 0xa3, + 0xb6, 0x94, 0x2b, 0xbc, 0xa7, 0xef, 0xae, 0x51, 0xa2, 0x80, 0x1c, 0x70, 0xae, 0x46, 0xea, 0x19, + 0x97, 0xdb, 0x60, 0x6a, 0xde, 0xc6, 0x21, 0xd3, 0xe3, 0xca, 0xc7, 0xdc, 0xb7, 0xe4, 0x42, 0xe1, + 0x83, 0x1f, 0xfe, 0x0e, 0x00, 0x00, 0xff, 0xff, 0xc6, 0xe4, 0xd7, 0xf2, 0x72, 0x06, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. diff --git a/hw12_13_14_15_calendar/internal/grpcserver/grpcserver.pb.gw.go b/hw12_13_14_15_calendar/internal/grpcserver/grpcserver.pb.gw.go new file mode 100644 index 0000000..54ea6e2 --- /dev/null +++ b/hw12_13_14_15_calendar/internal/grpcserver/grpcserver.pb.gw.go @@ -0,0 +1,375 @@ +// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. +// source: grpcserver.proto + +/* +Package grpcserver is a reverse proxy. + +It translates gRPC into RESTful JSON APIs. +*/ +package grpcserver + +import ( + "io" + "net/http" + + "github.com/golang/protobuf/proto" + "github.com/golang/protobuf/ptypes/empty" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/grpc-ecosystem/grpc-gateway/utilities" + "golang.org/x/net/context" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/status" +) + +var _ codes.Code +var _ io.Reader +var _ status.Status +var _ = runtime.String +var _ = utilities.NewDoubleArray + +func request_Grpc_Create_0(ctx context.Context, marshaler runtime.Marshaler, client GrpcClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq CreateReq + var metadata runtime.ServerMetadata + + newReader, berr := utilities.IOReaderFactory(req.Body) + if berr != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) + } + if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := client.Create(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func request_Grpc_Update_0(ctx context.Context, marshaler runtime.Marshaler, client GrpcClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq UpdateReq + var metadata runtime.ServerMetadata + + newReader, berr := utilities.IOReaderFactory(req.Body) + if berr != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) + } + if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["ID"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "ID") + } + + protoReq.ID, err = runtime.Int64(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "ID", err) + } + + msg, err := client.Update(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func request_Grpc_Delete_0(ctx context.Context, marshaler runtime.Marshaler, client GrpcClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq DeleteReq + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["ID"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "ID") + } + + protoReq.ID, err = runtime.Int64(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "ID", err) + } + + msg, err := client.Delete(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func request_Grpc_List_0(ctx context.Context, marshaler runtime.Marshaler, client GrpcClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq empty.Empty + var metadata runtime.ServerMetadata + + msg, err := client.List(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func request_Grpc_GetByID_0(ctx context.Context, marshaler runtime.Marshaler, client GrpcClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq GetByIDReq + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["ID"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "ID") + } + + protoReq.ID, err = runtime.Int64(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "ID", err) + } + + msg, err := client.GetByID(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func request_Grpc_GetByDate_0(ctx context.Context, marshaler runtime.Marshaler, client GrpcClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq GetByDateReq + var metadata runtime.ServerMetadata + + var ( + val string + e int32 + ok bool + err error + _ = err + ) + + val, ok = pathParams["Range"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "Range") + } + + e, err = runtime.Enum(val, QueryRange_value) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "Range", err) + } + + protoReq.Range = QueryRange(e) + + val, ok = pathParams["Date"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "Date") + } + + protoReq.Date, err = runtime.Timestamp(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "Date", err) + } + + msg, err := client.GetByDate(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +// RegisterGrpcHandlerFromEndpoint is same as RegisterGrpcHandler but +// automatically dials to "endpoint" and closes the connection when "ctx" gets done. +func RegisterGrpcHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { + conn, err := grpc.Dial(endpoint, opts...) + if err != nil { + return err + } + defer func() { + if err != nil { + if cerr := conn.Close(); cerr != nil { + grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + } + return + } + go func() { + <-ctx.Done() + if cerr := conn.Close(); cerr != nil { + grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + } + }() + }() + + return RegisterGrpcHandler(ctx, mux, conn) +} + +// RegisterGrpcHandler registers the http handlers for service Grpc to "mux". +// The handlers forward requests to the grpc endpoint over "conn". +func RegisterGrpcHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { + return RegisterGrpcHandlerClient(ctx, mux, NewGrpcClient(conn)) +} + +// RegisterGrpcHandlerClient registers the http handlers for service Grpc +// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "GrpcClient". +// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "GrpcClient" +// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in +// "GrpcClient" to call the correct interceptors. +func RegisterGrpcHandlerClient(ctx context.Context, mux *runtime.ServeMux, client GrpcClient) error { + + mux.Handle("POST", pattern_Grpc_Create_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) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Grpc_Create_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Grpc_Create_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("PUT", pattern_Grpc_Update_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) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Grpc_Update_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Grpc_Update_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("DELETE", pattern_Grpc_Delete_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) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Grpc_Delete_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Grpc_Delete_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Grpc_List_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) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Grpc_List_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Grpc_List_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Grpc_GetByID_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) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Grpc_GetByID_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Grpc_GetByID_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("POST", pattern_Grpc_GetByDate_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) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Grpc_GetByDate_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Grpc_GetByDate_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + return nil +} + +var ( + pattern_Grpc_Create_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0}, []string{"events"}, "")) + + pattern_Grpc_Update_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 1, 0, 4, 1, 5, 1}, []string{"events", "ID"}, "")) + + pattern_Grpc_Delete_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 1, 0, 4, 1, 5, 1}, []string{"events", "ID"}, "")) + + pattern_Grpc_List_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0}, []string{"events"}, "")) + + pattern_Grpc_GetByID_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 1, 0, 4, 1, 5, 1}, []string{"events", "ID"}, "")) + + pattern_Grpc_GetByDate_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 1, 0, 4, 1, 5, 1, 1, 0, 4, 1, 5, 2}, []string{"events", "Range", "Date"}, "")) +) + +var ( + forward_Grpc_Create_0 = runtime.ForwardResponseMessage + + forward_Grpc_Update_0 = runtime.ForwardResponseMessage + + forward_Grpc_Delete_0 = runtime.ForwardResponseMessage + + forward_Grpc_List_0 = runtime.ForwardResponseMessage + + forward_Grpc_GetByID_0 = runtime.ForwardResponseMessage + + forward_Grpc_GetByDate_0 = runtime.ForwardResponseMessage +) diff --git a/hw12_13_14_15_calendar/internal/grpcserver/handlers_test.go b/hw12_13_14_15_calendar/internal/grpcserver/handlers_test.go index dea031a..c92c391 100644 --- a/hw12_13_14_15_calendar/internal/grpcserver/handlers_test.go +++ b/hw12_13_14_15_calendar/internal/grpcserver/handlers_test.go @@ -13,7 +13,7 @@ import ( "time" ) -var conf = config.Config{Server: config.Server{Address: "localhost", Port: "50511"}, GRPC: config.Server{Address: "localhost", Port: "50512"}, Logger: config.Logger{File: "calendar.log", Level: "INFO", MuteStdout: false}, Storage: config.Storage{InMemory: true, SQLHost: "", SQLPort: "", SQLDbase: "", SQLUser: "", SQLPass: ""}} +var conf = config.Config{HTTP: config.Server{Address: "localhost", Port: "50511"}, GRPC: config.Server{Address: "localhost", Port: "50512"}, Logger: config.Logger{File: "calendar.log", Level: "INFO", MuteStdout: false}, Storage: config.Storage{InMemory: true, SQLHost: "", SQLPort: "", SQLDbase: "", SQLUser: "", SQLPass: ""}} var storeConf = store.Config(conf.Storage) @@ -41,13 +41,16 @@ func (suite *TestSuite) SetupTest() { func (s *TestSuite) TestCreateEvent() { controlEvent := testEvt1 s.createEvent(&controlEvent) + createdEvent := s.getEventByDate(controlEvent.Date) + s.Require().GreaterOrEqual(len(createdEvent), 1) s.Equal(&controlEvent, createdEvent[0]) } func (s *TestSuite) TestUpdateEvent() { oldEvent := testEvt1 s.createEvent(&oldEvent) + newEvent := testEvt2 s.updateEvent(oldEvent, newEvent) updatedEvent := s.getEventByID(oldEvent.ID) @@ -58,7 +61,9 @@ func (s *TestSuite) TestDeleteEvent() { testEvent := testEvt1 s.createEvent(&testEvent) createdEvent := s.getEventByDate(testEvent.Date) + s.Require().GreaterOrEqual(len(createdEvent), 1) s.Equal(&testEvent, createdEvent[0]) + s.deleteEvent(createdEvent[0].ID) controlEvent := s.getEventByDate(testEvent.Date) s.Equal(0, len(controlEvent)) @@ -67,14 +72,16 @@ func (s *TestSuite) TestDeleteEvent() { func (s *TestSuite) TestListEvent() { testEvent := testEvt1 s.createEvent(&testEvent) + eventList := s.listEvents() - s.Equal(1, len(eventList)) + s.GreaterOrEqual(len(eventList),1) s.Equal(testEvt1.Title, eventList[0].Title) } func (s *TestSuite) TestGetEventByID() { testEvent := testEvt1 s.createEvent(&testEvent) + eventList := s.getEventByID(testEvent.ID) s.Equal(testEvent.Title, eventList.Title) } @@ -82,8 +89,9 @@ func (s *TestSuite) TestGetEventByID() { func (s *TestSuite) TestGetEventByDate() { testEvent := testEvt1 s.createEvent(&testEvent) + eventList := s.getEventByDate(testEvent.Date) - s.Equal(1, len(eventList)) + s.GreaterOrEqual(len(eventList),1) s.Equal(testEvent.Title, eventList[0].Title) } diff --git a/hw12_13_14_15_calendar/internal/server/http/http.go b/hw12_13_14_15_calendar/internal/server/http/http.go deleted file mode 100644 index 3ae6cd2..0000000 --- a/hw12_13_14_15_calendar/internal/server/http/http.go +++ /dev/null @@ -1,33 +0,0 @@ -package http - -import ( - "net" - "net/http" - - "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/app" -) - -type Server struct { - server *http.Server - app app.App -} - -func NewServer(app *app.App, address string, port string) *Server { - return &Server{server: &http.Server{Addr: net.JoinHostPort(address, port), Handler: app.LoggingMiddleware(app.Handler)}, app: *app} -} - -func (s *Server) Start() error { - if err := s.server.ListenAndServe(); err != nil { - return err - } - s.app.Logger.Infof("Server starting") - return nil -} - -func (s *Server) Stop() error { - if err := s.server.Close(); err != nil { - return err - } - s.app.Logger.Infof("Server stoped") - return nil -}