【GO】 4.Golang gin Web框架的一个示例

  • 1.安装github.com/gin-gonic/gin

输入命令go get github.com/gin-gonic/gin 进行安装

当长时间没有反应的时候我就知道又有一些包被墙了,这次还是两个。然而一点也不慌,还是手动去github上下载缺失的包之后

运行:install $(GOPATH)\src\github.com/gin-gonic/gin  手动安装

  • 2.一个简单的服务器示例

package main

import (
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

type User struct {
	ID          int64
	Name        string
	Age         int
	CreatedTime time.Time
	UpdatedTime time.Time
	IsDeleted   bool
}

func main() {
    //初始化引擎
	r := gin.Default()

    //简单的Get请求
	r.GET("/ping", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "pong",
		})
	})

    //GET请求通过name获取参数  /user/test
	r.GET("/user/:name", func(c *gin.Context) {
		name := c.Param("name")
		c.String(http.StatusOK, "Hello %s", name)
	})

    //GET请求通过正常的URL获取参数  /getuser?id=2
	r.GET("/getuser", func(c *gin.Context) {
		rid := c.DefaultQuery("id", "1")
		id, _ := strconv.ParseInt(rid, 10, 64)
		user := User{ID: id, Age: 32, CreatedTime: time.Now(), UpdatedTime: time.Now(), IsDeleted: true}
		c.JSON(http.StatusOK, user)
	})

    //POST请求通过绑定获取对象
	r.POST("/adduser", func(c *gin.Context) {
		var user User
		err := c.ShouldBind(&user)
		if err == nil {
			c.JSON(http.StatusOK, user)
		} else {
			c.String(http.StatusBadRequest, "请求参数错误", err)
		}
	})

	r.Run(":9002") // listen and serve on 0.0.0.0:8080
}
  • 3.curl命令测试结果如下:

D:\>curl http://localhost:9002/ping
{"message":"pong"}
D:\>curl http://localhost:9002/user/test
Hello test
D:\>curl http://localhost:9002/getuser?id=33
{"ID":33,"Name":"","Age":32,"CreatedTime":"2019-04-18T19:31:44.3296375+08:00","UpdatedTime":"2019-04-18T19:31:44.3296375+08:00","IsDeleted":true}
D:\>curl -v --form ID=222 --form Name=dylan --form Age=3 --form IsDeleted=true --form CreatedTime=2015-09-15T14:00:12-00:00  http://localhost:9002/adduser
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 9002 (#0)
> POST /adduser HTTP/1.1
> Host: localhost:9002
> User-Agent: curl/7.55.1
> Accept: */*
> Content-Length: 558
> Expect: 100-continue
> Content-Type: multipart/form-data; boundary=------------------------db63a503440e7f15
>
< HTTP/1.1 100 Continue
< HTTP/1.1 200 OK
< Content-Type: application/json; charset=utf-8
< Date: Thu, 18 Apr 2019 11:31:59 GMT
< Content-Length: 124
<
{"ID":222,"Name":"dylan","Age":3,"CreatedTime":"2015-09-15T14:00:12Z","UpdatedTime":"0001-01-01T00:00:00Z","IsDeleted":true}* Connection #0 to host localhost left intact

更多gin框架细节参考github地址:https://github.com/gin-gonic/gin

参考资料:https://juejin.cn/post/6844903998869209095

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值