gin框架post路由的使用

freeshine發表於2018-10-27

gin_router_web

gin是簡單快速的golang框架,這篇文章主要是介紹gin的路由配置及使用(主要是post方法)

靜態資源配置

func setStaticFS(r *gin.Engine) {
	r.LoadHTMLGlob("views/*")
	r.StaticFS("/static", http.Dir("public/static"))
	r.StaticFS("/upload", http.Dir("upload"))
}
複製程式碼

func (engine *Engine) LoadHTMLGlob(pattern string)函式載入全域性模式的HTML檔案標識,並將結果與HTML渲染器相關聯。

func (group *RouterGroup) StaticFS(relativePath string, fs http.FileSystem) IRoutes 設定相對路徑的靜態資源

api

api路由分組

api := r.Group("/api")
{
	api.POST("/form_post", formPost)

	api.POST("/json_post", jsonPost)
	api.POST("/urlencoded_post", urlencodedPost)
	api.POST("/json_and_form_post", jsonAndFormPost)
	api.POST("/xml_post", xmlPost)
	api.POST("/file_upload", fileUpload)

	api.GET("/list", func(c *gin.Context) {
		message := c.Query("message")
		nick := c.DefaultQuery("nick", "anonymous")

		c.JSON(http.StatusOK, gin.H{
			"status":  "SUCCESS",
			"message": message,
			"nick":    nick,
		})
	})
}

複製程式碼

訊息的型別

常用請求HeadersContent-Type的型別有text/plaintext/htmlapplication/jsonapplication/x-www-form-urlencodedapplication/xmlmultipart/form-data等.

  • text/plain 純文字
  • text/html HTML文件
  • application/json json格式資料
  • application/x-www-form-urlencoded 使用HTTP的POST方法提交的表單
  • application/xml xml格式資料
  • application/form-data主要是用來上傳檔案

MIME

form 表單提交

gin 路由實現


api.POST("/form_post", formPost)

// 表單提交
func formPost(c *gin.Context) {

	message := c.PostForm("message")
	nick := c.DefaultPostForm("nick", "anonymous") // 沒有獲取到nick值時給一個預設值

	log.Println(message, nick)
	c.JSON(http.StatusOK, gin.H{
		"status":  "SUCCESS",
		"message": message,
		"nick":    nick,
	})
}

複製程式碼

html實現

<form method="post" action="/api/form_post">
	<input type="text" name="message">
	<input type="text" name="nick">
	<button type="submit">提交</button>
</form>
複製程式碼

post提交application/json型別資料

gin 路由實現


type User struct {
	Name    string `json:"name" form:"name"`
	Message string `json:"message" form:"message"`
	Nick    string `json:"nick" form:"nick"`
}

func jsonPost(c *gin.Context) {
	var user User

	c.BindJSON(&user)

	log.Println(user.Name, user.Message, user.Nick)

	c.JSON(http.StatusOK, gin.H{
		"status":  "SUCCESS",
		"name":    user.Name,
		"message": user.Message,
		"nick":    user.Nick,
	})
}

複製程式碼

js實現

$('.json').on('click', function() {
	axios({
  		method: 'post',
	  	url: '/api/json_post',
	  	headers: {
	  		'Content-Type': 'application/json'
	  	},
	  	data
	}).then(res => {
		console.log(res.data)
		$('.json-msg').text(`success  ${new Date()}`)
	})
})
複製程式碼

post提交application/x-www-form-urlencoded型別資料

gin實現

// application/x-www-form-urlencoded
func urlencodedPost(c *gin.Context) {

	name := c.Query("name")
	message := c.PostForm("message")
	nick := c.DefaultPostForm("nick", "1231412")

	log.Println(name, message, nick)
	c.JSON(http.StatusOK, gin.H{
		"status":  "SUCCESS",
		"name":    name,
		"message": message,
		"nick":    nick,
	})
}
複製程式碼

js實現

$('.urlencoded').on('click', function() {

	var data = {}
	var inputs = $('#form input')


	for (let i = 0; i < inputs.length; i ++) {
		data[$(inputs[i]).attr('name')] = $(inputs[i]).val()
	}

	axios({
 	 	method: 'post',
	  	url: '/api/urlencoded_post?name=shineshao',
	  	headers: {
	  		'Content-Type': 'application/x-www-form-urlencoded'
	  	},
	  	data: $.param(data)
	}).then(res => {
		console.log(res.data)
		$('.urlencoded-msg').text(`success  ${new Date()}`)
	})
})

複製程式碼

post 提交application/x-www-form-urlencodedapplication/json型別資料

gin

type User struct {
	Name    string `json:"name" form:"name"`
	Message string `json:"message" form:"message"`
	Nick    string `json:"nick" form:"nick"`
}

