最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

關于go-zero單體服務使用泛型簡化注冊Handler路由的問題

 更新時間:2022年07月27日 16:49:46   作者:修車課代表  
這篇文章主要介紹了go-zero單體服務使用泛型簡化注冊Handler路由,涉及到Golang環(huán)境安裝及配置Go Module的相關知識,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下

一、Golang環(huán)境安裝及配置Go Module

https://go-zero.dev/cn/docs/prepare/golang-install

mac OS安裝Go#

  • 下載并安裝Go for Mac
  • 驗證安裝結果
$ go version
go version go1.15.1 darwin/amd64

linux 安裝Go#

  • 下載Go for Linux
  • 解壓壓縮包至/usr/local
$ tar -C /usr/local -xzf go1.15.8.linux-amd64.tar.gz

添加/usr/local/go/bin到環(huán)境變量

$ $HOME/.profile
$ export PATH=$PATH:/usr/local/go/bin
$ source $HOME/.profile

驗證安裝結果

$ go version
go version go1.15.1 linux/amd64

Windows安裝Go#

下載并安裝Go for Windows驗證安裝結果

$ go version
go version go1.15.1 windows/amd64

MODULE配置

Go Module是Golang管理依賴性的方式,像Java中的Maven,Android中的Gradle類似。

查看GO111MODULE開啟情況

$ go env GO111MODULE
on

開啟GO111MODULE,如果已開啟(即執(zhí)行go env GO111MODULE結果為on)請?zhí)^。

$ go env -w GO111MODULE="on"

設置GOPROXY

$ go env -w GOPROXY=https://goproxy.cn

設置GOMODCACHE

查看GOMODCACHE

$ go env GOMODCACHE

如果目錄不為空或者/dev/null,請?zhí)^。

go env -w GOMODCACHE=$GOPATH/pkg/mod

二、Goctl 安裝

Goctl在go-zero項目開發(fā)著有著很大的作用,其可以有效的幫助開發(fā)者大大提高開發(fā)效率,減少代碼的出錯率,縮短業(yè)務開發(fā)的工作量,更多的Goctl的介紹請閱讀Goctl介紹

安裝(mac&linux)

### Go 1.15 及之前版本
GO111MODULE=on GOPROXY=https://goproxy.cn/,direct go get -u github.com/zeromicro/go-zero/tools/goctl@latest
### Go 1.16 及以后版本
GOPROXY=https://goproxy.cn/,direct go install github.com/zeromicro/go-zero/tools/goctl@latest

安裝(windows)

go install github.com/zeromicro/go-zero/tools/goctl@latest

環(huán)境變量檢測(mac&linux)
go get 下載編譯后的二進制文件位于 \$GOPATH/bin 目錄下,要確保 $GOPATH/bin已經添加到環(huán)境變量。

sudo vim /etc/paths //添加環(huán)境變量

在最后一行添加如下內容 //$GOPATH 為你本機上的文件地址

$GOPATH/bin 

安裝結果驗證

$ goctl -v
goctl version 1.1.4 darwin/amd64

二、初始化go-zero

快速生成 api 服務

goctl api new greet
cd greet
go mod init
go mod tidy
go run greet.go -f etc/greet-api.yaml

默認偵聽在 8888 端口
偵聽端口可以在greet-api.yaml配置文件里修改,此時,可以通過 curl 請求,或者直接在瀏覽器中打開http://localhost:8888/from/you

$ curl -i http://localhost:8888/from/you
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Traceparent: 00-45fa9e7a7c505bad3a53a024e425ace9-eb5787234cf3e308-00
Date: Thu, 22 Oct 2020 14:03:18 GMT
Content-Length: 14
null

greet服務的目錄結構

$ tree greet
greet
├── etc
│   └── greet-api.yaml
├── greet.api
├── greet.go
└── internal
    ├── config
    │   └── config.go
    ├── handler
    │   ├── greethandler.go
    │   └── routes.go
    ├── logic
    │   └── greetlogic.go
    ├── svc
    │   └── servicecontext.go
    └── types
        └── types.go

三、查看注冊Handler路由流程greet.go

var configFile = flag.String("f", "etc/greet-api.yaml", "the config file")
func main() {
	flag.Parse()
	var c config.Config
	conf.MustLoad(*configFile, &c)
	server := rest.MustNewServer(c.RestConf)
	defer server.Stop()
        //上面的都是加載配置什么的
	ctx := svc.NewServiceContext(c)
	handler.RegisterHandlers(server, ctx) //此方法是注冊路由和路由映射Handler,重點在這里
	fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
	server.Start()
}

