package main import ( "encoding/json" "errors" "fmt" "io" "net" "net/http" "os" "text/template" "github.com/joho/godotenv" ) type ipResponse struct { IP string `json:"ip"` Asn string `json:"asn"` AsName string `json:"as_name"` AsDomain string `json:"as_domain"` CountryCode string `json:"country_code"` Country string `json:"country"` ContinentCode string `json:"continent_code"` Continent string `json:"continent"` } func main() { mux := http.NewServeMux() godotenv.Load() // routes mux.HandleFunc("/", handleRoot) mux.HandleFunc("/robots.txt", serveRobots) mux.HandleFunc("/*", handleRoot) mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static")))) fmt.Println("listening on 8080") http.ListenAndServe(":8080", mux) } func handleRoot(w http.ResponseWriter, r *http.Request) { templ, err := template.ParseFiles("templates/home.html") if err != nil { http.Error(w, "template not found", http.StatusInternalServerError) return } host := r.Header.Get("X-Real-IP") if host == "" { host = r.Header.Get("X-Forwarded-For") } if host == "" { host, _, _ = net.SplitHostPort(r.RemoteAddr) } dox, err := callApi(host) if err != nil { http.Error(w, "api call failed", http.StatusInternalServerError) return } templ.Execute(w, dox) } func serveRobots(w http.ResponseWriter, r *http.Request) { robots, err := os.ReadFile("templates/robots.txt") if err != nil { fmt.Fprintf(w, "sucks to suck") return } fmt.Fprint(w, string(robots)) } func callApi(ip string) (ipResponse, error) { api := os.Getenv("IPAPI") fmt.Printf("api: %v\n", api) var values ipResponse if api == " " { return values, errors.New("No api key") } url := fmt.Sprintf("https://api.ipinfo.io/lite/%s?token=%s", ip, api) request, err := http.Get(url) if err != nil { return values, errors.New("request failed") } defer request.Body.Close() body, _ := io.ReadAll(request.Body) err = json.Unmarshal(body, &values) return values, nil }