// application/json  application/x-www-form-urlencoded
func jsonAndFormPost(c *gin.Context) {
	var user User

	c.Bind(&user)

	log.Println(user.Name, user.Message, user.Nick)

	c.JSON(http.StatusOK, gin.H{
		"status":  "SUCCESS",
		"name":    user.Name,
		"message": user.Message,
		"nick":    user.Nick,
	})
}

複製程式碼

js 實現


$('.jsonandform').on('click', function() {
	var data = {}
	var inputs = $('#form input')

	for (let i = 0; i < inputs.length; i ++) {
		data[$(inputs[i]).attr('name')] = $(inputs[i]).val()
	}


	axios({
  		method: 'post',
	  	url: '/api/json_and_form_post',
	  	headers: {
	  		'Content-Type': 'application/json'
	  	},
	  	data
	}).then(res => {
		console.log(res.data)
		$('.jsonandform-msg').text(`success application/json data,  ${new Date()}`)
	})
})

$('.jsonandform2').on('click', function() {
	var data = {}
	var inputs = $('#form input')

	for (let i = 0; i < inputs.length; i ++) {
		data[$(inputs[i]).attr('name')] = $(inputs[i]).val()
	}


	axios({
  		method: 'post',
	  	url: '/api/json_and_form_post',
	  	headers: {
	  		'Content-Type': 'application/x-www-form-urlencoded'
	  	},
	  	data:$.param(data)
	}).then(res => {
		console.log(res.data)
		$('.jsonandform-msg').text(`success application/x-www-form-urlencoded data${new Date()}`)
	})
})

複製程式碼

post提交application/xml型別資料(application/xml)

gin 實現

type User struct {
	Name    string `json:"name" form:"name" xml:"name"`
	Message string `json:"message" form:"message" xml:"message"`
	Nick    string `json:"nick" form:"nick" xml:"nick"`
}

func xmlPost(c *gin.Context) {
	var user User

	c.Bind(&user)

	log.Println(user.Name, user.Message, user.Nick)

	c.JSON(http.StatusOK, gin.H{
		"status":  "SUCCESS",
		"name":    user.Name,
		"message": user.Message,
		"nick":    user.Nick,
	})
}

複製程式碼

js 實現

$('.xml_post').on('click', function() {
	var data = {}
	var inputs = $('#form input')

	for (let i = 0; i < inputs.length; i ++) {
		data[$(inputs[i]).attr('name')] = $(inputs[i]).val()
	}

	axios({
		method: 'post',
		url: '/api/xml_post',
		headers: {
			"Content-Type": 'application/xml'
		},
		data: `<xml><name>${data.name}</name><message>${data.message}</message><nick>${data.nick}</nick></xml>`
	})
})

複製程式碼

post提交multipart/form-data型別資料(multipart/form-data)

gin實現檔案上傳

func fileUpload(c *gin.Context) {

	filesUrl := make([]string, 0)

	form, err := c.MultipartForm()

	if err != nil {
		log.Println("postMultipleFile error: %s")
	}

	files := form.File["file"]

	_, err = os.Stat("upload")

	if err != nil {
		os.Mkdir("upload", os.ModePerm)
	}

	for _, file := range files {
		log.Println(file.Filename)

		// Upload the file to specific dst.
		if err = c.SaveUploadedFile(file, "upload/"+file.Filename); err != nil {
			log.Println("SaveUploadedFile error: %s")

			return
		}
		filesUrl = append(filesUrl, "upload/"+file.Filename)
	}

	c.JSON(http.StatusOK, gin.H{
		"state": "SUCCESS",
		"url":   strings.Join(filesUrl, ";"),
	})
}
複製程式碼

html實現

<div>
	<form id="multipleForm">
		<input type="file" name="file" id='file' multiple="multiple" accept="image/*">
	</form>
	<button class="file_upload">上傳檔案</button>
</div>
複製程式碼

js實現

$('.file_upload').on('click', function () {

	// 單個檔案上傳
	// var fd = new FormData()
	// var file = document.getElementById('file')
	// fd.append('file', file.files[0])

	axios({
  		method: 'post',
	  	url: '/api/file_upload',
	  	headers: {
	  		'Content-Type': 'application/form-data'
	  	},
	  	// data:fd
	  	data: new FormData($('#multipleForm')[0])

	}).then(res => {
		console.log(res.data)
		const urls = res.data.url.split(';')
		let imgHtml = '';

		for(let i = 0; i < urls.length; i ++) {
			imgHtml += `<img style="width: 200px" src="/${urls[i]}" />`
		}

		$('.file_upload-msg').html(`<div>success ${new Date()} 檔案地址/${res.data.url} ${imgHtml}</div>`)
	})
})
複製程式碼

官方檔案上傳demo

我的demo

相關文章