Skip to content

Commit

Permalink
增加grpc服务
Browse files Browse the repository at this point in the history
  • Loading branch information
icowan committed Apr 27, 2020
1 parent 50b57e3 commit 0073b36
Show file tree
Hide file tree
Showing 9 changed files with 537 additions and 12 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,4 @@ push:
docker push $(HUB_ADDR)/$(NAMESPACE)/$(APPNAME):$(TAG)

run:
GO111MODULE=on $(GORUN) ./cmd/main.go -http-addr :8080
GO111MODULE=on $(GORUN) ./cmd/main.go -http-addr :8080 -grpc-addr :8082
49 changes: 49 additions & 0 deletions cmd/client/grpc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/**
* @Time : 27/04/2020 12:00 PM
* @Author : solacowa@gmail.com
* @File : grpc
* @Software: GoLand
*/

package main

import (
"context"
"fmt"
"github.com/icowan/shorter/pkg/grpc/pb"
"google.golang.org/grpc"
"log"
"time"
)

func main() {
conn, err := grpc.Dial("127.0.0.1:8082", grpc.WithInsecure(), grpc.WithBlock())
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer func() {
_ = conn.Close()
}()

svc := pb.NewShorterClient(conn)

ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()

r, err := svc.Post(ctx, &pb.PostRequest{
Domain: "https://www.baidu.com",
})
if err != nil {
log.Fatalf("could not put: %v", err)
}

fmt.Println("Code", r.Data.Code, "ShortUri", r.Data.ShortUri)

r, err = svc.Get(ctx, &pb.GetRequest{
Code: r.Data.Code,
})
if err != nil {
log.Fatalf("could not get: %v", err)
}
log.Printf("data: %s", r.GetData())
}
39 changes: 31 additions & 8 deletions cmd/service/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,30 +10,35 @@ package service
import (
"flag"
"fmt"
kitendpoint "github.com/go-kit/kit/endpoint"
"github.com/go-kit/kit/log/level"
"github.com/icowan/shorter/pkg/endpoint"
svchttp "github.com/icowan/shorter/pkg/http"
"github.com/icowan/shorter/pkg/logging"
"github.com/icowan/shorter/pkg/repository/mongodb"
"github.com/icowan/shorter/pkg/repository/redis"
"github.com/icowan/shorter/pkg/service"
"github.com/icowan/shorter/pkg/grpc"
"github.com/icowan/shorter/pkg/grpc/pb"
"net"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"

kitendpoint "github.com/go-kit/kit/endpoint"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/oklog/oklog/pkg/group"
googlegrpc "google.golang.org/grpc"

"github.com/icowan/shorter/pkg/endpoint"
svchttp "github.com/icowan/shorter/pkg/http"
"github.com/icowan/shorter/pkg/logging"
"github.com/icowan/shorter/pkg/repository/mongodb"
"github.com/icowan/shorter/pkg/repository/redis"
"github.com/icowan/shorter/pkg/service"
)

var logger log.Logger

var (
fs = flag.NewFlagSet("hello", flag.ExitOnError)
httpAddr = fs.String("http-addr", ":8080", "HTTP listen address")
grpcAddr = fs.String("grpc-addr", ":8082", "Grpc listen address")
dbDrive = fs.String("db-drive", "mongo", "db drive type, default: mongo")
mongoAddr = fs.String("mongo-addr", "mongodb://root:admin@localhost:27017/?authSource=admin", "mongodb uri, default: mongodb://localhost:27017")
redisDrive = fs.String("redis-drive", "single", "redis drive: single or cluster")
Expand Down Expand Up @@ -117,8 +122,26 @@ func initHttpHandler(endpoints endpoint.Endpoints, g *group.Group) {
}, func(error) {
_ = httpListener.Close()
})
}

func initGrpcHandler(endpoints endpoint.Endpoints, g *group.Group) {
options := defaultGrpcOptions(logger)

grpcListener, err := net.Listen("tcp", *grpcAddr)
if err != nil {
_ = logger.Log("transport", "gRPC", "during", "Listen", "err", err)
}

g.Add(func() error {
_ = level.Debug(logger).Log("transport", "GRPC", "addr", *grpcAddr)
baseServer := googlegrpc.NewServer()
pb.RegisterShorterServer(baseServer, grpc.MakeGRPCHandler(endpoints, options))
return baseServer.Serve(grpcListener)
}, func(error) {
_ = level.Error(logger).Log("transport", "GRPC", "grpcListener.Close", grpcListener.Close())
})
}

