main.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package main
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "os"
  7. "time"
  8. "git.red-green.com/david/astruct"
  9. )
  10. func main() {
  11. var err error
  12. _, err = os.Stat("output.go")
  13. if err != nil {
  14. if !errors.Is(err, os.ErrNotExist) {
  15. fmt.Println("Err:", err)
  16. return
  17. }
  18. var a *astruct.Astruct = astruct.NewAstruct("Weather")
  19. err = a.ReadFile("test.json")
  20. if err != nil {
  21. fmt.Println("Err:", err)
  22. return
  23. }
  24. fmt.Println("MapLikes:")
  25. for name, m := range a.MapLikes {
  26. if name == "" {
  27. continue
  28. }
  29. fmt.Printf("%s\n", name)
  30. for k, v := range m {
  31. fmt.Printf(" '%s' = %s\n", k, v.String())
  32. }
  33. }
  34. fmt.Println("ArrayLikes:")
  35. for name, a := range a.ArrayLikes {
  36. if name == "" {
  37. continue
  38. }
  39. fmt.Printf("%s\n", name)
  40. for i, v := range a {
  41. fmt.Printf(" %d = %s\n", i, v.String())
  42. }
  43. }
  44. err = a.WriteFile("output.go", "main", 0666)
  45. if err != nil {
  46. fmt.Println("Err:", err)
  47. return
  48. }
  49. }
  50. // --- Test unmarshaling our new go code ---
  51. var (
  52. pay []byte
  53. data Weather
  54. )
  55. pay, err = os.ReadFile("test.json")
  56. if err != nil {
  57. fmt.Println("Err:", err)
  58. return
  59. }
  60. err = json.Unmarshal(pay, &data)
  61. if err != nil {
  62. fmt.Println("Err:", err)
  63. return
  64. }
  65. fmt.Println("Weather Report:")
  66. fmt.Printf("%s, %s\n", data.Name, data.Sys.Country)
  67. fmt.Printf("lon %0.4f, lat %0.4f\n", data.Coord.Lon, data.Coord.Lat)
  68. fmt.Printf("Currently %s with %0.0f%% cload coverage\n", data.Weather[0].Description, data.Clouds.All)
  69. fmt.Printf("Wind of %0.1f MPH with gusts of upto %0.1f MPH\n", data.Wind.Speed, data.Wind.Gust)
  70. fmt.Printf("It feels like %0.1f F, Low is %0.1f F with a high of %0.1f F\n", data.Main.Feels_like, data.Main.Temp_min, data.Main.Temp_max)
  71. fmt.Printf("Humidity of %0.0f%%\n", data.Main.Humidity)
  72. at := time.Unix(data.Dt, 0).Round(time.Second)
  73. fmt.Printf("This report was generated on %s\n", at.Format(time.UnixDate))
  74. rise := time.Unix(data.Sys.Sunrise, 0).Round(time.Second)
  75. set := time.Unix(data.Sys.Sunset, 0).Round(time.Second)
  76. fmt.Printf("Sun rise at %s\n", rise.Format("03:04:05PM"))
  77. fmt.Printf("Sun set at %s\n", set.Format("03:04:05PM"))
  78. }