- Hands-On Microservices with Kubernetes
- Gigi Sayfan
- 291字
- 2021-06-24 13:46:43
Structuring microservices with Go kit
Go kit is all about best practices. Your business logic is implemented as pure Go libraries that only deal with interfaces and Go structs. All the complex aspects involved in APIs, serialization, routing, and networking will be relegated to clearly separate layers that are taking advantage of Go kit concepts and infrastructures such as transports, endpoints, and services. This makes for a great development experience, where you can evolve and test your application code in the simplest environment possible. Here is the interface for one of Delinkcious' services – the social graph. Note that it is in plain Go. There is no notion of API, microservice, or even Go kit imports:
type SocialGraphManager interface {
Follow(followed string, follower string) error
Unfollow(followed string, follower string) error
GetFollowing(username string) (map[string]bool, error)
GetFollowers(username string) (map[string]bool, error)
}
The implementation of this interface resides in a Go package that is still completely agnostic of Go kit or even the fact it is being used in a microservice:
package social_graph_manager
import (
"errors"
om "github.com/the-gigi/delinkcious/pkg/object_model"
)
type SocialGraphManager struct {
store om.SocialGraphManager
}
func (m *SocialGraphManager) Follow(followed string, follower string) (err error) {
...
}
func (m *SocialGraphManager) Unfollow(followed string, follower string) (err error) {
...
}
func (m *SocialGraphManager) GetFollowing(username string) (map[string]bool, error) {
...
}
func (m *SocialGraphManager) GetFollowers(username string) (map[string]bool, error) {
...
}
A good way to think of a Go kit service is as an onion with different layers. At the core is your business logic and layered on top are various concerns such as routing, rate limiting, logging, and metrics, which are eventually exposed to other services or the world over transports:
Go kit primarily supports RPC-style communication by using a request-response model.