go-api-framework
go基於gin三層架構web框架
三層架構模式
func RegisterHandler(業務最終函數,怎么取參數,怎么處理業務結果) func(context *gin.Context) {
xxxxxoooo
}
這個就是最終的結果
unc RegisterHandler(業務最終函數,怎么取參數,怎么處理業務結果) func(context *gin.Context) { 參數:=怎么取參數() 業務結果:=業務最終函數(參數) 怎么處理業務結果(業務結果) }
首先要定義原型
業務最終函數
type Endpoint func(ctx context.Context,request interface{}) (response interface{}, err error)
一律使用interface{} 。這樣可以處理不同的類型
怎么取參數 :
type EncodeRequestFunc func(*gin.Context, interface{}) (interface{}, error)
怎么處理響應:
type DecodeResponseFunc func(*gin.Context, interface{}) error
然后寫成這樣
func RegisterHandler(endpoint Endpoint,encodeFunc EncodeRequestFunc,decodeFunc DecodeResponseFunc) func(context *gin.Context){ return func(context *gin.Context) { req,err:=encodeFunc(context,nil) if err!=nil{ context.JSON(500,gin.H{"error":"param err"+err.Error()}) return } res,err:=endpoint(context,req) if err!=nil{ context.JSON(500,gin.H{"error":err}) }else{ err:=decodeFunc(context,res) if err!=nil{ context.JSON(500,gin.H{"error":err}) } } } }
最終核心結構:
package App import ( "context" "fmt" "github.com/gin-gonic/gin" ) type Middleware func(Endpoint) Endpoint //業務最終函數原型 type Endpoint func(ctx context.Context,request interface{}) (response interface{}, err error) //怎么取參數 type EncodeRequestFunc func(*gin.Context) (interface{}, error) //怎么處理業務結果 type DecodeResponseFunc func(*gin.Context, interface{}) error func RegisterHandler(endpoint Endpoint,encodeFunc EncodeRequestFunc, decodeFunc DecodeResponseFunc) func(context *gin.Context){ return func(context *gin.Context) { defer func() { if r:=recover();r!=nil{ fmt.Fprintln(gin.DefaultWriter,fmt.Sprintf("fatal error:%s",r)) context.JSON(500,gin.H{"error":fmt.Sprintf("fatal error:%s",r)}) return } }() //參數:=怎么取參數(context) //業務結果,error:=業務最終函數(context,參數) // // //怎么處理業務結果(業務結果) req,err:=encodeFunc(context) //獲取參數 if err!=nil{ context.JSON(400,gin.H{"error":"param error:"+err.Error()}) return } rsp,err:=endpoint(context,req) //執行業務過程 if err!=nil{ fmt.Fprintln(gin.DefaultWriter,"response error:",err) context.JSON(400,gin.H{"error":"response error:"+err.Error()}) return } err=decodeFunc(context,rsp) //處理 業務執行 結果 if err!=nil{ context.JSON(500,gin.H{"error":"server error:"+err.Error()}) return } } }
github地址:https://github.com/sunlongv520/go-api-framework