Last active
March 6, 2025 19:20
-
-
Save M0rais/4fea0b5e8e5fc4b98a036b9d78ea4152 to your computer and use it in GitHub Desktop.
small get time api using mux
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)) | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module github.com/m0rais/time | |
| go 1.23 | |
| require github.com/gorilla/mux v1.8.1 // indirect |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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