Skip to content

Commit

Permalink
Optimize Response WriteHeader, default status code 500
Browse files Browse the repository at this point in the history
  • Loading branch information
bddjr committed Nov 18, 2024
1 parent e06e90f commit 87c219c
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions src_response.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (
//
// "Connection" header always set "close".
type Response struct {
status int
status int // Default: 500
header http.Header
body []byte
}
Expand All @@ -34,20 +34,28 @@ func (r *Response) Header() http.Header {
return http.Header{}
}

// Set status code and lock header, if header does not locked.
// If input 0, set 500.
func (r *Response) WriteHeader(statusCode int) {
if r.status == 0 {
r.status = statusCode
if statusCode == 0 {
r.status = 500
} else {
r.status = statusCode
}
}
}

func (r *Response) Write(b []byte) (int, error) {
r.WriteHeader(0)
if len(b) > 0 {
r.body = append(r.body, b...)
}
return len(b), nil
}

func (r *Response) WriteString(s string) (int, error) {
r.WriteHeader(0)
if len(s) > 0 {
r.body = append(r.body, s...)
}
Expand All @@ -57,7 +65,7 @@ func (r *Response) WriteString(s string) (int, error) {
// Flush flushes buffered data to the client.
func (r *Response) Flush(w io.Writer) error {
// status
r.WriteHeader(400)
r.WriteHeader(0)
_, err := fmt.Fprint(w, "HTTP/1.1 ", r.status, " ", http.StatusText(r.status), "\r\n")
if err != nil {
return err
Expand Down

0 comments on commit 87c219c

Please sign in to comment.