armbian-router/http.go

69 lines
1.3 KiB
Go
Raw Normal View History

2022-01-10 04:47:40 +00:00
package main
import (
"encoding/json"
2022-01-10 04:53:23 +00:00
"fmt"
"net"
"net/http"
"net/url"
"path"
"strings"
2022-01-10 04:47:40 +00:00
)
func statusRequest(w http.ResponseWriter, r *http.Request) {
2022-01-10 04:53:23 +00:00
w.WriteHeader(http.StatusOK)
2022-01-10 04:47:40 +00:00
}
func serversRequest(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(servers)
}
2022-01-10 04:47:40 +00:00
func redirectRequest(w http.ResponseWriter, r *http.Request) {
2022-01-10 04:53:23 +00:00
ipStr, _, err := net.SplitHostPort(r.RemoteAddr)
2022-01-10 04:47:40 +00:00
2022-01-10 04:53:23 +00:00
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
2022-01-10 04:47:40 +00:00
2022-01-10 04:53:23 +00:00
ip := net.ParseIP(ipStr)
2022-01-10 04:47:40 +00:00
2022-01-10 04:53:23 +00:00
// TODO: This is temporary to allow testing on private addresses.
if ip.IsPrivate() {
ip = net.ParseIP("1.1.1.1")
}
2022-01-10 04:47:40 +00:00
2022-01-10 04:53:23 +00:00
server, distance, err := servers.Closest(ip)
2022-01-10 04:47:40 +00:00
2022-01-10 04:53:23 +00:00
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
2022-01-10 04:47:40 +00:00
2022-01-10 04:53:23 +00:00
scheme := r.URL.Scheme
2022-01-10 04:47:40 +00:00
2022-01-10 04:53:23 +00:00
if scheme == "" {
scheme = "https"
}
2022-01-10 04:47:40 +00:00
redirectPath := path.Join(server.Path, r.URL.Path)
if dlMap != nil {
if newPath, exists := dlMap[strings.TrimLeft(r.URL.Path, "/")]; exists {
redirectPath = path.Join(server.Path, newPath)
}
}
2022-01-10 04:53:23 +00:00
u := &url.URL{
Scheme: scheme,
Host: server.Host,
Path: redirectPath,
2022-01-10 04:53:23 +00:00
}
2022-01-10 04:47:40 +00:00
2022-01-10 04:53:23 +00:00
w.Header().Set("X-Geo-Distance", fmt.Sprintf("%f", distance))
w.Header().Set("Location", u.String())
w.WriteHeader(http.StatusFound)
}