Last active
November 2, 2017 07:09
-
-
Save travisjeffery/c33e43ed6a3d6b225d71dc877b527efa to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// example.proto | |
service Users { | |
rpc GetUser (GetUserRequest) returns (GetUserResponse) {} | |
} | |
message GetUserResponse { | |
User user = 1; | |
Error error = 2; | |
} | |
// endpoints.go | |
func makeGetUserEndpoint(userService user.Service) endpoint.Endpoint { | |
return func(ctx context.Context, request interface{}) (interface{}, error) { | |
req := request.(*GetUserRequest) | |
user, err := userService.GetUser(req.User) | |
if err != nil { | |
return &GetUserResponse{Error: err.(*Error)}, nil | |
} | |
return &GetUserResponse{User: user}, nil | |
} | |
} | |
// transport.go | |
r.Methods("GET").Handle("/users/{id}", httptransport.NewServer( | |
endpoints.GetUserEndpoint, | |
decodeGetUserRequest, | |
encodeResponse, | |
options..., | |
)) | |
type errorer interface { | |
GetError() *example.Error | |
} | |
func encodeResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error { | |
if e, ok := response.(errorer); ok { | |
if err := e.GetError(); err != nil { | |
w.WriteHeader(int(err.Code)) | |
} | |
} | |
w.Header().Set("Content-Type", "application/json; charset=utf-8") | |
return json.NewEncoder(w).Encode(response) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment