为什么webserver的返回不能放在channel中,之后一起处理返回,将*gin.Context放在channel后在取出就出错了。
第一个请求返回可以,之后就都不可以了
~~~
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
type data struct {
c *gin.Context
name string
}
var dataChan chan *data
func result(c *gin.Context, name string) {
c.JSON(http.StatusOK, name)
}
func g() {
for val := range dataChan {
result(val.c, val.name)
}
}
func hander(c *gin.Context) {
name := c.Query("name")
dataChan <- &data{c: c, name: name}
//result(c, name)
}
func main() {
dataChan = make(chan *data, 100)
go g()
router := gin.Default()
router.GET("/welcome", hander)
router.Run(":8080")
}
~~~
type Handler
A Handler responds to an HTTP request.
ServeHTTP should write reply headers and data to the ResponseWriter and then return. Returning signals that the request is finished; it is not valid to use the ResponseWriter or read from the Request.Body after or concurrently with the completion of the ServeHTTP call.
#3
更多评论
这个代码改成异步的了。
但是用postman请求时,第一个返回时对的,之后就变成框架默认返回了,不是c.JSON(http.StatusOK, name) 返回的了
#2