You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
1.9 KiB

2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "html/template"
  6. "net/http"
  7. "os"
  8. "time"
  9. )
  10. type Element struct {
  11. Humidity float64 `json:"humidity"`
  12. Weather []Weather `json:"weather"`
  13. }
  14. type Weather struct {
  15. Id int `json:"id"`
  16. Main string `json:"main"`
  17. Description string `json:"description"`
  18. Icon string `json:"icon"`
  19. }
  20. type OneCall struct {
  21. Date string
  22. Current struct {
  23. Element
  24. DateUnix CurrentDate `json:"dt"`
  25. Sunrise Hour `json:"sunrise"`
  26. Sunset Hour `json:"sunset"`
  27. Temp Temperature `json:"temp"`
  28. } `json:"current"`
  29. Hourly []struct {
  30. Element
  31. DateUnix HourOnly `json:"dt"`
  32. Temp Temperature `json:"temp"`
  33. } `json:"hourly"`
  34. Daily []struct {
  35. Element
  36. DateUnix Day `json:"dt"`
  37. Temp struct {
  38. Day Temperature `json:"day"`
  39. Min Temperature `json:"min"`
  40. Max Temperature `json:"max"`
  41. } `json:"temp"`
  42. } `json:"daily"`
  43. }
  44. func getOneCall(api string) (*OneCall, error) {
  45. r, err := http.Get("https://api.openweathermap.org/data/2.5/onecall?lat=27.98&lon=86.92&exclude=minutely,alerts&units=metric&appid=" + api)
  46. if err != nil {
  47. return nil, err
  48. }
  49. defer r.Body.Close()
  50. var d *OneCall
  51. err = json.NewDecoder(r.Body).Decode(&d)
  52. if err != nil {
  53. return nil, err
  54. }
  55. d.Date = time.Time(d.Current.DateUnix).Format("2006-01-02, 15:04:05")
  56. return d, nil
  57. }
  58. func main() {
  59. if len(os.Args) != 3 {
  60. fmt.Println("need an openwathermap.org API key as arg & port")
  61. os.Exit(0)
  62. }
  63. apiKey := os.Args[1]
  64. port := os.Args[2]
  65. tmpl := template.Must(template.ParseFiles("template.html"))
  66. fs := http.FileServer(http.Dir("icons"))
  67. http.Handle("/icons/", http.StripPrefix("/icons/", fs))
  68. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  69. data, err := getOneCall(apiKey)
  70. if err != nil {
  71. panic(err)
  72. }
  73. tmpl.Execute(w, data)
  74. })
  75. fmt.Println("serving at :" + port)
  76. http.ListenAndServe(":"+port, nil)
  77. }