fix cors and add html template
All checks were successful
Build docker container / Build image (push) Successful in 30s

This commit is contained in:
Mans Ziesel 2024-06-03 13:53:42 +02:00
parent 1d1f9b0fe7
commit c96249c0b5
2 changed files with 30 additions and 4 deletions

18
main.go
View File

@ -4,9 +4,11 @@ import (
"context"
"encoding/json"
"fmt"
"html/template"
"log"
"net"
"net/http"
"path"
)
type AddressType string
@ -82,8 +84,19 @@ func mainHandler(w http.ResponseWriter, r *http.Request) {
case http.MethodGet:
switch r.URL.Path {
case "/":
fmt.Fprintf(w, "%s\n%s", netAddr.Address, netAddr.Type)
case "/api":
fp := path.Join("templates", "index.html")
tmpl, err := template.ParseFiles(fp)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := tmpl.Execute(w, netAddr); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
case "/raw":
fmt.Fprintf(w, "%s\n%s\n", netAddr.Address, netAddr.Type)
case "/json":
responseJSON(w, netAddr)
default:
http.NotFound(w, r)
@ -95,6 +108,7 @@ func mainHandler(w http.ResponseWriter, r *http.Request) {
func responseJSON(w http.ResponseWriter, data interface{}) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
err := json.NewEncoder(w).Encode(data)
if err != nil {
http.Error(w, "Failed to encode JSON", http.StatusInternalServerError)

View File

@ -6,7 +6,19 @@
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
IPv4: asdf
IPv6: asdf
IP: {{ .Address }}<br />
IP: {{ .Type}}<br />
</body>
<script>
async function getIp() {
const isIpv4 = "{{ .Type }}" == "IPv4";
let requestUrl = isIpv4 ? "https://ip6.mziesel.nl/json" : "https://ip4.mziesel.nl/json";
const response = await fetch(requestUrl);
const data = await response.json();
console.log(data)
}
getIp();
</script>
</html>