1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
12 // fileTransport implements RoundTripper for the 'file' protocol.
13 type fileTransport struct {
17 // NewFileTransport returns a new RoundTripper, serving the provided
18 // FileSystem. The returned RoundTripper ignores the URL host in its
19 // incoming requests, as well as most other properties of the
22 // The typical use case for NewFileTransport is to register the "file"
23 // protocol with a Transport, as in:
25 // t := &http.Transport{}
26 // t.RegisterProtocol("file", http.NewFileTransport(http.Dir("/")))
27 // c := &http.Client{Transport: t}
28 // res, err := c.Get("file:///etc/passwd")
30 func NewFileTransport(fs FileSystem) RoundTripper {
31 return fileTransport{fileHandler{fs}}
34 func (t fileTransport) RoundTrip(req *Request) (resp *Response, err error) {
35 // We start ServeHTTP in a goroutine, which may take a long
36 // time if the file is large. The newPopulateResponseWriter
37 // call returns a channel which either ServeHTTP or finish()
38 // sends our *Response on, once the *Response itself has been
39 // populated (even if the body itself is still being
40 // written to the res.Body, a pipe)
41 rw, resc := newPopulateResponseWriter()
43 t.fh.ServeHTTP(rw, req)
49 func newPopulateResponseWriter() (*populateResponse, <-chan *Response) {
51 rw := &populateResponse{
52 ch: make(chan *Response),
65 // populateResponse is a ResponseWriter that populates the *Response
66 // in res, and writes its body to a pipe connected to the response
67 // body. Once writes begin or finish() is called, the response is sent
69 type populateResponse struct {
78 func (pr *populateResponse) finish() {
88 func (pr *populateResponse) sendResponse() {
92 pr.sentResponse = true
95 pr.res.ContentLength = -1
100 func (pr *populateResponse) Header() Header {
104 func (pr *populateResponse) WriteHeader(code int) {
108 pr.wroteHeader = true
110 pr.res.StatusCode = code
111 pr.res.Status = fmt.Sprintf("%d %s", code, StatusText(code))
114 func (pr *populateResponse) Write(p []byte) (n int, err error) {
116 pr.WriteHeader(StatusOK)
119 if !pr.sentResponse {
122 return pr.pw.Write(p)