func getServiceMiddleware(logger log.Logger) (mw []service.Middleware) {
mw = []service.Middleware{}
mw = addDefaultServiceMiddleware(logger, mw)
Expand Down
15 changes: 15 additions & 0 deletions cmd/service/service_gen.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
kitendpoint "github.com/go-kit/kit/endpoint"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/transport"
kitgrpc "github.com/go-kit/kit/transport/grpc"
kithttp "github.com/go-kit/kit/transport/http"
"github.com/icowan/shorter/pkg/endpoint"
"github.com/icowan/shorter/pkg/http"
Expand All @@ -23,6 +24,7 @@ import (
func createService(endpoints endpoint.Endpoints) (g *group.Group) {
g = &group.Group{}
initHttpHandler(endpoints, g)
initGrpcHandler(endpoints, g)
return g
}

Expand All @@ -37,9 +39,22 @@ func defaultHttpOptions(logger log.Logger) map[string][]kithttp.ServerOption {
kithttp.ServerErrorHandler(transport.NewLogErrorHandler(logger)),
kithttp.ServerBefore(kithttp.PopulateRequestContext),
}}

return options
}

func defaultGrpcOptions(logger log.Logger) map[string][]kitgrpc.ServerOption {
return map[string][]kitgrpc.ServerOption{
"Get": {
kitgrpc.ServerErrorHandler(transport.NewLogErrorHandler(logger)),
},
"Post": {
kitgrpc.ServerErrorHandler(transport.NewLogErrorHandler(logger)),
},
}

}

