gin+swagger+restful环境搭建

Gin 框架的使用

可以参考官网安装gin
https://github.com/gin-gonic/gin

使用go mod,若遇到golang.org包无法下载的问题请参考:https://blog.csdn.net/wz122330/article/details/89493467

[wangzheng@wangzheng-centos myweb]$ cat main.go 
package main

import (
    "gopkg.in/gin-gonic/gin.v1"
    "net/http"
)

func main(){
    router := gin.Default()
    router.GET("/", func(c *gin.Context) {
        c.String(http.StatusOK, "Hello World")
    })
    router.Run(":8000")
}
[wangzheng@wangzheng-centos myweb]$

使用go mod管理项目依赖包

go mod init生成go.mod文件

[wangzheng@wangzheng-centos myweb]$ go mod init
go: modules disabled inside GOPATH/src by GO111MODULE=auto; see 'go help modules'
[wangzheng@wangzheng-centos myweb]$ export GO111MODULE=on
[wangzheng@wangzheng-centos myweb]$ go mod init
go: creating new go.mod: module ginLearn/myweb
[wangzheng@wangzheng-centos myweb]$ ls
controller  go.mod  main.go  model  service
[wangzheng@wangzheng-centos myweb]$ cat go.mod 
module ginLearn/myweb

go 1.12
[wangzheng@wangzheng-centos myweb]$ 

执行go test

