go-kit学习指南 - 基础概念和架构

98 阅读2分钟

介绍

go-kit 是一个微服务开发工具集,并不算一个完整的框架。根据工程实践总结的一套开发规范,解决分布式开发中的常见问题,它同样也适用于单体服务开发。

github 地址:github.com/go-kit/kit

分层设计

go-kit 的分层设计思想是指将一个微服务应用程序划分为不同的层次,每个层次负责特定的功能,并且层与层之间的依赖关系被限制在特定的方向上。这种分层设计有助于提高代码的可维护性、可扩展性和可测试性,使得系统更容易理解、修改和维护。

  • 传输(Transport)层:负责处理网络通信协议,例如 HTTP、gRPC 等,并将请求和响应转换为端点可以处理的数据结构。
  • 端点(Endpoints)层: 整个服务的入口,负责将网络请求转换为业务逻辑调用,并将结果转换为网络响应。
  • 服务(Service)层:务层包含了实际的业务逻辑实现,负责处理请求并产生相应的结果。

go-kit.png

实现步骤

以下是实现一个简单的 say-hello 的示例。

示例代码: github.com/fengjx/go-k…

参考代码

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"net/http"

	"github.com/go-kit/kit/endpoint"
	httptransport "github.com/go-kit/kit/transport/http"
)

func main() {

	svc := greetService{}

	satHelloHandler := httptransport.NewServer(
		makeHelloEndpoint(svc),
		decodeRequest,
		encodeResponse,
	)

	http.Handle("/say-hello", satHelloHandler)
	log.Println("http server start")
	log.Fatal(http.ListenAndServe(":8080", nil))
}

type helloReq struct {
	Name string `json:"name"`
}

type helloResp struct {
	Msg string `json:"msg"`
}

type greetService struct {
}

func (svc greetService) SayHi(_ context.Context, name string) string {
	return fmt.Sprintf("hi: %s", name)
}

func makeHelloEndpoint(svc greetService) endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (interface{}, error) {
		req := request.(*helloReq)
		msg := svc.SayHi(ctx, req.Name)
		return helloResp{
			Msg: msg,
		}, nil
	}
}

func decodeRequest(_ context.Context, r *http.Request) (interface{}, error) {
	name := r.URL.Query().Get("name")
	req := &helloReq{
		Name: name,
	}
	return req, nil
}

func encodeResponse(_ context.Context, w http.ResponseWriter, response interface{}) error {
	data := map[string]any{
		"status": 0,
		"msg":    "ok",
		"data":   response,
	}
	return json.NewEncoder(w).Encode(data)
}

go-kit 的 helloworld 示例代码远比其他 web 框架复杂,主要是它有一套严格的分层规范和多协议支持。根据过往大型项目的实践来看,必要的代码分层对于多人协作开发的项目至关重要,可以保持代码的可维护和可扩展性,这对于长期维护的项目收益巨大。

启动服务

go run main.go

测试

# sya-hello
curl http://localhost:8080/say-hello?name=fengjx