0
Fork 0
mirror of https://github.com/willnorris/imageproxy.git synced 2024-12-16 21:56:43 -05:00

add initial (pretty naive) server implementation

This commit is contained in:
Will Norris 2013-11-27 12:10:29 -08:00
parent e61fba8787
commit 11441a107a
2 changed files with 61 additions and 0 deletions

20
imageproxy.go Normal file
View file

@ -0,0 +1,20 @@
package main
import (
"log"
"net/http"
"github.com/willnorris/go-imageproxy/proxy"
)
func main() {
p := proxy.NewProxy(nil)
server := &http.Server{
Addr: ":8080",
Handler: p,
}
err := server.ListenAndServe()
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}

View file

@ -3,6 +3,7 @@ package proxy
import ( import (
"fmt" "fmt"
"io/ioutil"
"net/http" "net/http"
"net/url" "net/url"
"strconv" "strconv"
@ -79,3 +80,43 @@ func NewRequest(r *http.Request) (*Request, error) {
return req, nil return req, nil
} }
// Proxy serves image requests.
type Proxy struct {
Client *http.Client // client used to fetch remote URLs
}
// NewProxy constructs a new proxy. The provided http Client will be used to
// fetch remote URLs. If nil is provided, http.DefaultClient will be used.
func NewProxy(client *http.Client) *Proxy {
if client == nil {
client = http.DefaultClient
}
return &Proxy{Client: client}
}
// ServeHTTP handles image requests.
func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
req, err := NewRequest(r)
if err != nil {
http.Error(w, fmt.Sprintf("invalid request URL: %v", err.Error()), http.StatusBadRequest)
return
}
resp, err := p.Client.Get(req.URL.String())
if err != nil {
http.Error(w, fmt.Sprintf("error fetching remote image: %v", err.Error()), http.StatusInternalServerError)
return
}
if resp.StatusCode != http.StatusOK {
http.Error(w, fmt.Sprintf("error fetching remote image: %v", resp.Status), resp.StatusCode)
return
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
http.Error(w, fmt.Sprintf("error fetching remote image: %v", err.Error()), http.StatusInternalServerError)
}
w.Write(data)
}