1快速开始

5 篇文章 0 订阅

快速开始 

package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func main() {
	//1.创建路由
	r := gin.Default()
	//2.指定路由规则,执行的函数
	r.GET("/ping", func(c *gin.Context) {
		c.String(http.StatusOK,"hello world")
	})
	//3.监听端口,默认是8080
	r.Run(":8000")// listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}

路由

API参数

	r.GET("/user/:name", func(c *gin.Context) {
		name := c.Param("name")
		c.String(http.StatusOK, "Hello %s", name)
	})

测试:http://localhost:8000/user/fsl

url参数

	r.GET("/welcome", func(c *gin.Context) {
		//DefaultQuery没有值的时候取第二个参数
		firstname := c.DefaultQuery("firstname", "Guest")
		//根据key获取值
		lastname := c.Query("lastname") // shortcut for c.Request.URL.Query().Get("lastname")

		c.String(http.StatusOK, "Hello %s %s", firstname, lastname)
	})

表单参数

	r.POST("/form_post", func(c *gin.Context) {
		message := c.PostForm("message")
		nick := c.DefaultPostForm("nick", "anonymous")

		c.JSON(200, gin.H{
			"status":  "posted",
			"message": message,
			"nick":    nick,
		})
	})

x-www-form-urlencoded

单文件上传

    // Set a lower memory limit for multipart forms (default is 32 MiB)
	// router.MaxMultipartMemory = 8 << 20  // 8 MiB
	r.POST("/upload", func(c *gin.Context) {
		// single file
		file, _ := c.FormFile("file")
		log.Println(file.Filename)

		// Upload the file to specific dst.
		// c.SaveUploadedFile(file, dst)

		c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))
	})

多文件上传

	r.POST("/upload", func(c *gin.Context) {
		// Multipart form
		form, _ := c.MultipartForm()
		files := form.File["files"]
		for _, file := range files {
			log.Println(file.Filename)
			// Upload the file to specific dst.
			if err:=c.SaveUploadedFile(file,file.Filename);err!=nil{
				c.String(http.StatusBadRequest,fmt.Sprintf("uplod err %s",err.Error()))
				return
			}
		}
		c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files)))
	})

路由组

	// Simple group: v1
	v1 := r.Group("/v1")
	{
		v1.POST("/login", loginEndpoint)
		v1.POST("/submit", submitEndpoint)
		v1.POST("/read", readEndpoint)
	}

	// Simple group: v2
	v2 := r.Group("/v2")
	{
		v2.POST("/login", loginEndpoint)
		v2.POST("/submit", submitEndpoint)
		v2.POST("/read", readEndpoint)
	}
	//3.监听端口,默认是8080
	r.Run(":8000") // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")

}
func loginEndpoint(c *gin.Context){
	fmt.Println("登录")
	c.String(http.StatusOK,"登录")
}
func submitEndpoint(c *gin.Context){
	c.String(http.StatusOK,"提交")
}
func readEndpoint(c *gin.Context){
	c.String(http.StatusOK,"读取")
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值