48 lines
909 B
Go
48 lines
909 B
Go
package main
|
|
|
|
import (
|
|
"embed"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"strings"
|
|
)
|
|
|
|
//go:embed *.html *.svg *.css
|
|
var static embed.FS
|
|
|
|
func geoHandler(w http.ResponseWriter, r *http.Request) {
|
|
ip := r.Header.Get("X-Forwarded-For")
|
|
if ip == "" {
|
|
ip = r.RemoteAddr
|
|
}
|
|
// Strip port
|
|
if i := strings.LastIndex(ip, ":"); i >= 0 {
|
|
ip = ip[:i]
|
|
}
|
|
ip = strings.Trim(ip, "[]")
|
|
|
|
resp, err := http.Get("https://ipapi.co/" + ip + "/json/")
|
|
if err != nil {
|
|
http.Error(w, `{"error":"geo failed"}`, 502)
|
|
return
|
|
}
|
|
defer resp.Body.Close()
|
|
w.Header().Set("Content-Type", "application/json")
|
|
io.Copy(w, resp.Body)
|
|
}
|
|
|
|
func main() {
|
|
port := os.Getenv("PORT")
|
|
if port == "" {
|
|
port = "8099"
|
|
}
|
|
http.HandleFunc("/geo", geoHandler)
|
|
http.Handle("/", http.FileServer(http.FS(static)))
|
|
log.Printf("vault1984-web starting on :%s", port)
|
|
if err := http.ListenAndServe(":"+port, nil); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
}
|