github.com/gogf/gf@v1.16.9/net/ghttp/ghttp_response.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/gogf/gf.
     6  //
     7  
     8  package ghttp
     9  
    10  import (
    11  	"bytes"
    12  	"fmt"
    13  	"net/http"
    14  
    15  	"github.com/gogf/gf/os/gres"
    16  
    17  	"github.com/gogf/gf/os/gfile"
    18  )
    19  
    20  // Response is the http response manager.
    21  // Note that it implements the http.ResponseWriter interface with buffering feature.
    22  type Response struct {
    23  	*ResponseWriter                 // Underlying ResponseWriter.
    24  	Server          *Server         // Parent server.
    25  	Writer          *ResponseWriter // Alias of ResponseWriter.
    26  	Request         *Request        // According request.
    27  }
    28  
    29  // newResponse creates and returns a new Response object.
    30  func newResponse(s *Server, w http.ResponseWriter) *Response {
    31  	r := &Response{
    32  		Server: s,
    33  		ResponseWriter: &ResponseWriter{
    34  			writer: w,
    35  			buffer: bytes.NewBuffer(nil),
    36  		},
    37  	}
    38  	r.Writer = r.ResponseWriter
    39  	return r
    40  }
    41  
    42  // ServeFile serves the file to the response.
    43  func (r *Response) ServeFile(path string, allowIndex ...bool) {
    44  	var (
    45  		serveFile *staticFile
    46  	)
    47  	if file := gres.Get(path); file != nil {
    48  		serveFile = &staticFile{
    49  			File:  file,
    50  			IsDir: file.FileInfo().IsDir(),
    51  		}
    52  	} else {
    53  		path, _ = gfile.Search(path)
    54  		if path == "" {
    55  			r.WriteStatus(http.StatusNotFound)
    56  			return
    57  		}
    58  		serveFile = &staticFile{Path: path}
    59  	}
    60  	r.Server.serveFile(r.Request, serveFile, allowIndex...)
    61  }
    62  
    63  // ServeFileDownload serves file downloading to the response.
    64  func (r *Response) ServeFileDownload(path string, name ...string) {
    65  	var (
    66  		serveFile *staticFile
    67  	)
    68  	downloadName := ""
    69  	if len(name) > 0 {
    70  		downloadName = name[0]
    71  	}
    72  	if file := gres.Get(path); file != nil {
    73  		serveFile = &staticFile{
    74  			File:  file,
    75  			IsDir: file.FileInfo().IsDir(),
    76  		}
    77  		if downloadName == "" {
    78  			downloadName = gfile.Basename(file.Name())
    79  		}
    80  	} else {
    81  		path, _ = gfile.Search(path)
    82  		if path == "" {
    83  			r.WriteStatus(http.StatusNotFound)
    84  			return
    85  		}
    86  		serveFile = &staticFile{Path: path}
    87  		if downloadName == "" {
    88  			downloadName = gfile.Basename(path)
    89  		}
    90  	}
    91  	r.Header().Set("Content-Type", "application/force-download")
    92  	r.Header().Set("Accept-Ranges", "bytes")
    93  	r.Header().Set("Content-Disposition", fmt.Sprintf(`attachment;filename="%s"`, downloadName))
    94  	r.Server.serveFile(r.Request, serveFile)
    95  }
    96  
    97  // RedirectTo redirects client to another location.
    98  // The optional parameter <code> specifies the http status code for redirecting,
    99  // which commonly can be 301 or 302. It's 302 in default.
   100  func (r *Response) RedirectTo(location string, code ...int) {
   101  	r.Header().Set("Location", location)
   102  	if len(code) > 0 {
   103  		r.WriteHeader(code[0])
   104  	} else {
   105  		r.WriteHeader(http.StatusFound)
   106  	}
   107  	r.Request.Exit()
   108  }
   109  
   110  // RedirectBack redirects client back to referer.
   111  // The optional parameter <code> specifies the http status code for redirecting,
   112  // which commonly can be 301 or 302. It's 302 in default.
   113  func (r *Response) RedirectBack(code ...int) {
   114  	r.RedirectTo(r.Request.GetReferer(), code...)
   115  }
   116  
   117  // Buffer returns the buffered content as []byte.
   118  func (r *Response) Buffer() []byte {
   119  	return r.buffer.Bytes()
   120  }
   121  
   122  // BufferString returns the buffered content as string.
   123  func (r *Response) BufferString() string {
   124  	return r.buffer.String()
   125  }
   126  
   127  // BufferLength returns the length of the buffered content.
   128  func (r *Response) BufferLength() int {
   129  	return r.buffer.Len()
   130  }
   131  
   132  // SetBuffer overwrites the buffer with <data>.
   133  func (r *Response) SetBuffer(data []byte) {
   134  	r.buffer.Reset()
   135  	r.buffer.Write(data)
   136  }
   137  
   138  // ClearBuffer clears the response buffer.
   139  func (r *Response) ClearBuffer() {
   140  	r.buffer.Reset()
   141  }
   142  
   143  // Flush outputs the buffer content to the client and clears the buffer.
   144  func (r *Response) Flush() {
   145  	if r.Server.config.ServerAgent != "" {
   146  		r.Header().Set("Server", r.Server.config.ServerAgent)
   147  	}
   148  	r.Writer.Flush()
   149  }