func addDefaultServiceMiddleware(logger log.Logger, mw []service.Middleware) []service.Middleware {
mw = append(mw, service.LoggingMiddleware(logger))
return mw
Expand Down
4 changes: 3 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ require (
github.com/go-playground/validator/v10 v10.0.1
github.com/go-redis/redis v6.15.6+incompatible
github.com/go-stack/stack v1.8.0 // indirect
github.com/golang/protobuf v1.3.3
github.com/golang/snappy v0.0.1 // indirect
github.com/google/go-cmp v0.3.1 // indirect
github.com/gorilla/mux v1.7.3
Expand All @@ -28,6 +29,7 @@ require (
github.com/xdg/stringprep v1.0.0 // indirect
go.mongodb.org/mongo-driver v1.1.3
golang.org/x/crypto v0.0.0-20191112222119-e1110fd1c708 // indirect
golang.org/x/sync v0.0.0-20190423024810-112230192c58 // indirect
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3
golang.org/x/time v0.0.0-20191024005414-555d28b269f0
google.golang.org/grpc v1.29.1
)
44 changes: 42 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
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/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
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/envoyproxy/go-control-plane v0.9.0/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/fastly/go-utils v0.0.0-20180712184237-d95a45783239 h1:Ghm4eQYC0nEPnSJdVkTrXpu9KtoVCSo1hg7mtI7G9KU=
github.com/fastly/go-utils v0.0.0-20180712184237-d95a45783239/go.mod h1:Gdwt2ce0yfBxPvZrHkprdPPTTS3N5rwmLE8T22KBXlw=
github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
Expand All @@ -22,10 +30,16 @@ github.com/go-redis/redis v6.15.6+incompatible h1:H9evprGPLI8+ci7fxQx6WNZHJSb7be
github.com/go-redis/redis v6.15.6+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA=
github.com/go-stack/stack v1.8.0 h1:5SgMzNM5HxrEjV0ww2lTmX6E2Izsfxas4+YHWRs3Lsk=
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
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 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM=
github.com/golang/protobuf v1.2.0/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 h1:gyjaxf+svBWX08ZjK86iN9geUJF0H6gp2IRKX6Nf6/I=
github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4=
github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/google/go-cmp v0.3.1 h1:Xye71clBPdm5HgqGwUkwhbynsUJZhDbS20FvLhQ2izg=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/gorilla/mux v1.7.3 h1:gnP5JzjVOuiZD07fKKToCAOjS0yOpj/qPETTXCCS6hw=
Expand Down Expand Up @@ -61,6 +75,7 @@ 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/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
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/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4=
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
Expand All @@ -72,8 +87,6 @@ github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJy
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/tebeka/strftime v0.1.3 h1:5HQXOqWKYRFfNyBMNVc9z5+QzuBtIXy03psIhtdJYto=
github.com/tebeka/strftime v0.1.3/go.mod h1:7wJm3dZlpr4l/oVK0t1HYIc4rMzQ2XJlOMIUJUJH6XQ=
github.com/teris-io/shortid v0.0.0-20171029131806-771a37caa5cf h1:Z2X3Os7oRzpdJ75iPqWZc0HeJWFYNCvKsfpQwFpRNTA=
github.com/teris-io/shortid v0.0.0-20171029131806-771a37caa5cf/go.mod h1:M8agBzgqHIhgj7wEn9/0hJUZcrvt9VY+Ln+S1I5Mha0=
github.com/tidwall/pretty v1.0.0 h1:HsD+QiTn7sK6flMKIvNmpqz1qrpP3Ps6jOKIKMooyg4=
github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
github.com/xdg/scram v0.0.0-20180814205039-7eeb5667e42c h1:u40Z8hqBAAQyv+vATcGgV0YCnDjqSL7/q/JyPhhJSPk=
Expand All @@ -85,13 +98,24 @@ go.mongodb.org/mongo-driver v1.1.3/go.mod h1:u7ryQJ+DOzQmeO7zB6MHyr8jkEQvC8vH7qL
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191112222119-e1110fd1c708 h1:pXVtWnwHkrWD9ru3sDxY/qFK/bfc0egRovX91EjWjf4=
golang.org/x/crypto v0.0.0-20191112222119-e1110fd1c708/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=
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/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-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 h1:0GoQqolDA55aaLxZyTzK/Y2ePZzZTUrRacwib7cNsYQ=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f h1:wMNYb4v58l5UBM7MYRLPG6ZhfOqbKu7X5eyFl8ZhKvA=
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-20190423024810-112230192c58 h1:8gQV6CLnAEikrhgkHFbMAEhagSSnXWGV915qUMm9mrU=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/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-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-20190412213103-97732733099d h1:+R4KGOnez64A81RvjARKc4UT5/tI9ujCIVX+P5KiHuI=
Expand All @@ -104,6 +128,20 @@ golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/time v0.0.0-20191024005414-555d28b269f0 h1:/5xXl8Y5W96D+TtHSlonuFqGHIWVuyCkGJLwGh9JJFs=
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
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-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
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/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55 h1:gSJIx1SDwno+2ElGhA4+qG2zF97qiUzTM+rQ0klBOcE=
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
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.29.1 h1:EC2SB8S04d2r73uptxphDSUG+kTKVgjRPF+N3xpxRB4=
google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk=
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/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4=
Expand All @@ -113,3 +151,5 @@ gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWD
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.4 h1:/eiJrUcujPVeJ3xlSWaiNi3uSVmDGBK1pDHUHAnao1I=
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
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=
109 changes: 109 additions & 0 deletions pkg/grpc/handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
/**
* @Time : 27/04/2020 11:34 AM
* @Author : solacowa@gmail.com
* @File : handler
* @Software: GoLand
*/

package grpc

import (
"context"
"github.com/icowan/shorter/pkg/service"

kitgrpc "github.com/go-kit/kit/transport/grpc"
endpoint2 "github.com/icowan/shorter/pkg/endpoint"
"github.com/icowan/shorter/pkg/grpc/pb"
)

type grpcServer struct {
get kitgrpc.Handler
post kitgrpc.Handler
}

func (g *grpcServer) Get(ctx context.Context, req *pb.GetRequest) (*pb.ServiceResponse, error) {
_, rep, err := g.get.ServeGRPC(ctx, req)
if err != nil {
return nil, err
}
return rep.(*pb.ServiceResponse), nil
}

func (g *grpcServer) Post(ctx context.Context, req *pb.PostRequest) (*pb.ServiceResponse, error) {
_, rep, err := g.post.ServeGRPC(ctx, req)
if err != nil {
return nil, err
}
return rep.(*pb.ServiceResponse), nil
}

func MakeGRPCHandler(eps endpoint2.Endpoints, opts map[string][]kitgrpc.ServerOption) pb.ShorterServer {
return &grpcServer{
get: kitgrpc.NewServer(
eps.GetEndpoint,
decodeGetRequest,
encodeResponse,
opts["Get"]...,
),
post: kitgrpc.NewServer(
eps.PostEndpoint,
decodePostRequest,
encodePostResponse,
opts["Post"]...,
),
}
}

func decodePostRequest(ctx context.Context, r interface{}) (interface{}, error) {
return endpoint2.PostRequest{URL: r.(*pb.PostRequest).GetDomain()}, nil
}

func decodeGetRequest(_ context.Context, r interface{}) (interface{}, error) {
return endpoint2.GetRequest{Code: r.(*pb.GetRequest).Code}, nil
}

func encodeResponse(_ context.Context, r interface{}) (interface{}, error) {
resp := r.(endpoint2.GetResponse)
var (
errStr string
err error
dataResponse *pb.ResponseData
)
if resp.Err != nil {
errStr = resp.Err.Error()
err = resp.Err
}
if resp.Data != nil {
data := resp.Data.(*service.Redirect)
dataResponse = &pb.ResponseData{
Url: data.URL,
Code: data.Code,
ShortUri: data.URL,
}
}

return &pb.ServiceResponse{
Data: dataResponse,
Err: errStr,
}, err
}

func encodePostResponse(_ context.Context, r interface{}) (interface{}, error) {
resp := r.(endpoint2.PostResponse)
var (
errStr string
err error
)
if resp.Err != nil {
errStr = resp.Err.Error()
err = resp.Err
}
return &pb.ServiceResponse{
Data: &pb.ResponseData{
Url: resp.Data.Url,
Code: resp.Data.Code,
ShortUri: resp.Data.ShortUri,
},
Err: errStr,
}, err
}
Loading

0 comments on commit 0073b36

Please sign in to comment.