Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

在微信多模板消息推送的时候会panic,Handler crashed with error http: wrote more than the declared Content-Length #190

Open
chaegumi opened this issue Nov 12, 2019 · 0 comments

Comments

@chaegumi
Copy link

chaegumi commented Nov 12, 2019

问题及现象

不是每次都报错,我观察了下,是render里边的性能不够高

//Render render from bytes
func (ctx *Context) Render(bytes []byte) {
	//debug
	//fmt.Println("response msg = ", string(bytes))
	ctx.Writer.WriteHeader(200)
	_, err := ctx.Writer.Write(bytes)
	if err != nil {
		panic(err)
	}
}

看了beego的源码,再结合stackoverflow上搜索到的回答https://stackoverflow.com/questions/29664720/golang-map-of-http-responsewriters

就是这个问题了。

The goroutine responsible for the ResponseWriter exits. A 'better' way would be to trigger the work, block in the handler, write the work to a buffer, and then io.Copy(buf, w) to write it out back in the handler. Set a timeout to prevent the HTTP connection from timing out on the client side.

beego

func (output *BeegoOutput) Body(content []byte) error {
	var encoding string
	var buf = &bytes.Buffer{}
	if output.EnableGzip {
		encoding = ParseEncoding(output.Context.Request)
	}
	if b, n, _ := WriteBody(encoding, buf, content); b {
		output.Header("Content-Encoding", n)
		output.Header("Content-Length", strconv.Itoa(buf.Len()))
	} else {
		output.Header("Content-Length", strconv.Itoa(len(content)))
	}
	// Write status code if it has been set manually
	// Set it to 0 afterwards to prevent "multiple response.WriteHeader calls"
	if output.Status != 0 {
		output.Context.ResponseWriter.WriteHeader(output.Status)
		output.Status = 0
	} else {
		output.Context.ResponseWriter.Started = true
	}
	io.Copy(output.Context.ResponseWriter, buf)
	return nil
}

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant