SendFile 发送文件内容,并终止请求
(status int, path string)
| 867 | |
| 868 | // SendFile 发送文件内容,并终止请求 |
| 869 | func (this *HTTPWriter) SendFile(status int, path string) (int64, error) { |
| 870 | this.WriteHeader(status) |
| 871 | this.isFinished = true |
| 872 | |
| 873 | fp, err := os.OpenFile(path, os.O_RDONLY, 0444) |
| 874 | if err != nil { |
| 875 | return 0, fmt.Errorf("open file '%s' failed: %w", path, err) |
| 876 | } |
| 877 | defer func() { |
| 878 | _ = fp.Close() |
| 879 | }() |
| 880 | |
| 881 | stat, err := fp.Stat() |
| 882 | if err != nil { |
| 883 | return 0, err |
| 884 | } |
| 885 | if stat.IsDir() { |
| 886 | return 0, errors.New("open file '" + path + "' failed: it is a directory") |
| 887 | } |
| 888 | |
| 889 | var bufPool = this.req.bytePool(stat.Size()) |
| 890 | var buf = bufPool.Get() |
| 891 | defer bufPool.Put(buf) |
| 892 | |
| 893 | written, err := io.CopyBuffer(this, fp, buf.Bytes) |
| 894 | if err != nil { |
| 895 | return written, err |
| 896 | } |
| 897 | |
| 898 | return written, nil |
| 899 | } |
| 900 | |
| 901 | // SendResp 发送响应对象 |
| 902 | func (this *HTTPWriter) SendResp(resp *http.Response) (int64, error) { |