hw12_13_14_15_calendar
Andrey Ivanov 2021-03-19 11:33:13 -04:00 committed by Andrey Ivanov
parent a0b572be3a
commit ddb1205fd3
10 changed files with 321 additions and 450 deletions

View File

@ -13,7 +13,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 ./api/public --go_out=plugins=grpc:./pkg/api/public --grpc-gateway_out=logtostderr=true:./pkg/api/public ./api/public/public.proto
protoc -I ./api/public --go_out=plugins=grpc:./pkg/api/public ./api/public/public.proto
protoc -I ./api/private --go_out=plugins=grpc:./internal/api/private ./api/private/private.proto
up: sup-up calendar-up sender-up sheduler-up

View File

@ -3,9 +3,8 @@ package main
import (
"context"
"flag"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/api/private"
"google.golang.org/grpc"
"github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/pkg/api/rest"
oslog "log"
"net"
"net/http"
@ -13,11 +12,11 @@ import (
"os/signal"
"syscall"
_ "github.com/go-sql-driver/mysql"
"github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/calendar"
"github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/pkg/api/public"
"github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/pkg/config"
"github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/pkg/logger"
"github.com/gorilla/mux"
store "github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/pkg/storage"
)
@ -59,25 +58,20 @@ 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()
ctx, cancel := context.WithCancel(context.Background())
if err = public.RegisterGrpcHandler(ctx, grpcGwRouter, grpcDiler); err != nil {
log.Errorf("can't register handlers for grpc-gateway: " + err.Error())
os.Exit(1)
}
_, cancel := context.WithCancel(context.Background())
m := mux.NewRouter()
m.HandleFunc("/events", rest.FromRESTCreate(calendar)).Methods("POST")
m.HandleFunc("/events/{ID}", rest.FromRESTUpdate(calendar)).Methods("PUT")
m.HandleFunc("/events/{ID}", rest.FromRESTDelete(calendar)).Methods("DELETE")
m.HandleFunc("/events", rest.FromRESTList(calendar)).Methods("GET")
m.HandleFunc("/events/{ID}", rest.FromRESTGetByID(calendar)).Methods("GET")
m.HandleFunc("/events/{Range}/{Date}", rest.FromRESTGetByDate(calendar)).Methods("GET")
mux := http.NewServeMux()
mux.Handle("/", grpcGwRouter)
go func() {
log.Infof("webAPI server starting")
if err := http.ListenAndServe(net.JoinHostPort(conf.HTTP.Address, conf.HTTP.Port), mux); err != nil {
if err := http.ListenAndServe(net.JoinHostPort(conf.HTTP.Address, conf.HTTP.Port), m); err != nil {
log.Errorf("failed to start webAPI server: " + err.Error())
os.Exit(1)
}

View File

@ -7,6 +7,7 @@ require (
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
github.com/gorilla/mux v1.8.0
github.com/grpc-ecosystem/grpc-gateway v1.15.0
github.com/kr/text v0.2.0 // indirect
github.com/lib/pq v1.10.0

View File

@ -38,19 +38,16 @@ github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMyw
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/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
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/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/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 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
@ -58,7 +55,6 @@ github.com/lib/pq v1.10.0 h1:Zx5DJFEYQXio93kgXnQ09fXNiUKsqv4OUEu2UtGcB1E=
github.com/lib/pq v1.10.0/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
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 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
@ -66,20 +62,16 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
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/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 h1:kuuDrUJFZL1QYL9hUNuCxNObNzB0bV/ZG5jV3RWAQgo=
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=
@ -97,10 +89,8 @@ 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-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/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
@ -108,7 +98,6 @@ golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvx
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/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.3.0 h1:RM4zey1++hCTbCVQfnWeKs9/IEsaBLA8vTkd0WVtmH4=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
@ -118,7 +107,6 @@ golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73r
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-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-20200625001655-4c5254603344 h1:vGXIOMxbNfDTk/aXCmfdLgkrSV+Z2tcbze+pEc3v5W4=
@ -128,20 +116,16 @@ golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4Iltr
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-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
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-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-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=
golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
@ -152,12 +136,10 @@ golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
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-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=
@ -167,7 +149,6 @@ google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7
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-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=
@ -183,19 +164,15 @@ google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQ
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 h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU=
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/natefinch/lumberjack.v2 v2.0.0 h1:1Lc07Kr7qY4U2YPouBjpCLxpiyxIVoxqXgkXLknAOE8=
gopkg.in/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k=

View File

@ -733,9 +733,7 @@ func _Grpc_Create_Handler(srv interface{}, ctx context.Context, dec func(interfa
return nil, err
}
if interceptor == nil {
sss := srv.(GrpcServer)
rrrrr, err := sss.Create(ctx, in)
return rrrrr, err
return srv.(GrpcServer).Create(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,

View File

@ -1,375 +0,0 @@
// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT.
// source: public.proto
/*
Package public is a reverse proxy.
It translates gRPC into RESTful JSON APIs.
*/
package public
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
)

View File

@ -0,0 +1,83 @@
package rest
import (
"github.com/golang/protobuf/ptypes"
"github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/pkg/api/public"
"github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/pkg/storage/event"
)
func createReq2Event(e public.CreateReq) (res event.Event, err error) {
res = event.Event{
Title: e.Title,
Note: e.Note,
UserID: e.UserID,
}
res.Date, err = ptypes.Timestamp(e.Date)
if err != nil {
return event.Event{}, err
}
res.Latency, err = ptypes.Duration(e.Latency)
if err != nil {
return event.Event{}, err
}
res.NotifyTime, err = ptypes.Duration(e.NotifyTime)
if err != nil {
return event.Event{}, err
}
return res, nil
}
func pubEvent2Event(e public.Event) (res event.Event, err error) {
res = event.Event{
Title: e.Title,
Note: e.Note,
UserID: e.UserID,
}
res.Date, err = ptypes.Timestamp(e.Date)
if err != nil {
return event.Event{}, err
}
res.Latency, err = ptypes.Duration(e.Latency)
if err != nil {
return event.Event{}, err
}
res.NotifyTime, err = ptypes.Duration(e.NotifyTime)
if err != nil {
return event.Event{}, err
}
return res, nil
}
func event2pubEvent(e event.Event) (res public.Event, err error) {
res = public.Event{
Title: e.Title,
Latency: ptypes.DurationProto(e.Latency),
Note: e.Note,
UserID: e.UserID,
NotifyTime: ptypes.DurationProto(e.NotifyTime),
}
res.Date, err = ptypes.TimestampProto(e.Date)
if err != nil {
return public.Event{}, err
}
return res, nil
}
func events2pubEvents(e map[event.ID]event.Event) (res []public.Event, err error) {
for id,ev := range e {
r := public.Event{
ID: int64(id),
Title: ev.Title,
Latency: ptypes.DurationProto(ev.Latency),
Note: ev.Note,
UserID: ev.UserID,
NotifyTime: ptypes.DurationProto(ev.NotifyTime),
}
r.Date, err = ptypes.TimestampProto(ev.Date)
if err != nil {
return []public.Event{}, err
}
res = append(res,r)
}
return res, nil
}

View File

@ -0,0 +1,146 @@
package rest
import (
"encoding/json"
"github.com/gorilla/mux"
"github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/internal/calendar"
"github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/pkg/api/public"
"github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/pkg/logger"
"github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/pkg/storage/event"
"io/ioutil"
"log"
"net/http"
"strconv"
"time"
)
func FromRESTCreate(calendar *calendar.App) http.HandlerFunc {
return func(r http.ResponseWriter, req *http.Request) {
bodyReq := public.CreateReq{}
bodyIn, err := ioutil.ReadAll(req.Body)
defer req.Body.Close()
if err != nil {
err503("can't body of the HTTP API request", err, calendar.Logger, r)
}
err = json.Unmarshal(bodyIn, &bodyReq)
if err != nil {
err503("can't unmarshal data from HTTP API request", err, calendar.Logger, r)
}
evt, err := createReq2Event(bodyReq)
if err != nil {
err503("can't convert types", err, calendar.Logger, r)
}
id, err := calendar.Storage.Create(evt)
if err != nil {
err503("can't create event through HTTP API", err, calendar.Logger, r)
}
bodyOut,err := json.Marshal(&public.CreateRsp{ID: int64(id)})
r.WriteHeader(201)
r.Write(bodyOut)
}
}
func FromRESTUpdate(calendar *calendar.App) http.HandlerFunc {
return func(r http.ResponseWriter, req *http.Request) {
paramID, err := strconv.Atoi(mux.Vars(req)["ID"])
if err != nil {
err503("can't get request parameter", err, calendar.Logger, r)
}
bodyReq := public.Event{}
bodyIn, err := ioutil.ReadAll(req.Body)
defer req.Body.Close()
if err != nil {
err503("can't body of the HTTP API request", err, calendar.Logger, r)
}
err = json.Unmarshal(bodyIn, &bodyReq)
if err != nil {
err503("can't unmarshal data from HTTP API request", err, calendar.Logger, r)
}
evt, err := pubEvent2Event(bodyReq)
if err != nil {
err503("can't convert types", err, calendar.Logger, r)
}
err = calendar.Storage.Update(event.ID(paramID), evt)
if err != nil {
err503("can't update event through HTTP API", err, calendar.Logger, r)
}
r.WriteHeader(200)
}
}
func FromRESTDelete(calendar *calendar.App) http.HandlerFunc {
return func(r http.ResponseWriter, req *http.Request) {
paramID, err := strconv.Atoi(mux.Vars(req)["ID"])
if err != nil {
err503("can't get request parameter", err, calendar.Logger, r)
}
err = calendar.Storage.Delete(event.ID(paramID))
if err != nil {
err503("can't create event from HTTP API", err, calendar.Logger, r)
}
r.WriteHeader(200)
}
}
func FromRESTList(calendar *calendar.App) http.HandlerFunc {
return func(r http.ResponseWriter, req *http.Request) {
evs, err := calendar.Storage.List()
if err != nil {
err503("can't list events through HTTP API", err, calendar.Logger, r)
}
events, err := events2pubEvents(evs)
if err != nil {
err503("can't convert types", err, calendar.Logger, r)
}
bodyOut,err := json.Marshal(&events)
r.WriteHeader(200)
r.Write(bodyOut)
}
}
func FromRESTGetByID(calendar *calendar.App) http.HandlerFunc {
return func(r http.ResponseWriter, req *http.Request) {
paramID, err := strconv.Atoi(mux.Vars(req)["ID"])
if err != nil {
err503("can't get request parameter", err, calendar.Logger, r)
}
ev, _ := calendar.Storage.GetByID(event.ID(paramID))
event, err := event2pubEvent(ev)
if err != nil {
err503("can't convert types", err, calendar.Logger, r)
}
bodyOut,err := json.Marshal(&event)
r.WriteHeader(200)
r.Write(bodyOut)
log.Println(paramID)
r.WriteHeader(555)
}
}
func FromRESTGetByDate(calendar *calendar.App) http.HandlerFunc {
return func(r http.ResponseWriter, req *http.Request) {
paramRange := mux.Vars(req)["Range"]
paramDate, err := time.Parse("2006-01-02 15:04:05", mux.Vars(req)["Date"])
if err != nil {
err503("can't parse date from request parameter", err, calendar.Logger, r)
}
evs, err := calendar.Storage.GetByDate(paramDate, paramRange)
if err != nil {
err503("can't list events through HTTP API", err, calendar.Logger, r)
}
events, err := events2pubEvents(evs)
if err != nil {
err503("can't convert types", err, calendar.Logger, r)
}
bodyOut,err := json.Marshal(&events)
r.WriteHeader(200)
r.Write(bodyOut)
}
}
func err503(s string, err error, l logger.Interface, r http.ResponseWriter) {
l.Errorf(s,": ", err.Error())
r.WriteHeader(503)
}

View File

@ -50,7 +50,7 @@ func (h HTTPAPI) Update(req *public.UpdateReq) error {
if err != nil {
return err
}
if res.StatusCode!=201 {
if res.StatusCode!=200 {
return fmt.Errorf("unexpected status code %d",res.StatusCode)
}
return nil
@ -65,7 +65,7 @@ func (h HTTPAPI) Delete(req *public.DeleteReq) error {
if err != nil {
return err
}
if res.StatusCode!=201 {
if res.StatusCode!=200 {
return fmt.Errorf("unexpected status code %d",res.StatusCode)
}
return nil
@ -80,7 +80,7 @@ func (h HTTPAPI) GetByID(req *public.GetByIDReq) ( *public.GetByIDResp, error) {
if err != nil {
return &public.GetByIDResp{}, err
}
if res.StatusCode!=201 {
if res.StatusCode!=200 {
return &public.GetByIDResp{}, fmt.Errorf("unexpected status code %d",res.StatusCode)
}
var getByIDResp public.GetByIDResp
@ -116,7 +116,7 @@ func (h HTTPAPI) GetByDate(req *public.GetByDateReq) ( *public.GetByDateResp, er
if err != nil {
return &public.GetByDateResp{}, err
}
if res.StatusCode!=201 {
if res.StatusCode!=200 {
return &public.GetByDateResp{}, fmt.Errorf("unexpected status code %d",res.StatusCode)
}
var getByDateResp public.GetByDateResp

View File

@ -6,8 +6,10 @@ import (
"github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/pkg/api/public"
"github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/test/client"
"github.com/tiburon-777/HW_OTUS/hw12_13_14_15_calendar/test/misc"
"log"
"sync"
"testing"
"time"
)
func TestPublicAPIEndpoints(t *testing.T) {
@ -19,12 +21,17 @@ func TestPublicAPIEndpoints(t *testing.T) {
wg.Add(len(cli)*5)
for _,c := range cli {
t.Run("test "+c.GetName()+" for Create and GetById", func(t *testing.T) {
defer wg.Done()
t.Run("test "+c.GetName()+" for Create, GetById and Delete", func(t *testing.T) {
var ids []int64
defer func() {
wg.Done()
clean(c,&ids)
}()
resp1, err := c.Create(&misc.TestEvent01)
require.NoError(t, err)
require.Greater(t, resp1.ID, int64(0))
ids=append(ids,resp1.ID)
resp2,err := c.GetByID(&public.GetByIDReq{ID:resp1.ID})
require.NoError(t, err)
@ -34,12 +41,17 @@ func TestPublicAPIEndpoints(t *testing.T) {
require.Equal(t, misc.TestEvent01.Note, resp2.Events[0].Note)
})
t.Run("test "+c.GetName()+" for Create, Update and GetById", func(t *testing.T) {
defer wg.Done()
t.Run("test "+c.GetName()+" for Create, Update, GetById and Delete", func(t *testing.T) {
var ids []int64
defer func() {
wg.Done()
clean(c,&ids)
}()
resp1, err := c.Create(&misc.TestEvent01)
require.NoError(t, err)
require.Greater(t, resp1.ID, int64(0))
ids=append(ids,resp1.ID)
err = c.Update(&public.UpdateReq{ID:resp1.ID, Event: &public.Event{ ID: resp1.ID, Title: misc.TestEvent02.Title, Date: misc.TestEvent02.Date, Latency: misc.TestEvent02.Latency, Note: misc.TestEvent02.Note, UserID: misc.TestEvent02.UserID, NotifyTime: misc.TestEvent02.NotifyTime }})
require.NoError(t, err)
@ -67,16 +79,23 @@ func TestPublicAPIEndpoints(t *testing.T) {
require.Nil(t, resp2)
})
t.Run("test "+c.GetName()+" for Create and List", func(t *testing.T) {
defer wg.Done()
t.Run("test "+c.GetName()+" for Create, List and Delete", func(t *testing.T) {
var ids []int64
defer func() {
wg.Done()
clean(c,&ids)
}()
resp1, err := c.Create(&misc.TestEvent01)
require.NoError(t, err)
require.Greater(t, resp1.ID, int64(0))
ids=append(ids,resp1.ID)
resp2, err := c.Create(&misc.TestEvent02)
require.NoError(t, err)
require.Greater(t, resp2.ID, int64(0))
ids=append(ids,resp2.ID)
resp3, err := c.List()
require.NoError(t, err)
@ -92,29 +111,57 @@ func TestPublicAPIEndpoints(t *testing.T) {
}
require.True(t, e1)
require.True(t, e2)
err = c.Delete(&public.DeleteReq{ ID: resp1.ID })
require.NoError(t, err)
err = c.Delete(&public.DeleteReq{ ID: resp2.ID })
require.NoError(t, err)
})
t.Run("test "+c.GetName()+" for Create and GetByDate", func(t *testing.T) {
defer wg.Done()
t.Run("test "+c.GetName()+" for Create, GetByDate and Delete", func(t *testing.T) {
var ids []int64
defer func() {
wg.Done()
clean(c,&ids)
}()
resp1, err := c.Create(&misc.TestEvent01)
startDate, err := time.Parse("2006-01-02T15:04:00","3100-01-01T12:00:00")
require.NoError(t, err)
require.Greater(t, resp1.ID, int64(0))
resp2, err := c.Create(&misc.TestEvent02)
require.NoError(t, err)
require.Greater(t, resp2.ID, int64(0))
resp3,err := c.GetByDate(&public.GetByDateReq{Date: misc.TestEvent01.Date, Range: public.QueryRange_DAY})
require.NoError(t, err)
require.GreaterOrEqual(t, len(resp3.Events), 1)
var e1 bool
for _, v := range resp3.Events {
if v.ID == resp1.ID {
e1 = true
}
for i:=time.Hour;i<(60*24*time.Hour);i=i+48*time.Hour{
resp1, err := c.Create(&public.CreateReq{
Title: "Test event 02",
Date: misc.Time2pbtimestamp(startDate.Add(i)),
Latency: misc.Dur2pbduration(2 * 24 * time.Hour),
Note: "Note of test event 02",
NotifyTime: misc.Dur2pbduration(5 * time.Minute),
UserID: 2222,
})
require.NoError(t, err)
require.Greater(t, resp1.ID, int64(0))
ids=append(ids,resp1.ID)
}
require.True(t, e1)
resp2,err := c.GetByDate(&public.GetByDateReq{Date: misc.Time2pbtimestamp(startDate), Range: public.QueryRange_DAY})
require.NoError(t, err)
require.Equal(t, 1, len(resp2.Events) )
resp3,err := c.GetByDate(&public.GetByDateReq{Date: misc.Time2pbtimestamp(startDate), Range: public.QueryRange_WEEK})
require.NoError(t, err)
require.Equal(t, 4, len(resp3.Events) )
resp4,err := c.GetByDate(&public.GetByDateReq{Date: misc.Time2pbtimestamp(startDate), Range: public.QueryRange_MONTH})
require.NoError(t, err)
require.Equal(t, 16, len(resp4.Events) )
})
}
}
func clean(c client.Interface, ids *[]int64) {
for _,m := range *ids {
err := c.Delete(&public.DeleteReq{ID:m})
if err != nil {
log.Println("error when try to clean DB: ", err.Error())
}
}
}