1
0
mirror of https://github.com/gogf/gf.git synced 2025-04-05 11:18:50 +08:00

fix: http superfluous response.WriteHeader call in some scenario (#3428)

This commit is contained in:
John Guo 2024-03-28 22:08:54 +08:00 committed by GitHub
parent 3a9e0e34ca
commit 1c12f3a30d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 26 additions and 5 deletions

View File

@ -72,8 +72,8 @@ func DumpWithOption(value interface{}, option gutil.DumpOption) {
}
// DumpJson pretty dumps json content to stdout.
func DumpJson(jsonContent string) {
gutil.DumpJson(jsonContent)
func DumpJson(value any) {
gutil.DumpJson(value)
}
// Throw throws an exception, which can be caught by TryCatch function.

View File

@ -28,7 +28,11 @@ func NewWriter(writer http.ResponseWriter) *Writer {
}
// WriteHeader implements the interface of http.ResponseWriter.WriteHeader.
// Note that the underlying `WriteHeader` can only be called once in a http response.
func (w *Writer) WriteHeader(status int) {
if w.wroteHeader {
return
}
w.ResponseWriter.WriteHeader(status)
w.wroteHeader = true
}
@ -42,6 +46,7 @@ func (w *Writer) BytesWritten() int64 {
func (w *Writer) Write(data []byte) (int, error) {
n, err := w.ResponseWriter.Write(data)
w.bytesWritten += int64(n)
w.wroteHeader = true
return n, err
}

View File

@ -472,12 +472,28 @@ func addSlashesForString(s string) string {
}
// DumpJson pretty dumps json content to stdout.
func DumpJson(jsonContent string) {
func DumpJson(value any) {
switch result := value.(type) {
case []byte:
doDumpJson(result)
case string:
doDumpJson([]byte(result))
default:
jsonContent, err := json.Marshal(value)
if err != nil {
fmt.Println(err.Error())
return
}
doDumpJson(jsonContent)
}
}
func doDumpJson(jsonContent []byte) {
var (
buffer = bytes.NewBuffer(nil)
jsonBytes = []byte(jsonContent)
jsonBytes = jsonContent
)
if err := json.Indent(buffer, jsonBytes, "", "\t"); err != nil {
if err := json.Indent(buffer, jsonBytes, "", " "); err != nil {
fmt.Println(err.Error())
}
fmt.Println(buffer.String())