天天看點

Go web架構建構三層架構

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
        }

    }
}