package main import ( "encoding/json" "fmt" "log" "net/http" "strconv" "time" ) var portToListenOn int = 9100 var defaultTZ string = "Europe/Berlin" type DateTimeResponse struct { Year int `json:"year,omitempty"` Month int `json:"month,omitempty"` Day int `json:"day,omitempty"` Hour int `json:"hour,omitempty"` Minute int `json:"minute,omitempty"` Seconds int `json:"seconds,omitempty"` MilliSeconds int `json:"milliSeconds,omitempty"` DateTime string `json:"dateTime,omitempty"` Date string `json:"date,omitempty"` Time string `json:"time,omitempty"` TimeZone string `json:"timeZone,omitempty"` DayOfWeek string `json:"dayOfWeek,omitempty"` DstActive bool `json:"dstActive,omitempty"` } func main() { fmt.Println("********************************************") fmt.Println("* *") fmt.Println("* git.0x0001f346.de/andreas/Datetime-API *") fmt.Println("* *") fmt.Println("********************************************") fmt.Println("") fmt.Printf("Listening: http://localhost:%d\n", portToListenOn) fmt.Println("") http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { loc, _ := time.LoadLocation(defaultTZ) if r.URL.String() != "/" { newloc, err := time.LoadLocation(r.URL.String()[1:]) if err == nil { loc = newloc } } log.Printf( "%q %q\n", loc.String(), r.RemoteAddr, ) w.Header().Add("Content-Language", "en") w.Header().Add("Content-Type", "application/json; charset=utf-8") w.Header().Add("Server", "git.0x0001f346.de/andreas/Datetime-API") fmt.Fprint(w, GetDateTimeResponseAsJSONString(loc)) }) log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", portToListenOn), nil)) } func GetDateTimeResponse(loc *time.Location) DateTimeResponse { t := time.Now().In(loc) return DateTimeResponse{ Year: t.Year(), Month: int(t.Month()), Day: t.Day(), Hour: t.Hour(), Minute: t.Minute(), Seconds: t.Second(), MilliSeconds: func(i int64, err error) int { return int(i) }(strconv.ParseInt(strconv.Itoa(t.Nanosecond())[:3], 10, 0)), DateTime: t.Format(time.RFC3339), Date: fmt.Sprintf("%02d/%02d/%04d", t.Month(), t.Day(), t.Year()), Time: fmt.Sprintf("%02d:%02d", t.Hour(), t.Minute()), TimeZone: loc.String(), DayOfWeek: t.Weekday().String(), DstActive: t.IsDST(), } } func GetDateTimeResponseAsJSONString(loc *time.Location) string { r, _ := json.Marshal(GetDateTimeResponse(loc)) return string(r) }