inou/portal/api_proxy.go

82 lines
1.7 KiB
Go

package main
import (
"io"
"net/http"
"strings"
"time"
)
var apiEndpoints = map[string]bool{
"/api/version": true,
"/api/dossiers": true,
"/api/dossier": true,
"/api/studies": true,
"/api/series": true,
"/api/slices": true,
"/api/labs/tests": true,
"/api/labs/results": true,
}
const apiBackend = "http://127.0.0.1:8082"
func handleAPIProxy(w http.ResponseWriter, r *http.Request) {
// Allow v1 API paths to pass through
if !strings.HasPrefix(r.URL.Path, "/api/v1/") && !apiEndpoints[r.URL.Path] {
tarpit(w, r, "TARPIT-API")
return
}
backendURL := apiBackend + r.URL.RequestURI()
proxyReq, err := http.NewRequest(r.Method, backendURL, r.Body)
if err != nil {
http.Error(w, "proxy error", http.StatusBadGateway)
return
}
for k, v := range r.Header {
proxyReq.Header[k] = v
}
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(proxyReq)
if err != nil {
http.Error(w, "backend unavailable", http.StatusBadGateway)
return
}
defer resp.Body.Close()
for k, v := range resp.Header {
w.Header()[k] = v
}
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
}
func handleImageProxy(w http.ResponseWriter, r *http.Request) {
backendURL := apiBackend + r.URL.RequestURI()
proxyReq, err := http.NewRequest(r.Method, backendURL, r.Body)
if err != nil {
http.Error(w, "proxy error", http.StatusBadGateway)
return
}
for k, v := range r.Header {
proxyReq.Header[k] = v
}
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(proxyReq)
if err != nil {
http.Error(w, "backend unavailable", http.StatusBadGateway)
return
}
defer resp.Body.Close()
for k, v := range resp.Header {
w.Header()[k] = v
}
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
}