go-kit學習指南 - 基礎概念和架構

原文:https://blog.fengjx.com/pages/40737e

介紹

go-kit 是一個微服務開發工具集,並不算一個完整的框架。根據工程實踐總結的一套開發規範,解決分佈式開發中的常見問題,它同樣也適用於單體服務開發。

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

分層設計

go-kit 的分層設計思想是指將一個微服務應用程序劃分爲不同的層次,每個層次負責特定的功能,並且層與層之間的依賴關係被限制在特定的方向上。這種分層設計有助於提高代碼的可維護性、可擴展性和可測試性,使得系統更容易理解、修改和維護。

  • 傳輸(Transport)層:負責處理網絡通信協議,例如 HTTP、gRPC 等,並將請求和響應轉換爲端點可以處理的數據結構。
  • 端點(Endpoints)層: 整個服務的入口,負責將網絡請求轉換爲業務邏輯調用,並將結果轉換爲網絡響應。
  • 服務(Service)層:務層包含了實際的業務邏輯實現,負責處理請求併產生相應的結果。

go-kit

實現步驟

以下是實現一個簡單的 say-hello 的示例。

示例代碼: https://github.com/fengjx/go-kit-demo/tree/master/greetsvc

參考代碼

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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章