gin多數據格式返回結果


1.返回byte和string類型

context.Writer.Write([]byte("fullpath="+fullpath))
context.Writer.WriteString("fullpath"+fullpath)

2.返回JSON

package main

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

func main(){
	engine := gin.Default()
	engine.GET("/hello", func(context *gin.Context) {
		fullpath := context.FullPath()
		context.Writer.Write([]byte("fullpath="+fullpath))
		context.Writer.WriteString("fullpath"+fullpath)
	})
	//map類型的
	engine.GET("/hellojson", func(context *gin.Context) {
		fullpath := context.FullPath()
		context.JSON(200, map[string]interface{}{
			"code":200,
			"msg":"OK",
			"data":fullpath,
		})
	})
	//結構體類型
	engine.GET("/hellostruct", func(context *gin.Context) {
		fullpath := context.FullPath()
		resp := Response{
			Code: 200,
			Msg: "OK",
			Data: fullpath,
		}
		context.JSON(200,&resp)
	})
	//模板渲染
	engine.LoadHTMLGlob("./gin01/html/*")//設置html訪問路徑
	engine.Static("/img","./img") //第一個參數是前端訪問的  第二個參數是本地的
	engine.GET("/helloshtml", func(context *gin.Context) {
		fullpath := context.FullPath()
		context.HTML(http.StatusOK,"index.html",gin.H{
			"fullpath":fullpath,
		}) //傳值到html  頁面{{.fullpath}}渲染
	})
	engine.Run()
}

type Response struct {
	Code int
	Msg string
	Data interface{}
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM