Skip to content

Instantly share code, notes, and snippets.

@M0rais
Last active March 6, 2025 19:20
Show Gist options
  • Select an option

  • Save M0rais/4fea0b5e8e5fc4b98a036b9d78ea4152 to your computer and use it in GitHub Desktop.

Select an option

Save M0rais/4fea0b5e8e5fc4b98a036b9d78ea4152 to your computer and use it in GitHub Desktop.
small get time api using mux
package app
import (
"github.com/gorilla/mux"
"log"
"net/http"
)
func Start() {
route := mux.NewRouter()
//routes
route.HandleFunc("/api/time", getTime).Methods("GET")
//start
log.Fatal(http.ListenAndServe(":8080", route))
}
module github.com/m0rais/time
go 1.23
require github.com/gorilla/mux v1.8.1 // indirect
package app
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
)
func getTime(writer http.ResponseWriter, request *http.Request) {
tz := request.URL.Query().Get("tz")
if tz == "" {
currentTime := time.Now().UTC()
fmt.Fprint(writer, currentTime.Format(time.RFC1123))
return
}
response := make(map[string]string)
for _, zone := range strings.Split(tz, ",") {
location, err := time.LoadLocation(zone)
if err != nil {
writer.WriteHeader(http.StatusNotFound)
fmt.Fprint(writer, zone)
return
}
response[zone] = time.Now().In(location).Format(time.RFC1123)
}
writer.Header().Set("Content-Type", "application/json")
json.NewEncoder(writer).Encode(response)
}
package main
import "github.com/m0rais/time/app"
func main() {
app.Start()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment