3 Star 0 Fork 0

Gitee 极速下载/gitlab-workhorsesource

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
此仓库是为了提升国内下载速度的镜像仓库,每日同步一次。 原始仓库: https://gitlab.com/gitlab-org/gitlab-workhorse
克隆/下载
sendfile.go 1.87 KB
一键复制 编辑 原始数据 按行查看 历史
Jacob Vosmaer 提交于 2016-03-23 17:05 . Separate imports
/*
The xSendFile middleware transparently sends static files in HTTP responses
via the X-Sendfile mechanism. All that is needed in the Rails code is the
'send_file' method.
*/
package sendfile
import (
"log"
"net/http"
"gitlab.com/gitlab-org/gitlab-workhorse/internal/helper"
)
const sendFileResponseHeader = "X-Sendfile"
type sendFileResponseWriter struct {
rw http.ResponseWriter
status int
hijacked bool
req *http.Request
}
func SendFile(h http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
s := &sendFileResponseWriter{
rw: rw,
req: req,
}
// Advertise to upstream (Rails) that we support X-Sendfile
req.Header.Set("X-Sendfile-Type", "X-Sendfile")
defer s.Flush()
h.ServeHTTP(s, req)
})
}
func (s *sendFileResponseWriter) Header() http.Header {
return s.rw.Header()
}
func (s *sendFileResponseWriter) Write(data []byte) (n int, err error) {
if s.status == 0 {
s.WriteHeader(http.StatusOK)
}
if s.hijacked {
return
}
return s.rw.Write(data)
}
func (s *sendFileResponseWriter) WriteHeader(status int) {
if s.status != 0 {
return
}
s.status = status
if s.status != http.StatusOK {
s.rw.WriteHeader(s.status)
return
}
if file := s.Header().Get(sendFileResponseHeader); file != "" {
s.Header().Del(sendFileResponseHeader)
// Mark this connection as hijacked
s.hijacked = true
// Serve the file
sendFileFromDisk(s.rw, s.req, file)
return
}
s.rw.WriteHeader(s.status)
return
}
func sendFileFromDisk(w http.ResponseWriter, r *http.Request, file string) {
log.Printf("Send file %q for %s %q", file, r.Method, r.RequestURI)
content, fi, err := helper.OpenFile(file)
if err != nil {
http.NotFound(w, r)
return
}
defer content.Close()
http.ServeContent(w, r, "", fi.ModTime(), content)
}
func (s *sendFileResponseWriter) Flush() {
s.WriteHeader(http.StatusOK)
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/mirrors/gitlab-workhorsesource.git
git@gitee.com:mirrors/gitlab-workhorsesource.git
mirrors
gitlab-workhorsesource
gitlab-workhorsesource
v1.0.1

搜索帮助