package main

import (
    "net/http"

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

func hello(c *gin.Context) {
    c.String(http.StatusOK, "hello\n")
}

func XXXMiddleware(c *gin.Context) {
    // 调用其他中间件前
    c.String(http.StatusOK, "hello before\n")

    // 取消后续中间件执行
    c.Abort()

    // 调用后续中间件 (无后续代码可省略)
    c.Next()

    // 调用其他中间件后
    c.String(http.StatusOK, "hello after\n")
}

func main() {
    api := gin.Default()

    // 使用中间件
    api.Use(XXXMiddleware)

    api.GET("/hello", hello)
    // api.GET("/hello", hello, XXXMiddleware) 这里也是可以挂后续中间件的

    api.Run(":5000")
}

package main

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

func hello(c *gin.Context) {
    c.JSON(200, gin.H{
        "message": "hello world",
    })
}

func main() {
    api := gin.Default()
    api.GET("/hello", hello)
    api.Run(":5000")
}

curl -XGET http://localhost:5000/hello
{"message":"hello world"}

import "os/exec"

// 不获取执行内容
err := exec.Command("git", "fetch").Run()

// 获取执行内容
out, err := exec.Command("git", "rev-parse", "--abbrev-ref", "HEAD").Output()
fmt.Println(string(out))

// 实时获取执行内容
cmd := exec.Command("python3", "xxx.py")
stdout, err := cmd.StdoutPipe()
cmd.Start()
reader := bufio.NewReader(stdout)
for {
    line, err := reader.ReadString('\n')
    if err != nil {
        break
    }
    fmt.Println(line)
}
cmd.Wait()

服务端模式

import "github.com/gorilla/websocket"

var upGrader = websocket.Upgrader{
    CheckOrigin: func(r *http.Request) bool {
        return true
    },
}

func websocketHandler(c *gin.Context) {
    ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
    if err != nil {
        return
    }
    defer ws.Close()
    
    // 循环读取部分
    for {
        //读取ws中的数据
        _, _, err := ws.ReadMessage()
        if err != nil {
            break
        }
    }

    // 发送消息部分
    data := []byte("hello world")
    ws.WriteMessage(websocket.TextMessage, data)
}

兼容 gin 和 原生http

js 测试代码
        var ws = new WebSocket("ws://wameidemao.com/ws");  
        //连接打开时触发 
        ws.onopen = function(evt) {  
            console.log("Connection open ...");  
            ws.send("Hello WebSockets!");  
        };  

        //接收到消息时触发  
        ws.onmessage = function(evt) {  
            console.log("Received Message: " + evt.data);  
        };  

        //连接关闭时触发  
        ws.onclose = function(evt) {  
            console.log("Connection closed.");  
        }

客户端模式

package main

import (
    "github.com/gorilla/websocket"
)

func main() {
    url := "ws://api.yqmiot.com/websocket"
    c, _, err := websocket.DefaultDialer.Dial(url, nil)
    if err != nil {
        panic(err)
    }

    go func() {
        for {
            _, data, err := c.ReadMessage()
            if err != nil {
                break
            }
            _ = data
        }
    }()

    go func() {
        for {
            time.Sleep(time.Second * 5)
            c.WriteMessage(websocket.BinaryMessage, []byte("hello world"))
        }
    }
}

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "net/http"
)

const (
    corpid     = "企业代号"
    agentId    = "1000004"
    corpsecret = "企业密钥"
)

func httpGetJson(url string) (map[string]interface{}, error) {
    resp, err := http.Get(url)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()

    var data map[string]interface{}
    err = json.NewDecoder(resp.Body).Decode(&data)
    if err != nil {
        return nil, err
    }

    return data, nil
}

func httpPostJson(url string, data map[string]interface{}) (map[string]interface{}, error) {
    xxx, err := json.Marshal(data)
    if err != nil {
        return nil, err
    }

    resp, err := http.Post(url, "application/json", bytes.NewReader(xxx))
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()

    var data2 map[string]interface{}
    err = json.NewDecoder(resp.Body).Decode(&data)
    if err != nil {
        return nil, err
    }

    return data2, nil
}

func main() {
    url := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s", corpid, corpsecret)
    data, err := httpGetJson(url)
    if err != nil {
        fmt.Println(err)
        return
    }

    errcode := data["errcode"].(float64)
    if errcode != 0 {
        fmt.Println("errcode: ", errcode)
        return
    }
    access_token := data["access_token"]

    req := map[string]interface{}{
        "touser":  "@all",
        "msgtype": "text",
        "agentid": agentId,
        "text": map[string]interface{}{
            "content": "hello",
        },
    }

    url = fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s", access_token)
    data, err = httpPostJson(url, req)
    if err != nil {
        fmt.Println(err)
        return
    }

    fmt.Println("ok")
}