move NewRequest to data.go

This commit is contained in:
Will Norris 2013-12-26 14:38:15 -08:00
parent c3eda83ab5
commit cc2bed6b8f
4 changed files with 122 additions and 142 deletions

View file

@ -18,6 +18,7 @@ package proxy
import (
"bytes"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
@ -116,6 +117,41 @@ type Request struct {
Options *Options // Image transformation to perform
}
// NewRequest parses an http.Request into an image request.
func NewRequest(r *http.Request) (*Request, error) {
var err error
req := new(Request)
path := r.URL.Path[1:] // strip leading slash
req.URL, err = url.Parse(path)
if err != nil || !req.URL.IsAbs() {
// first segment is likely options
parts := strings.SplitN(path, "/", 2)
if len(parts) != 2 {
return nil, URLError{"too few path segments", r.URL}
}
req.URL, err = url.Parse(parts[1])
if err != nil {
return nil, URLError{fmt.Sprintf("unable to parse remote URL: %v", err), r.URL}
}
req.Options = ParseOptions(parts[0])
}
if !req.URL.IsAbs() {
return nil, URLError{"must provide absolute remote URL", r.URL}
}
if req.URL.Scheme != "http" && req.URL.Scheme != "https" {
return nil, URLError{"remote URL must have http or https URL", r.URL}
}
// query string is always part of the remote URL
req.URL.RawQuery = r.URL.RawQuery
return req, nil
}
// Image represents a remote image that is being proxied. It tracks where
// the image was originally retrieved from and how long the image can be cached.
type Image struct {