go从0到1项目实战体系三十一:演示案例代码优化

发布时间:2023年12月25日

(1). BsyErp\Contract\main.go:

func main () {
	{
		bookResponse := Services.CreateBookResponse()
		bookServer := &Services.BookService{}
		bookListHandler := Lib.RegisterHandler(
			Services.CreateBookListRequest(),
			Services.BookListEndPoint(bookServer), // 将公共的提到上面去
			bookResponse,
		)
		bookDetailHandler := Lib.RegisterHandler(
			Services.CreateBookDetailRequest(),
			Services.BookDetailEndPoint(bookServer),
			bookResponse,
		)
    	// 获取book列表
		v1.Handle(Init.HTTP_METHOD_GET, "/books", bookListHandler)
    	// 获取book详情
		v1.Handle(Init.HTTP_METHOD_GET, "/book/:id", bookDetailHandler)
	}
	router.Run(Init.SERVER_ADDRESS)
}:. 下面(6)中如果Response方法优化了,这里可以优化为:
    bookResponse := Services.CreateBookResponse(),再将两个Response方法用变量替换.

(3). bookModel(BsyErp\Contract\Models\Books.go):

package Models
// 单实体
type Books struct{
	BookID int `gorm:"column:book_id;AUTO_INCREMENT;PRIMARY_KEY"`
	BookName string `gorm:"column:book_name;type:varchar(50)"`
	BookIntr string `gorm:"column:book_intr;type:text"`
	BookPrice float64 `gorm:"column:book_price;type:decimal"`
	BookKind int `gorm:"column:book_kind;type:int"`
}
// 列表
type BooksList []*Books

注:. 属性名有规范,字段名就不一定有规范.

(1). BsyErp\Contract\App\Services\BookEndpoint.go:

type BookListResponse struct { // 响应参数
	Result *Models.BooksList `json:"ResultData"`
}
type BookDetailResponse struct {
	Result *Models.Books `json:"ResultData"`
}:. 上面两个response如果都是返回{Result: xxx},可以优化:
    type BookResponse struct {
      Result interface{} `json:"ResultData"`
    }

(5). BsyErp\Contract\App\Services\BookService.go:

package Services
import (
	"Contract.bsybx.com/App/Lib"
	"Contract.bsybx.com/Models"
	"context"
)
// v1/books?page=1&size=1
type BookListRequest struct {
	Page int  `form:"page"`
	Size int `form:"size"`
}
type BookListResponse struct {
	Result *Models.BooksList `json:"ResultData"`
}
// v1/book/12
type BookDetailRequest struct {
	// max可以做预估判断
	BookID int `uri:"id" binding:"required,gt=0,max=1000000"`
}
type BookDetailResponse struct {
	Result *Models.Books `json:"ResultData"`
}
func BookListEndPoint(book *BookService)  Lib.Endpoint {
   return func(ctx context.Context, request interface{}) (response interface{}, err error) {
	   req := request.(*BookListRequest)
	   return &BookListResponse{Result:book.BookList(req)}, nil
   }
}
func BookDetailEndPoint(book *BookService) Lib.Endpoint {
	return func(ctx context.Context, request interface{}) (interface{}, error) {
		req := request.(*BookDetailRequest)
		return &BookDetailResponse{Result:book.BookDetail(req)}, nil
	}
}

(6). BsyErp\Contract\App\Services\BookTransport.go:

package Services
import (
	"Contract.bsybx.com/App/Lib"
	"fmt"
	"github.com/gin-gonic/gin"
)
func CreateBookListRequest() Lib.EncodeRequestFunc {
	return func(context *gin.Context) (i interface{}, e error) {
		req := &BookListRequest{}
		err := context.BindQuery(req)   // 和框架有关系了,获取一个get参数,并且绑定到BookListRequest上,会去寻找这个BookListRequest struct中是否有size。如果有绑定,否则出错。
		fmt.Println(req)
		if err != nil{
			return nil, err
		}
		return req, nil
	}
}
func CreateBookListResponse() Lib.DecodeResponseFunc  {
	return func(context *gin.Context, i interface{}) error {
		res := i.(*BookListResponse)       // 取出BookListResponse,后再断言
		context.JSON(200, res)
		return nil
	}
}
func CreateBookDetailRequest() Lib.EncodeRequestFunc {
	return func(context *gin.Context) (interface{}, error) {
		req := &BookDetailRequest{}
		// 优化把err合并为一句
		if err := context.ShouldBindUri(req); err != nil {
			return nil, err
		}
		return req, nil
	}
}
func CreateBookDetailResponse() Lib.DecodeResponseFunc {
	return func(context *gin.Context, i interface{}) error {
		res := i.(*BookDetailResponse)
		context.JSON(200, res)
		return nil
	}
}:. 两个Response都是差不多逻辑,可以优化为:
   func CreateBookResponse() Lib.DecodeResponseFunc {
     return func(context *gin.Context, res interface{}) error {
       context.JSON(200, res)
       return nil
     }
   }

(7). 请求访问:

①. 列表:
   GET http://localhost/v1/books?page=1&size=1

②. 详情:
   GET http://localhost/v1/book/200
文章来源:https://blog.csdn.net/m0_68635815/article/details/135198296
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。