Skip to content

Instantly share code, notes, and snippets.

@leiless
Last active February 22, 2024 06:20
Show Gist options
  • Save leiless/57097a758b68ae7c9f8b2bf312bd2632 to your computer and use it in GitHub Desktop.
Save leiless/57097a758b68ae7c9f8b2bf312bd2632 to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
func todayDate() time.Time {
t := time.Now().Local()
return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
}
var httpClient = http.Client{
Timeout: 10 * time.Second,
}
func isHoliday() (bool, error) {
today := todayDate()
yymmdd := fmt.Sprintf("%04d-%02d-%02d", today.Year(), today.Month(), today.Day())
url := fmt.Sprintf("https://timor.tech/api/holiday/info/%v", yymmdd)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return false, err
}
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
resp, err := httpClient.Do(req)
if err != nil {
return false, fmt.Errorf("GET %v: %w", url, err)
}
defer resp.Body.Close()
data, _ := io.ReadAll(resp.Body)
if resp.StatusCode/100 != 2 {
return false, fmt.Errorf("GET %v: %v: %v", url, resp.StatusCode, string(data))
}
m := make(map[string]interface{})
if err := json.Unmarshal(data, &m); err != nil {
return false, fmt.Errorf("holiday: unmarshal JSON response: %w", err)
}
if m["code"].(float64) != 0 {
return false, fmt.Errorf("GET %v: code is %v", url, m["code"])
}
if m["holiday"] != nil {
h := m["holiday"].(map[string]interface{})
v, ok := h["holiday"]
return ok && v.(bool), nil
}
return false, nil
}
func main() {
is, err := isHoliday()
fmt.Printf("%v %v\n", is, err)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment