github.com/wangyougui/gf/v2@v2.6.5/net/ghttp/internal/response/response_writer.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/wangyougui/gf.
     6  
     7  package response
     8  
     9  import (
    10  	"bufio"
    11  	"net"
    12  	"net/http"
    13  )
    14  
    15  // Writer wraps http.ResponseWriter for extra features.
    16  type Writer struct {
    17  	http.ResponseWriter      // The underlying ResponseWriter.
    18  	hijacked            bool // Mark this request is hijacked or not.
    19  	wroteHeader         bool // Is header wrote or not, avoiding error: superfluous/multiple response.WriteHeader call.
    20  }
    21  
    22  // NewWriter creates and returns a new Writer.
    23  func NewWriter(writer http.ResponseWriter) *Writer {
    24  	return &Writer{
    25  		ResponseWriter: writer,
    26  	}
    27  }
    28  
    29  // WriteHeader implements the interface of http.ResponseWriter.WriteHeader.
    30  func (w *Writer) WriteHeader(status int) {
    31  	w.ResponseWriter.WriteHeader(status)
    32  	w.wroteHeader = true
    33  }
    34  
    35  // Hijack implements the interface function of http.Hijacker.Hijack.
    36  func (w *Writer) Hijack() (conn net.Conn, writer *bufio.ReadWriter, err error) {
    37  	conn, writer, err = w.ResponseWriter.(http.Hijacker).Hijack()
    38  	w.hijacked = true
    39  	return
    40  }
    41  
    42  // IsHeaderWrote returns if the header status is written.
    43  func (w *Writer) IsHeaderWrote() bool {
    44  	return w.wroteHeader
    45  }
    46  
    47  // IsHijacked returns if the connection is hijacked.
    48  func (w *Writer) IsHijacked() bool {
    49  	return w.hijacked
    50  }
    51  
    52  // Flush sends any buffered data to the client.
    53  func (w *Writer) Flush() {
    54  	flusher, ok := w.ResponseWriter.(http.Flusher)
    55  	if ok {
    56  		flusher.Flush()
    57  		w.wroteHeader = true
    58  	}
    59  }