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 oracle命令行窗口命令上下翻阅
    oracle 转移表空间
    perl字符集处理
    Perl解析JSON数据精解
    处理外壳PROC
    FileIsExe
    写壳前的设计
    SEH结构化异常处理03
    SEH结构化异常处理02
    博客首记
  • 原文地址:https://www.cnblogs.com/zexin88/p/14439620.html
Copyright © 2011-2022 走看看