Echo frameworks context bind twice without losing data

Retrieve data from echo middleware, may cause you get code=400, message=EOF error.

Context.Bind only can bind once, after the request passed the middleware,the request data reader is running out, Context.Bind() function read request body data from the socket buffer, once you took it out, it just gone

that’s why it returns EOF error.

solution

func main() {
    echoServer := echo.New()
    echoServer.POST("/api", webfunc1, middleware1)
    echoServer.Start(":8080")
}

func middleware1(next echo.HandlerFunc) echo.HandlerFunc {
    return func(c echo.Context) error {
        // read origin body bytes
        var bodyBytes []byte
        if c.Request().Body != nil {
            bodyBytes, _ = ioutil.ReadAll(c.Request().Body)
            // write back to request body
            c.Request().Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
            // parse json data
            reqData := struct {
                ID string `json:"id"`
            }{}
            err := json.Unmarshal(bodyBytes, &reqData)
            if err != nil {
                return c.JSON(400, "error json.")
            }
            fmt.Println(reqData.ID)
        }
        return next(c)
    }
}

func webfunc1(c echo.Context) error {
    reqData := struct {
        Data string `json:"data"`
    }{}
    c.Bind(&reqData)
    fmt.Println(reqData.Data)
    return c.HTML(200, "200 OK.")
}

Golang: Read from an io.ReadWriter without losing its content

Python基于socket\subprocess编写远程命令执行

简介写socket通讯过程
服务端

1. 初始化socket对象
2. 绑定IP/PORT
3. 监听端口
4. 等待客户链接
    1. 等待消息
    2. 发送消息
5. 关闭客户端链接

客户端

1. 初始化socket对象
2. 链接服务端
    1. 发送消息
    2. 等待消息
3. 关闭与服务器链接

Continue reading Python基于socket\subprocess编写远程命令执行