美文网首页
Go Gin 使用范例

Go Gin 使用范例

作者: 萧何爱英语 | 来源:发表于2019-01-17 10:46 被阅读0次

server.go(来源:https://github.com/gin-gonic/gin#quick-starthttps://raw.githubusercontent.com/gin-gonic/examples/master/basic/main.go

package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
)

var db = make(map[string]string)

func setupRouter() *gin.Engine {
    // Disable Console Color
    // gin.DisableConsoleColor()
    r := gin.Default()

    // Ping test
    r.GET("/ping", func(c *gin.Context) {
        c.String(http.StatusOK, "pong")
    })

    // Get user value
    r.GET("/user/:name", func(c *gin.Context) {
        user := c.Params.ByName("name")
        value, ok := db[user]
        if ok {
            c.JSON(http.StatusOK, gin.H{"user": user, "value": value})
        } else {
            c.JSON(http.StatusOK, gin.H{"user": user, "status": "no value"})
        }
    })

    // Authorized group (uses gin.BasicAuth() middleware)
    // Same than:
    // authorized := r.Group("/")
    // authorized.Use(gin.BasicAuth(gin.Credentials{
    //    "foo":  "bar",
    //    "manu": "123",
    //}))
    authorized := r.Group("/", gin.BasicAuth(gin.Accounts{
        "foo":  "bar", // user:foo password:bar
        "manu": "123", // user:manu password:123
    }))

    authorized.POST("admin", func(c *gin.Context) {
        user := c.MustGet(gin.AuthUserKey).(string)

        // Parse JSON
        var json struct {
            Value string `json:"value" binding:"required"`
        }

        if c.Bind(&json) == nil {
            db[user] = json.Value
            c.JSON(http.StatusOK, gin.H{"status": "ok"})
        }
    })

    return r
}

func main() {
    r := setupRouter()
    // Listen and Server in 0.0.0.0:8080
    r.Run(":8080")
}

client.go(来源:自己写)

package main

import (
    "encoding/base64"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "strings"
)

func main() {
    var jsonData struct {
        Value string `json:"value"`
    }
    jsonData.Value = "1"

    data, _ := json.Marshal(jsonData)
    httpPost("http://localhost:8080/admin", "foo", "bar", string(data))
}

func httpPost(url, user, password, data string) {
    req, err := http.NewRequest("POST", url, strings.NewReader(data))
    if err != nil {
        fmt.Println("error:", err)
        return
    }

    auth := "Basic " + base64.StdEncoding.EncodeToString([]byte(user+":"+password))
    req.Header.Set("Authorization", auth)
    req.Header.Set("Content-Type", "application/json")

    resp, err := http.DefaultClient.Do(req)
    helpRead(resp)
}

func helpRead(resp *http.Response) {
    if resp == nil {
        return
    }
    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println("error:", err)
        return
    }
    fmt.Println("body:", string(body))
}

相关文章

网友评论

      本文标题:Go Gin 使用范例

      本文链接:https://www.haomeiwen.com/subject/xmbbdqtx.html