I am trying to push multiple variables into my Html template but unable to do that.
The template is as below
<html>
<head>
<title>Current IP Check</title>
</head>
<body>
<div>Current IP Address: {{.injectIP}}</div>
<div>Current Location: {{.injectCity}}</div>
</body>
</html>
the go file is this
package main
// modules requirement.
import (
"bytes"
"encoding/json"
"fmt"
"html/template"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
)
type Htmltemp struct {
injectIP string
injectCity string
}
// template to parse the json and pass to html
type Geo struct {
City string `json:"city"`
}
// Main function, to create a web server on port 80
func main() {
http.HandleFunc("/", ReadUserIP)
http.ListenAndServe(":80", nil)
}
func ReadUserIP(w http.ResponseWriter, r *http.Request) {
//check for X-forwarded-for Header
IPAddress := ""
if IPAddress == "" {
//IPAddress = r.Header.Get("x-forwarded-for")
IPAddress = "134.201.250.155, 23:24:3:5" // -----------to be deleted hardcoded for testing
}
// print the remote address from request
if IPAddress == "" {
IPAddress = r.RemoteAddr
}
// iterrate the string for desired value.
ipadd := strings.Split(IPAddress, ",") //---- my change from : to ,
cip1 := ipadd[0]
//t.Execute(w, cip1)
// creating the endpoint for Geolocation API call, by inserting the located IP
buffer := bytes.Buffer{}
buffer.WriteString("http://api.ipstack.com/")
buffer.WriteString(cip1)
buffer.WriteString("?access_key=2dd2ca2a9f39638d4f61533ecb1b337b&fields=city") //please register at the site and get a new key I changed my key, also - buy paid version for getting Timezone data using this API
url := buffer.String()
// making the API call to recieve the IP related data
response, err := http.Get(url)
if err != nil {
fmt.Print(err.Error())
os.Exit(1)
}
responseData, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Fatal(err)
}
//fmt.Println(string(responseData)) // for viewing the response
//parsing of Json and insertion of location and timezone in output file "t" is pending
// - unmarshalling the json
// then inserting them in the html template
var geo Geo
err = json.Unmarshal(responseData, &geo)
if err != nil {
panic(err)
}
fmt.Println(geo.City)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
t, err := template.ParseFiles("index.html")
if err != nil {
fmt.Fprintf(w, "Unable to load template")
}
inject := Htmltemp{injectIP: cip1, injectCity: geo.City}
t.Execute(w, inject)
}