armbian-router/http.go

53 lines
969 B
Go
Raw Normal View History

2022-01-10 04:47:40 +00:00
package main
import (
2022-01-10 04:53:23 +00:00
"fmt"
"net"
"net/http"
"net/url"
"path"
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 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
2022-01-10 04:53:23 +00:00
u := &url.URL{
Scheme: scheme,
Host: server.Host,
Path: path.Join(server.Path, r.URL.Path),
}
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)
}