1
0
Fork 0
photos/cmd/proxy/proxy.go

93 lines
1.8 KiB
Go

package main
import (
"io"
"log"
"net/http"
"os"
"time"
"github.com/miekg/dns"
)
var endpoint string
var endpointSecure bool
var client *http.Client
func main() {
// Read configuration
endpoint = os.Getenv("MINIO_ENDPOINT")
endpointSecure = os.Getenv("MINIO_ENDPOINT_SECURE") == "true"
// Setup HTTP client
transport := &http.Transport{
MaxIdleConns: 4,
MaxIdleConnsPerHost: 4,
IdleConnTimeout: 30 * time.Second,
DisableCompression: true,
}
client = &http.Client{
Transport: transport,
Timeout: 5 * time.Second,
}
server := &http.Server{
Addr: ":80",
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
Handler: http.HandlerFunc(handle),
}
err := server.ListenAndServe()
if err != nil {
panic(err)
}
}
func handle(w http.ResponseWriter, r *http.Request) {
if len(r.Host) == 0 {
w.WriteHeader(http.StatusNotFound)
return
}
if _, ok := dns.IsDomainName(r.Host); !ok {
w.WriteHeader(http.StatusBadRequest)
return
}
cloneRequest := r.Clone(r.Context())
cloneRequest.URL.Scheme = "http"
if endpointSecure {
cloneRequest.URL.Scheme = "https"
}
cloneRequest.URL.Host = endpoint
cloneRequest.URL.Path = "/" + r.Host + r.URL.Path
if r.URL.Path == "/" {
cloneRequest.URL.Path = "/" + r.Host + "/index.html"
}
if r.URL.Path == "/manage" {
cloneRequest.URL.Path = "/" + r.Host + "/manage/index.html"
}
cloneRequest.Host = ""
cloneRequest.RequestURI = ""
log.Println(cloneRequest.URL)
resp, err := client.Do(cloneRequest)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Println(err)
return
}
defer resp.Body.Close()
for key, value := range resp.Header {
for _, v := range value {
w.Header().Add(key, v)
}
}
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
}