zoukankan      html  css  js  c++  java
  • golang gin 返回json

    package main
    
    import (
    	"github.com/gin-gonic/gin"
    	"net/http"
    )
    
    type UserInfo struct {
    	Message string
    	Name    string
    	Age     int
    }
    
    type Student struct {
    	Name string `json:"name"` // 序列化 体现在输出的的时候 就变成小写了
    	Age  int    `json:"age"`
    }
    
    func main() {
    	r := gin.Default()
    	r.GET("/json", func(c *gin.Context) {
    		//方法1 map
    
    		data := map[string]interface{}{
    			"message": "hello",
    			"name":    "stefan",
    			"age":     20,
    		}
    
    		c.JSON(http.StatusOK, data)
    
    	})
    
    	r.GET("/anotherjson", func(c *gin.Context) {
    		//方法二 结构体
    		data := &UserInfo{
    			Message: "wahahah",
    			Name:    "stefan",
    			Age:     22,
    		}
    
    		c.JSON(http.StatusOK, data)
    
    	})
    
    	// json序列化
    	r.GET("/test", func(c *gin.Context) {
    		data := &Student{
    			Name: "xiaoming",
    			Age:  23,
    		}
    		c.JSON(http.StatusOK, data)
    	})
    
    	/* 输出
    	{"name":"xiaoming","age":23}
    	*/
    
    	r.Run(":9999")
    }
    

      

  • 相关阅读:
    【转载】Linux 内核启动时间分析
    hackbench
    c用户组函数
    c环境变量操作函数
    c网络接口套接字函数
    c信号处理函数
    c进程操作函数
    c文件内容操作函数
    c文件操作
    c数据结构和算法
  • 原文地址:https://www.cnblogs.com/zexin88/p/14439620.html
Copyright © 2011-2022 走看看