RegisterHandlers在internal\handler\routes.go

func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
   server.AddRoutes( //往rest.Server中添加路由
	[]rest.Route{ //路由數(shù)組
	   {
	      Method:  http.MethodGet,
	      Path:    "/from/:name", //路由
	      Handler: GreetHandler(serverCtx),//當前路由的處理Handler
	   },
	},
   )
}

GreetHandler在internal\handler\greethandler.go

func GreetHandler(ctx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req types.Request
	if err := httpx.Parse(r, &req); err != nil { //請求的錯誤判斷,這個可以不用管
			httpx.Error(w, err)
			return
		}
 
		l := logic.NewGreetLogic(r.Context(), ctx) //GreetHandler處理函數(shù)將請求轉發(fā)到了GreetLogic中,調用NewGreetLogic進行結構體的初始化
		resp, err := l.Greet(req) //然后調用Greet來進行處理請求,所以我們在GreetLogic.Greet方法中可以看到一句話// todo: add your logic here and delete this line
		if err != nil {
			httpx.Error(w, err)
		} else {
			httpx.OkJson(w, resp)
		}
	}
}

四、對注冊Handler路由進行簡化

項目文件的增加

在路由注冊時,我們如果服務越加越多,那么相對應的func xxxxHandler(ctx *svc.ServiceContext) http.HandlerFunc就要進行多次的添加,并且這個方法體內部1到5行是屬于額外的重復添加
例如:我們添加一個customlogic.go
按照命名的正確和規(guī)范性,需要在internal\logic目錄下添加customlogic.go文件,然后在internal\handler目錄下添加customhandler.go文件,并且兩個文件都添加相對應的結構體和函數(shù)等,最后在routes.go中再添加一次

{
    Method:  http.MethodGet,
    Path:    "/custom/:name",
    Handler: CustomHandler(serverCtx),
},

此時,我們的文件結構應該是這樣

greet
├── etc
│   └── greet-api.yaml
├── greet.api
├── greet.go
└── internal
    ├── config
    │   └── config.go
    ├── handler
    │   ├── greethandler.go
    │   ├── customhandler.go
    │   ├── ...
    │   └── routes.go
    ├── logic
    │   ├── greetlogic.go
    │   ├── ...
    │   └── customlogic.go
    ├── svc
    │   └── servicecontext.go
    └── types
        └── types.go

當單體應用達到一定的數(shù)量級,handler和logic文件夾下將會同步增加很多的文件

引入泛型概念

自Go1.18開始,go開始使用泛型,泛型的廣泛定義 :是一種把明確類型的工作推遲到創(chuàng)建對象或者調用方法的時候才去明確的特殊的類型。 也就是說在泛型使用過程中,操作的數(shù)據類型被指定為一個參數(shù),而這種參數(shù)類型可以用在 類、方法和接口 中,分別被稱為 泛型類 、 泛型方法 、 泛型接口 。
我們可以利用泛型,讓在添加路由時就要固定死的Handler: GreetHandler(serverCtx)推遲到后面,去根據實際的Logic結構體去判斷需要真正執(zhí)行的logic.NewGreetLogic(r.Context(), ctx)初始化結構體和l.Greet(req)邏輯處理方法

如何去做在internal\logic下添加一個baselogic.go文件,參考Go泛型實戰(zhàn) | 如何在結構體中使用泛型

package logic
import (
	"greet/internal/svc"
	"greet/internal/types"
	"net/http"
)
type BaseLogic interface {
	any
	Handler(req types.Request, w http.ResponseWriter, r *http.Request, svcCtx *svc.ServiceContext) //每一個結構體中必須要繼承一下Handler方法,例如customlogic.go和greetlogic.go中的Handler方法
}
type logic[T BaseLogic] struct {
	data T
}
func New[T BaseLogic]() logic[T] {
	c := logic[T]{}
	var ins T
	c.data = ins
	return c
}
func (a *logic[T]) LogicHandler(req types.Request, w http.ResponseWriter, r *http.Request, svcCtx *svc.ServiceContext) { //作為一個中轉處理方法,最終執(zhí)行結構體的Handler
	a.data.Handler(req, w, r, svcCtx)
}

greethandler.go文件修改成basehandler.go,注釋掉之前的GreetHandler方法

package handler
import (
	"net/http"
	"greet/internal/logic"
	"greet/internal/svc"
	"greet/internal/types"
	"github.com/zeromicro/go-zero/rest/httpx"
)
// func GreetHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
// 	return BaseHandlerFunc(svcCtx)
// 	// return func(w http.ResponseWriter, r *http.Request) {
// 	// 	var req types.Request
// 	// 	if err := httpx.Parse(r, &req); err != nil {
// 	// 		httpx.Error(w, err)
// 	// 		return
// 	// 	}
// 	// 	l := logic.NewGreetLogic(r.Context(), svcCtx)
// 	// 	resp, err := l.Greet(&req)
// 	// 	if err != nil {
// 	// 		httpx.Error(w, err)
// 	// 	} else {
// 	// 		httpx.OkJson(w, resp)
// 	// 	}
// 	// }
// }
func BaseHandlerFunc[T logic.BaseLogic](svcCtx *svc.ServiceContext, t T) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req types.Request
		if err := httpx.Parse(r, &req); err != nil {
			httpx.Error(w, err)
			return
		}
		//通過泛型動態(tài)調用不同結構體的Handler方法
		cc := logic.New[T]()
		cc.LogicHandler(req, w, r, svcCtx)
	}
}

internal\logic\greetlogic.go中增加一個Handler方法

package logic
import (
	"context"
	"net/http"
	"greet/internal/svc"
	"greet/internal/types"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpx"
)
type GreetLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}
func NewGreetLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GreetLogic {
	return &GreetLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}
func (a GreetLogic) Handler(req types.Request, w http.ResponseWriter, r *http.Request, svcCtx *svc.ServiceContext) { //新增方法
	l := NewGreetLogic(r.Context(), svcCtx)
	resp, err := l.Greet(&req)
	if err != nil {
		httpx.Error(w, err)
	} else {
		httpx.OkJson(w, resp)
	}
}
func (l *GreetLogic) Greet(req *types.Request) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line
	response := new(types.Response)
	if (*req).Name == "me" {
		response.Message = "greetLogic: listen to me, thank you."
	} else {
		response.Message = "greetLogic: listen to you, thank me."
	}
	return response, nil
}

然后修改internal\handler\routes.go下面的server.AddRoutes部分

func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
   server.AddRoutes( //往rest.Server中添加路由
	[]rest.Route{ //路由數(shù)組
	   {
	      Method:  http.MethodGet,
	      Path:    "/from/:name", //路由
	      Handler: BaseHandlerFunc(serverCtx,logic.GreetLogic{}),
	   },
	},
   )
}

現(xiàn)在就大功告成了,我們啟動一下

go run greet.go -f etc/greet-api.yaml

然后在瀏覽器中請求一下http://localhost:8888/from/you

驗證一下新增api路由在internal\logic下新增一個customlogic.go文件

package logic
import (
	"context"
	"net/http"
	"greet/internal/svc"
	"greet/internal/types"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpx"
)
type CustomLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}
func NewCustomLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CustomLogic {
	return &CustomLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}
func (a CustomLogic) Handler(req types.Request, w http.ResponseWriter, r *http.Request, svcCtx *svc.ServiceContext) {
	l := NewCustomLogic(r.Context(), svcCtx)
	resp, err := l.Custom(&req)
	if err != nil {
		httpx.Error(w, err)
	} else {
		httpx.OkJson(w, resp)
	}
}
func (l *CustomLogic) Custom(req *types.Request) (resp *types.Response, err error) { //response.Message稍微修改了一下,便于區(qū)分
	// todo: add your logic here and delete this line
	response := new(types.Response)
	if (*req).Name == "me" {
		response.Message = "customLogic: listen to me, thank you."
	} else {
		response.Message = "customLogic: listen to you, thank me."
	}
	return response, nil
}

然后修改internal\handler\routes.go

func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
   server.AddRoutes( //往rest.Server中添加路由
	[]rest.Route{ //路由數(shù)組
	   {
	      Method:  http.MethodGet,
	      Path:    "/from/:name", //路由
	      Handler: BaseHandlerFunc(serverCtx,logic.GreetLogic{}),
	   },
           {
	      Method:  http.MethodGet,
	      Path:    "/to/:name", //路由
	      Handler: BaseHandlerFunc(serverCtx,logic.CustomLogic{}),
	   },
	},
   )
}