[wangzheng@wangzheng-centos myweb]$ go test
go: finding github.com/gin-contrib/sse latest
go: finding github.com/gin-gonic/gin/binding latest
go: finding github.com/gin-gonic/gin/render latest
go: finding github.com/gin-gonic/gin/json latest
go: golang.org/x/sys@v0.0.0-20190222072716-a9d3bda3a223: unrecognized import path "golang.org/x/sys" (https fetch: Get https://golang.org/x/sys?go-get=1: dial tcp 216.239.37.1:443: i/o timeout)
go: error loading module requirements

replace替换golang.org为github上的代码

[wangzheng@wangzheng-centos myweb]$ go mod edit -replace=golang.org/x/sys@v0.0.0-20190222072716-a9d3bda3a223=github.com/golang/sys@latest
[wangzheng@wangzheng-centos myweb]$ cat go.mod 
module ginLearn/myweb

go 1.12

replace golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223 => github.com/golang/sys latest
[wangzheng@wangzheng-centos myweb]$ go test
go: finding github.com/golang/sys latest
go: finding github.com/gin-contrib/sse latest
go: finding github.com/gin-gonic/gin/binding latest
go: finding github.com/gin-gonic/gin/render latest
go: finding github.com/gin-gonic/gin/json latest
go: downloading github.com/golang/sys v0.0.0-20190424175732-18eb32c0e2f0
go: finding github.com/ugorji/go/codec latest
go: extracting github.com/golang/sys v0.0.0-20190424175732-18eb32c0e2f0
go: finding github.com/golang/protobuf/proto latest
?   	ginLearn/myweb	[no test files]

go build生成可执行程序

[wangzheng@wangzheng-centos myweb]$ go build
[wangzheng@wangzheng-centos myweb]$ ls
controller  go.mod  go.sum  main.go  model  myweb  service
[wangzheng@wangzheng-centos myweb]$ ./myweb 
[GIN-debug] [WARNING] Now Gin requires Go 1.6 or later and Go 1.7 will be required soon.

[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.

[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
 - using env:	export GIN_MODE=release
 - using code:	gin.SetMode(gin.ReleaseMode)

[GIN-debug] GET    /                         --> main.main.func1 (3 handlers)
[GIN-debug] Listening and serving HTTP on :8000

访问8000端口

在这里插入图片描述

Gin 框架集成swagger

可参考官网安装https://github.com/swaggo/gin-swagger

安装 swag

[wangzheng@wangzheng-centos myweb]$ go get github.com/swaggo/swag/cmd/swag

如有问题请参考:https://blog.csdn.net/wz122330/article/details/89510092

在go 项目中(包含main.go)的目录,使用swag init命令生成相关文件。

[wangzheng@wangzheng-centos myweb]$ swag init
2019/04/24 22:32:35 Generate swagger docs....
2019/04/24 22:32:35 Generate general API Info
2019/04/24 22:32:35 create docs.go at  docs/docs.go
2019/04/24 22:32:35 create swagger.json at  docs/swagger.json
2019/04/24 22:32:35 create swagger.yaml at  docs/swagger.yaml
[wangzheng@wangzheng-centos myweb]$ ls docs/
docs.go  swagger.json  swagger.yaml
[wangzheng@wangzheng-centos myweb]$ 

安装 gin-swagger

[wangzheng@wangzheng-centos src]$ go get -u github.com/swaggo/gin-swagger
[wangzheng@wangzheng-centos src]$ go get -u github.com/swaggo/gin-swagger/swaggerFiles
package main

import (
    _ "ginLearn/myweb/docs"
    router "ginLearn/myweb/routers"
    "github.com/swaggo/gin-swagger"
    "github.com/swaggo/gin-swagger/swaggerFiles"
)

// @title Swagger Example API
// @version 1.0
// @description This is a sample server Petstore server.
// @termsOfService http://swagger.io/terms/

// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io

// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html

// @host 192.168.0.5:8080
func main() {
    router:=router.InitRouter()

    // use ginSwagger middleware to 
    router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

    router.Run()
}
package routers

import (
  "github.com/gin-gonic/gin"
  . "ginLearn/myweb/controllers" //api部分
 )

func InitRouter() *gin.Engine{
    router := gin.Default()
    //Hello World
    router.GET("/hello", GetDataList)

    router.POST("/user/add", InsertUser)

    return router
}
package controllers

import (
    "net/http"
    "github.com/gin-gonic/gin"
    db "ginLearn/myweb/db"
    user "ginLearn/myweb/models"
    "strconv"
)


// @列表页面数据
// @Description get data
// @Accept  json
// @Produce json
// @Success 200 {string} string "hello"
// @Router /hello/ [get]
func GetDataList(c *gin.Context) {

    //返回结果
    c.JSON(http.StatusOK, gin.H{
        "data": "hello",
    })
}

// @增加用户
// @Description add user
// @Accept  json
// @Produce json
// @Param Id query int false "int valid"
// @Param Name query string false "string valid"
// @Param Age query int false "int valid"
// @Router /user/add [post]
func InsertUser(c *gin.Context) {
    id, _ := strconv.Atoi(c.Request.FormValue("Id"))
    age, _ := strconv.Atoi(c.Request.FormValue("Age"))
    u := user.User{Id : id, Name : c.Request.FormValue("Name"), Age : age}
    db.InsertUser(&u)
}
package db

import (
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/mysql"
     "log"
     user "ginLearn/myweb/models"
     "fmt"
)

func NewConn() *gorm.DB {
    db, err := gorm.Open("mysql", "root:111111@tcp(192.168.0.69:12345)/test?parseTime=true")
//    defer db.Close()

    if err != nil {
        log.Fatal(err.Error())
    }
    return db
}

func InsertUser(u *user.User) {
    db := NewConn()
    fmt.Println("开始创建...")
    if !db.HasTable(&user.User{}) {
        if err := db.Set("gorm:table_options", "ENGINE=InnoDB DEFAULT CHARSET=utf8").CreateTable(&user.User{}).Error; err != nil {
            panic(err)
        }
    }
    fmt.Println("创建完了")
    fmt.Println("插入用户...")
    db.Create(u)
    defer db.Close()
}
package models

type User struct {
   Id   int    `gorm:"primary_key"`
   Name string `gorm:"type:varchar(256);not null;"`
   Age  int
}

执行go build,若出现错误,则使用go mod edit -replace进行替换。

测试

[wangzheng@wangzheng-centos myweb]$ go run main.go 
[GIN-debug] [WARNING] Now Gin requires Go 1.6 or later and Go 1.7 will be required soon.

[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.

[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
 - using env:	export GIN_MODE=release
 - using code:	gin.SetMode(gin.ReleaseMode)

[GIN-debug] GET    /hello                    --> ginLearn/myweb/controllers.GetDataList (3 handlers)
[GIN-debug] POST   /user/add                 --> ginLearn/myweb/controllers.InsertUser (3 handlers)
[GIN-debug] GET    /swagger/*any             --> github.com/swaggo/gin-swagger.WrapHandler.func1 (3 handlers)
[GIN-debug] Environment variable PORT is undefined. Using port :8080 by default
[GIN-debug] Listening and serving HTTP on :8080
[GIN] 2019/04/25 - 05:45:13 | 200 |     423.949µs |     192.168.0.8 | GET      /swagger/index.html
[GIN] 2019/04/25 - 05:45:13 | 200 |    4.913887ms |     192.168.0.8 | GET      /swagger/swagger-ui.css
[GIN] 2019/04/25 - 05:45:13 | 200 |   10.532505ms |     192.168.0.8 | GET      /swagger/swagger-ui-standalone-preset.js
[GIN] 2019/04/25 - 05:45:13 | 200 |     28.1525ms |     192.168.0.8 | GET      /swagger/swagger-ui-bundle.js
[GIN] 2019/04/25 - 05:45:13 | 200 |     230.546µs |     192.168.0.8 | GET      /swagger/doc.json
[GIN] 2019/04/25 - 05:45:13 | 200 |      55.106µs |     192.168.0.8 | GET      /swagger/favicon-32x32.png
开始创建...
创建完了
插入用户...
[GIN] 2019/04/25 - 05:45:24 | 200 |   25.103268ms |     192.168.0.8 | POST     /user/add?Id=3&Name=sd&Age=22

在这里插入图片描述
在这里插入图片描述
项目代码:https://github.com/wz18567908/ginLearn/tree/master/myweb

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值