Created
July 17, 2023 18:19
-
-
Save AryanGodara/58e5c61d57559691953b800585f2ce4c to your computer and use it in GitHub Desktop.
endpoints/endpoints.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package endpoints | |
import ( | |
"context" | |
"github.com/aryangodara/go-kit-grpc-example1/api/service" | |
"github.com/go-kit/kit/endpoint" | |
) | |
// Endpoints struct holds a list of endpoints | |
type Endpoints struct { | |
Add endpoint.Endpoint | |
Subtract endpoint.Endpoint | |
Multiply endpoint.Endpoint | |
Divide endpoint.Endpoint | |
} | |
// MathReq struct holds the endpoint request definition | |
type MathReq struct { | |
NumA float32 `json:"num_a"` | |
NumB float32 `json:"num_b"` | |
} | |
// MathResp struct holds the endpoint response definition | |
type MathResp struct { | |
Result float32 `json:"result"` | |
} | |
// MakeAddEndpoint struct holds the endpoint response definition | |
func MakeEndpoints(s service.Service) Endpoints { | |
return Endpoints{ | |
Add: makeAddEndpoint(s), | |
Subtract: makeSubtractEndpoint(s), | |
Multiply: makeMultiplyEndpoint(s), | |
Divide: makeDivideEndpoint(s), | |
} | |
} | |
func makeAddEndpoint(s service.Service) endpoint.Endpoint { | |
return func(ctx context.Context, request interface{}) (interface{}, error) { | |
req := request.(MathReq) | |
result, err := s.Add(ctx, req.NumA, req.NumB) | |
if err != nil { | |
return MathResp{result}, err | |
} | |
return MathResp{result}, nil | |
} | |
} | |
func makeSubtractEndpoint(s service.Service) endpoint.Endpoint { | |
return func(ctx context.Context, request interface{}) (interface{}, error) { | |
req := request.(MathReq) | |
result, err := s.Subtract(ctx, req.NumA, req.NumB) | |
if err != nil { | |
return MathResp{result}, err | |
} | |
return MathResp{result}, nil | |
} | |
} | |
func makeMultiplyEndpoint(s service.Service) endpoint.Endpoint { | |
return func(ctx context.Context, request interface{}) (interface{}, error) { | |
req := request.(MathReq) | |
result, err := s.Multiply(ctx, req.NumA, req.NumB) | |
if err != nil { | |
return MathResp{result}, err | |
} | |
return MathResp{result}, nil | |
} | |
} | |
func makeDivideEndpoint(s service.Service) endpoint.Endpoint { | |
return func(ctx context.Context, request interface{}) (interface{}, error) { | |
req := request.(MathReq) | |
result, err := s.Divide(ctx, req.NumA, req.NumB) | |
if err != nil { | |
return MathResp{result}, err | |
} | |
return MathResp{result}, nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment