implemented ip from backend
This commit is contained in:
@@ -1,15 +1,34 @@
|
||||
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)
|
||||
@@ -28,7 +47,18 @@ func handleRoot(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
templ.Execute(w, nil)
|
||||
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err != nil {
|
||||
host = 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) {
|
||||
@@ -40,3 +70,28 @@ func serveRobots(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user