其他地方不需要修改
我們啟動一下

go run greet.go -f etc/greet-api.yaml

然后在瀏覽器中請求一下http://localhost:8888/from/you、http://localhost:8888/to/you、http://localhost:8888/too/you

現(xiàn)在,在添加新的logic做路由映射時,就可以直接簡化掉添加xxxxhandler.go文件了,實際上是將這個Handler移動到了xxxxlogic.go中。

本文代碼放在go-zero-monolithic-service-generics

到此這篇關于go-zero單體服務使用泛型簡化注冊Handler路由的文章就介紹到這了,更多相關go-zero單體服務內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • golang實現(xiàn)給圖片加水印

    golang實現(xiàn)給圖片加水印

    這篇文章主要為大家詳細介紹了Vue3如何利用golang實現(xiàn)給圖片加水印,文中的示例代碼講解詳細,具有一定的借鑒價值,需要的可以參考一下
    2023-12-12
  • 在Golang中使用Redis的方法示例

    在Golang中使用Redis的方法示例

    這篇文章主要介紹了在Golang中使用Redis的方法示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-06-06
  • golang架構設計開閉原則手寫實現(xiàn)

    golang架構設計開閉原則手寫實現(xiàn)

    這篇文章主要為大家介紹了golang架構設計開閉原則手寫實例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-07-07
  • Golang哈希算法實現(xiàn)配置文件的監(jiān)控功能詳解

    Golang哈希算法實現(xiàn)配置文件的監(jiān)控功能詳解

    這篇文章主要介紹了Golang哈希算法實現(xiàn)配置文件的監(jiān)控功能,哈希和加密類似,唯一區(qū)別是哈希是單項的,即哈希后的數(shù)據無法解密,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習吧
    2023-03-03
  • Go庫text與template包使用示例詳解

    Go庫text與template包使用示例詳解

    這篇文章主要為大家介紹了Go庫text與template包使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-12-12
  • Go語言中字符串拼接的方法總結

    Go語言中字符串拼接的方法總結

    在Go語言中,我們可以使用+操作符、bytes.Buffer、strings.Builder等方法來拼接字符串,本文主要為大家介紹了這些常用方法的實現(xiàn)以及性能對比,感興趣的小伙伴可以了解下
    2023-11-11
  • 詳解Go語言如何解析帶注釋的json

    詳解Go語言如何解析帶注釋的json

    標準的json格式是不帶注釋,但是有時候為了方便理解json中各字段的含義,需要支持帶注釋的json,這篇文章主要介紹了Go語言解析帶注釋json的相關方法,希望對大家有所幫助
    2024-03-03
  • 深入了解Golang中的數(shù)據類型

    深入了解Golang中的數(shù)據類型

    在計算機編程中,數(shù)據類型是非常重要的一個概念。這篇文章將詳細介紹 Golang中的數(shù)據類型,包括基本類型、復合類型、引用類型以及自定義類型,希望對大家有所幫助
    2023-04-04
  • 詳解golang碎片整理之 fmt.Scan

    詳解golang碎片整理之 fmt.Scan

    本文介紹了從golang語言中fmt包從標準輸入獲取數(shù)據的Scan系列函數(shù)、從io.Reader中獲取數(shù)據的Fscan系列函數(shù)以及從字符串中獲取數(shù)據的Sscan系列函數(shù)的用法,感興趣的小伙伴們可以參考一下
    2019-05-05
  • go?doudou開發(fā)單體RESTful服務快速上手教程

    go?doudou開發(fā)單體RESTful服務快速上手教程

    這篇文章主要為大家介紹了go?doudou開發(fā)單體RESTful服務快速上手教程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-12-12

最新評論

博野县| 平果县| 大余县| 赤峰市| 弋阳县| 盐城市| 揭阳市| 临桂县| 呼和浩特市| 青岛市| 疏勒县| 多伦县| 德州市| 武胜县| 沾化县| 松阳县| 井冈山市| 邓州市| 修文县| 岳阳县| 介休市| 图们市| 舒兰市| 类乌齐县| 福海县| 利辛县| 黄骅市| 凤凰县| 龙口市| 剑河县| 高州市| 江永县| 阿克苏市| 沁阳市| 鸡东县| 宁明县| 广平县| 弋阳县| 许昌市| 泸水县| 文山县|