美文网首页
GIN-Web入门

GIN-Web入门

作者: 洛杉矶银河 | 来源:发表于2020-03-13 00:21 被阅读0次

    这是个小案例返回一个图书列表,用到了gin和gorm

    Go版本:1.13,Go modules

    目录结构

    ├── App
    │   ├── ServiceHelp.go
    │   └── services
    │       ├── BookEndpoint.go
    │       ├── BookService.go
    │       └── BookTransport.go
    ├── AppInit
    │   ├── Config.go
    │   └── DBInit.go
    ├── Models
    │   └── Books.go
    ├── gin.ini
    ├── gin.log
    ├── go.mod
    ├── go.sum
    └── main.go
    

    main.Go

    package main
    
    import (
        "github.com/gin-gonic/gin"
        "io"
        "os"
        "src/App"
        "src/App/services"
        . "src/AppInit"
    )
    func main()  {
    
        f, _ := os.Create("gin.log")
        gin.DefaultWriter = io.MultiWriter(f)
    
        router:=gin.Default()
    
        bookserviceListEndpoint := services.BookListEndPoint(&services.BookService{})
    
        bookListHandler:=App.RegisterHandler(bookserviceListEndpoint,
            services.CreateBookListRequest(),
            services.CreateBookListResponse(),
            )
        
    
        v1:=router.Group("v1")
        {
            v1.Handle(HTTP_METHOD_GET,"/prods", bookListHandler)
            
        }
    
    
        router.Run(SERVER_ADDRESS)
    
    }
    

    定义模型 Book.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"`
        BookPrice1 float64 `gorm:"column:book_price1;type:decimal"`
        BookPrice2 float64 `gorm:"column:book_price2;type:decimal"`
        BookAuthor string `gorm:"column:book_author;type:varchar(50)"`
        BookPress string `gorm:"column:book_press;type:varchar(50)"`
        BookDate string `gorm:"column:book_date;type:varchar(50)"`
        BookKind int `gorm:"column:book_kind;type:int"`
        BookKindStr string `gorm:"column:book_kind_str;type:varchar(20)"`
    }
    type BookList []*Books
    

    定义Handler函数

    package App
    
    import (
        "context"
        "fmt"
        "github.com/gin-gonic/gin"
    )
    //业务最终函数原型
    type Endpoint func(ctx context.Context,request interface{}) ( response interface{},err error)
    //怎么取参数
    type EndcodeRequestFunc func(*gin.Context)(interface{},error)
    
    //怎么处理业务结果
    type DecodeResponseFunc func(*gin.Context,interface{}) error
    
    
    func RegisterHandler(endpoint Endpoint,endcodeFunc EndcodeRequestFunc,decodeFunc DecodeResponseFunc) func(context *gin.Context) {
    
        return func(context *gin.Context) {
            defer func() {
                if r:=recover();r!=nil{
                    context.JSON(500,gin.H{"error:":fmt.Sprintf("fatal error:s%",r)})
                }
            }()
            //参数:=怎么取参数(context)
            //业务结果,error:=业务最终函数(context,参数)
            //
            //
            //怎么处理业务结果(业务结果)
    
            req,err:=endcodeFunc(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:":" response error"+err.Error()})
                return
            }
        }
    }
    

    定义BookEndpoint.go

     package services
    
    import (
        "context"
        "src/App"
        "src/Models"
    )
    
    type BookListRequest struct {
        Size int `form:"size" binding:"required,gt=0,max=200"`
    }
    
    
    type BookListResponse struct {
        Result *Models.BookList
    }
    
    
    func BookListEndPoint(book *BookService)App.Endpoint  {
        return func(ctx context.Context, request interface{}) (response interface{}, err error) {
            req:=request.(*BookListRequest)
            result,err:=book.LoadBookList(req)
            return &BookListResponse{Result:result},err
        }
    }
    

    BookService.go

    package services
    
    import (
        "fmt"
        "src/AppInit"
        "src/Models"
    )
    
    type BookService struct {
    
    }
    
    func (this *BookService)LoadBookList(req *BookListRequest)(*Models.BookList ,error) {
        prods:=&Models.BookList{}
        err:=AppInit.GetDB().Limit(req.Size).Order("book_id desc").Find(prods).Error
        if err!=nil{
            return nil,err
        }
        return prods,nil
    }
    

    BookTransport.go

    package services
    
    import (
        "fmt"
        "github.com/gin-gonic/gin"
        "src/App"
    )
    
    func CreateBookListRequest() App.EndcodeRequestFunc  {
        return func(context *gin.Context) (i interface{}, e error) {
            bReq:= &BookListRequest{}
            //err:=context.BindQuery(bReq)
            err:=context.ShouldBindQuery(bReq)
            fmt.Println(bReq)
            if err!=nil{
                return nil,err
            }
            return bReq,nil
        }
    }
    
    func CreateBookListResponse() App.DecodeResponseFunc{
        return func(context *gin.Context, i interface{}) error {
            res:= i.(*BookListResponse)
            context.JSON(200,res)
            return  nil
        }
    }
    

    初始化配置Config.go

    package AppInit
    
    import (
        "github.com/go-ini/ini"
        "log"
    )
    
    const (
        HTTP_METHOD_GET="GET"
    
    )
    
    var(
        SERVER_ADDRESS=":8080"
        MYSQL_DSN=""
        MYSQL_MAXIDLE=10
        MYSQL_MAXCONN=50
    )
    
    func init(){
        cfg,err:=ini.Load("gin.ini")
        if err!=nil{
            log.Fatal(" config err")
        }
        //muststring 带默认值
        SERVER_ADDRESS=cfg.Section("server").Key("port").MustString(":8080")
        //数据库连接字符串
        MYSQL_DSN=cfg.Section("mysql").Key("dsn").String()
        //最大空闲连接
        MYSQL_MAXIDLE=cfg.Section("mysql").Key("maxidle").MustInt(10)
        //最大连接数
        MYSQL_MAXCONN=cfg.Section("mysql").Key("maxconn").MustInt(50)
    
    }
    

    数据库

    package AppInit
    
    import (
        "fmt"
        "github.com/jinzhu/gorm"
        _ "github.com/jinzhu/gorm/dialects/mysql"
        "log"
    )
    
    var db *gorm.DB
    func init() {
        var err error
        db, err = gorm.Open("mysql",
            MYSQL_DSN)
        if err != nil {
            log.Fatal(err)
        }
        db.SingularTable(true)
        db.DB().SetMaxIdleConns(MYSQL_MAXIDLE)
        db.DB().SetMaxOpenConns(MYSQL_MAXCONN)
        fmt.Println("当前连接池",MYSQL_MAXCONN,MYSQL_MAXIDLE)
        db.LogMode(true)
    }
    func  GetDB() *gorm.DB {
        return db
    }
    

    配置文件gin.ini

    [server]
    address=":8080"
    
    [mysql]
    dsn="user:pwd@tcp(host:3306)/book?charset=utf8mb4&parseTime=True&loc=Local"
    maxidle=10
    maxconn=509
    

    数据表结构

     CREATE TABLE `books` (
       `book_id` int(11) NOT NULL AUTO_INCREMENT,
       `book_name` varchar(500) DEFAULT NULL COMMENT '图书名称',
       `book_intr` text COMMENT '图书简介',
       `book_price1` decimal(10,2) DEFAULT NULL COMMENT '图书价格1',
       `book_price2` decimal(10,2) DEFAULT NULL COMMENT '图书价格2',
       `book_author` varchar(50) DEFAULT NULL COMMENT '图书作者',
       `book_press` varchar(50) DEFAULT NULL COMMENT '出版社',
       `book_date` varchar(100) DEFAULT NULL COMMENT '出版时间',
       `book_kind_str` varchar(20) DEFAULT NULL COMMENT '分类名',
       `book_kind` int(11) DEFAULT NULL COMMENT '分类ID',
       `dd_id` int(11) DEFAULT NULL,
       PRIMARY KEY (`book_id`)
     ) ENGINE=InnoDB  DEFAULT CHARSET=utf8mb4;
    

    项目运行

    设置gopath
    项目根目录下go mod init ,go mod tidy
    go run main.go
    访问 localhost:8080/v1/prods
    数据库,数据表,测试数据自行添加
    

    相关文章

      网友评论

          本文标题:GIN-Web入门

          本文链接:https://www.haomeiwen.com/subject/jpwnjhtx.html