gin學習

sunny0901發表於2021-12-30
package main

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

type Article struct {
    Title   string `json:"title"`
    Desc    string `json:"desc"`
    Content string `json:"content"`
}

func main() {

    r := gin.Default()



    //配置模板的路勁
    r.LoadHTMLGlob("templates/*")


    //定義普通路由GET
    r.GET("/news", func(c *gin.Context) {

        c.HTML(http.StatusOK,"news.html",gin.H{
            "title":"我是後臺皮膚",

        })
        c.String(200, "我是新聞頁面")
    })


    r.GET("/goods", func(c *gin.Context) {

        c.HTML(http.StatusOK,"goods.html",gin.H{
            "title":"我是後臺商品變數",

        })
        c.String(200, "我是新聞頁面")
    })




    //返回map
    r.GET("/json", func(c *gin.Context) {
        c.JSON(200, map[string]interface{}{
            "success": true,
            "message": "你好gin",
        })
    })
    //返回map
    r.GET("/json2", func(c *gin.Context) {
        c.JSON(200, map[string]interface{}{
            "success": true,
            "message": "你好gin",
        })
    })

    //返回Article結構體
    r.GET("/json3", func(c *gin.Context) {
        a := &Article{
            Title:   "笑傲江湖",
            Desc:    "這是一部武俠小說",
            Content: "令狐沖獨霸武林",
        }
        c.JSON(200, a)
    })

    //定義普通路由
    r.GET("/ping", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "success": true,
            "message": "pong01",
        })
    })


    //定義普通路由POST
    r.POST("/add", func(c *gin.Context) {
        c.String(200, "我是postman請求")
    })

    //響應jsonp請求
    r.GET("/jsonp", func(c *gin.Context) {
        a := &Article{
            Title:   "笑傲江湖",
            Desc:    "這是一部武俠小說",
            Content: "令狐沖獨霸武林",
        }
        c.JSONP(200, a)
    })

    //返回XML資料

    r.GET("/xml", func(c *gin.Context) {

        c.XML(http.StatusOK, gin.H{
            "success": true,
            "message": "你好gin",
        })
    })

    r.Run()
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章