Timestamp microservice
User stories
- I can pass a string as a parameter, and it will check to see whether that string contains either a unix timestamp or a natural language date (example: January 1, 2016)
- If it does, it returns both the Unix timestamp and the natural language form of that date.
- If it does not contain a date or Unix timestamp, it returns null for those properties.
Example usage
/api/time/December%2015,%202015
/api/time/1450137600
Example output
{ "unix": 1450137600, "natural": "December 15, 2015" }
Solution
package main
import (
"encoding/json"
"log"
"net/http"
"strconv"
"time"
"github.com/gorilla/mux"
)
var dateFormats = []string{
"January 2 2006",
"Jan 2 2006",
"2 Jan 2006",
"2 January 2006",
"January 2, 2006",
"Jan 2, 2006",
"2 Jan, 2006",
"2 January, 2006",
"2006 January 2",
"2006 Jan 2",
"2006 2 Jan",
"2006 2 January",
"2006, January 2",
"2006, Jan 2",
"2006, 2 Jan",
"2006, 2 January",
}
type response struct {
Unix string `json:"unix,omitempty"`
Natural string `json:"natural,omitempty"`
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/api/time/{date}", handleString).Methods("GET")
log.Fatal(http.ListenAndServe(":8000", r))
}
func handleString(w http.ResponseWriter, r *http.Request) {
enc := json.NewEncoder(w)
date := mux.Vars(r)["date"]
i, err := strconv.ParseInt(date, 10, 64)
if err == nil {
tm := time.Unix(i, 0)
enc.Encode(response{
Unix: date,
Natural: tm.Format("January 2, 2006"),
})
return
}
var resp response
for _, dateFormat := range dateFormats {
if tm, err := time.Parse(dateFormat, date); err == nil {
resp = response{
Unix: strconv.FormatInt(tm.UTC().Unix(), 10),
Natural: tm.Format("January 2, 2006"),
}
}
}
enc.Encode(resp)
}