使用微服务构建一个 TODO 应用,可能会给人一种杀鸡用牛刀(overkill)的感觉,但是其实还是非常好的 Gokit based 案例,以及了解如何用脚手架工具 GrantZheng/kit 快速构建一个项目。
source code:**
https://github.com/WenyXu/todo-gokit-demo
设计目标
- 显示所有存在 TODO
- 允许用户新增 TODO
- 允许用户变更 TODO
- 允许用户删除 TODO
事前准备
Go 环境
安装脚手架工具
git clone https://github.com/GrantZheng/kit.gitcd kitgo install
创建一个服务(Service)
kit new service todokit n s todo # using aliases
我们会得到如下的一个结构
todo/|---pkg/|------service/|----------service.go
service.go
package service// TodoService describes the service.type TodoService interface {// Add your methods here// e.x: Foo(ctx context.Context,s string)(rs string, err error)}
在这里我们会定义所有我们服务路径(Service Endpoint),或许更多时候在 MVC 框架中被叫做 Route
定义数据模型
创建一下目录及文件,IO层(或许更多时候在 MVC 框架中被叫做 Model)
todo/
|---pkg/
|------io/
|----------io.go
package io
import "encoding/json"
//Todo struct
type Todo struct {
ID string `json:"id"`
Title string `json:"title"`
Complete bool `json:"complete"`
}
func (t Todo) String() string{
b, err := json.Marshal(t)
if err != nil{
return "unsupported value type"
}
return string(b)
}
回到 service.go 定义我们的路径(Endpoint)
// TodoService describes the service.
type TodoService interface {
Get(ctx context.Context) (t []io.Todo, err error)
Add(ctx context.Context, todo io.Todo) (t io.Todo, err error)
Update(ctx context.Context, todo io.Todo) (t io.Todo, err error)
Delete(ctx context.Context, id string) (err error)
}
使用脚手架生成代码
kit g s todo
kit g s todo --dmw # to create the default middleware
kit g s todo -t grpc # specify the transport (default is http)
我们在这使用使用
kit g s todo --dmw # to create the default middleware
来生成一个基本的包含中间件的服务(Service)
脚手架会帮助我们生成以下结构
todo/
|---cmd/
|------service/
|----------server.go Wire the service.
|----------server_gen.go Also wire the service.
|------main.go Runs the service
|---pkg/
|------endpoints/
|----------endpoint.go The endpoint logic.
|----------endpoint_gen.go This will wire the endpoints.
|----------middleware.go Endpoint middleware
|------http/
|----------handler.go Transport logic encode/decode data.
|----------handler_gen.go This will wire the transport.
|------io/
|----------io.go The input output structs.
|------service/
|----------middleware.go The service middleware.
|----------service.go Business logic.
实现 DB 层
创建一下目录及文件
todo/
|---pkg/
|------db/
|----------db.go
为了简化流程,我们基于内存数据实现我们的 DB 层。
package db
import "todo/pkg/io"
// Service interface
type Service interface {
Get() (t []io.Todo, err error)
Add(todo io.Todo) (t io.Todo, err error)
Update(todo io.Todo) (t io.Todo, err error)
Delete(id string)(err error)
}
func mapToSlice(m map[string]io.Todo) []io.Todo {
s := make([]io.Todo, 0, len(m))
for _, v := range m {
s = append(s, v)
}
return s
}
// service struct
type svc struct {
todoList map[string]io.Todo
}
func (s *svc) Get()(t []io.Todo, err error){
return mapToSlice(s.todoList),nil
}
func (s *svc) Add(todo io.Todo) (t io.Todo, err error){
s.todoList[todo.ID]=todo
return todo,nil
}
func (s *svc) Update(todo io.Todo) (t io.Todo, err error){
s.todoList[todo.ID]=todo
return todo,nil
}
func (s *svc) Delete(id string) (err error){
delete(s.todoList,id)
return nil
}
func NewService() Service{
return &svc{todoList: map[string]io.Todo{}}
}
初始化数据库
service.go
import (
db2 "todo/pkg/db"
)
type basicTodoService struct{
db db2.Service
}
// NewBasicTodoService returns a naive, stateless implementation of TodoService.
func NewBasicTodoService() TodoService{
return &basicTodoService{db:db2.NewService()}
}
Get 实现
func (b *basicTodoService) Get(ctx context.Context) (t []io.Todo, err error) {
t, err = b.db.Get()
return t, err
}
Add 实现
func (b *basicTodoService) Add(ctx context.Context, todo io.Todo) (t io.Todo, err error) {
t, err = b.db.Add(todo)
return t, err
}
修改 Handler
todo/http/handler.go
从:
// decodeGetRequest is a transport/http.DecodeRequestFunc that decodes a
// JSON-encoded request from the HTTP request body.
func decodeGetRequest(_ context.Context, r *http.Request) (interface{}, error) {
req := endpoint.GetRequest{}
err := json.NewDecoder(r.Body).Decode(&req)
return req, err
}
更改为:
// decodeGetRequest is a transport/http.DecodeRequestFunc that decodes a
// JSON-encoded request from the HTTP request body.
func decodeGetRequest(_ context.Context, r *http.Request) (interface{}, error) {
req := endpoint.GetRequest{}
return req, nil
}
Update 实现
func (b *basicTodoService) Update(ctx context.Context, todo io.Todo) (t io.Todo, err error) {
t, err = b.db.Update(todo)
return t, err
}
Delete 实现
func (b *basicTodoService) Delete(ctx context.Context, id string) (err error) {
err = b.db.Delete(id)
return err
}
运行
go run todo/cmd/main.go
手动测试
Add
curl --location --request GET 'localhost:8081/add' \
--header 'Content-Type: application/json' \
--data-raw '{"todo":{"title":"test1","id":"1","complete":true}}'
Result
{"t":{"id":"1","title":"test1","complete":true},"err":null}
Get
curl --location --request GET 'localhost:8081/get' \
--header 'Content-Type: application/json'
Result
{"t":[{"id":"1","title":"test1","complete":true}],"err":null}
Update
curl --location --request GET 'localhost:8081/update' \
--header 'Content-Type: application/json' \
--data-raw '{"todo":{"title":"test2","id":"1","complete":true}}'
Result
{"t":{"id":"1","title":"test2","complete":true},"err":null}
Delete
curl --location --request GET 'localhost:8081/delete' \
--header 'Content-Type: application/json' \
--data-raw '{"id":"1"}'
Result
{"err": null}
其他特性
生成一个新的服务路径( Service Endpoint)
// TodoService describes the service.
type TodoService interface {
Get(ctx context.Context) (t []io.Todo, err error)
Add(ctx context.Context, todo io.Todo) (t io.Todo, err error)
Update(ctx context.Context, todo io.Todo) (t io.Todo, err error)
Delete(ctx context.Context, id string) (err error)
GetById(ctx context.Context, id string) (t io.Todo, error error)
}
运行
kit g s todo --dmw
脚手架会创建所有缺失的 Endpoint 实现函数和中间件以及重新生成_gen后缀文件
为服务(Service)添加中间件(Middleware)
kit g m auth -s todo
会生成以下代码在todo/service/middleware.go
type authMiddleware struct {
next TodoService
}
// AuthMiddleware returns a TodoService Middleware.
func AuthMiddleware() Middleware {
return func(next TodoService) TodoService {
return &authMiddleware{next}
}
}
func (a authMiddleware) Get(ctx context.Context) (t []io.Todo, error error) {
// Implement your middleware logic here
return a.next.Get(ctx)
}
func (a authMiddleware) Add(ctx context.Context, todo io.Todo) (t io.Todo, error error) {
// Implement your middleware logic here
return a.next.Add(ctx, todo)
}
func (a authMiddleware) SetComplete(ctx context.Context, id string) (error error) {
// Implement your middleware logic here
return a.next.SetComplete(ctx, id)
}
func (a authMiddleware) RemoveComplete(ctx context.Context, id string) (error error) {
// Implement your middleware logic here
return a.next.RemoveComplete(ctx, id)
}
func (a authMiddleware) Delete(ctx context.Context, id string) (error error) {
// Implement your middleware logic here
return a.next.Delete(ctx, id)
}
为路径(Endpoint)添加中间件(Middleware)
kit g m auth -s todo -e
会生成以下代码在todo/service/middleware.go
// AuthMiddleware returns an endpoint middleware
func AuthMiddleware() endpoint.Middleware {
return func(next endpoint.Endpoint) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
// Add your middleware logic here
return next(ctx, request)
}
}
}
添加你的中间件到todo/cmd/service/service.go#getServiceMiddleware以及todo/cmd/service/service.go#getEndpointMiddleware函数中
func getServiceMiddleware(logger log.Logger) (mw []service.Middleware) {
mw = []service.Middleware{}
mw = addDefaultServiceMiddleware(logger, mw)
// My auth middleware
mw = append(mw, service.AuthMiddleware())
return
}
func getEndpointMiddleware(logger log.Logger) (mw map[string][]endpoint1.Middleware) {
mw = map[string][]endpoint1.Middleware{}
duration := prometheus.NewSummaryFrom(prometheus1.SummaryOpts{
Help: "Request duration in seconds.",
Name: "request_duration_seconds",
Namespace: "example",
Subsystem: "todo",
}, []string{"method", "success"})
addDefaultEndpointMiddleware(logger, duration, mw)
// My auth middleware
addEndpointMiddlewareToAllMethods(mw,endpoint.AuthMiddleware())
return
}
为单一路径(Endpoint)添加中间件(Middleware)
addEndpointMiddlewareToAllMethods(mw,endpoint.AuthMiddleware())
...
func addEndpointMiddlewareToAllMethods(mw map[string][]endpoint1.Middleware, m endpoint1.Middleware) {
methods := []string{"Get", "Add", "Update", "Delete", "GetById"}
for _, v := range methods {
mw[v] = append(mw[v], m)
}
}
addEndpointMiddlewareToAllMethods会为所有路径添加中间件,当你只需要单一路径添加中间件的时候:
func getEndpointMiddleware(logger log.Logger) (mw map[string][]endpoint1.Middleware) {
mw = map[string][]endpoint1.Middleware{}
duration := prometheus.NewSummaryFrom(prometheus1.SummaryOpts{
Help: "Request duration in seconds.",
Name: "request_duration_seconds",
Namespace: "example",
Subsystem: "todo",
}, []string{"method", "success"})
addDefaultEndpointMiddleware(logger, duration, mw)
// My auth middleware only for the "Get" method
mw["Get"] = append(mw["Get"], endpoint.AuthMiddleware())
return
}
添加 gRPC transport
kit g s todo --dmw -t grpc
参考
medium story
原文作者的 kujtimiihoxha/kit 项目已不再进行维护,所以基于 GrantZheng/kit 的版本重写了一篇。
