timezone.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package timezone
  2. import (
  3. "encoding/json"
  4. "io/ioutil"
  5. "net/http"
  6. "os/exec"
  7. "runtime"
  8. "strings"
  9. "time"
  10. )
  11. /*
  12. (The Original) System Time & Date Services
  13. This module handle updates and setup of the current system time and date
  14. (Add more helpful comments here)
  15. Original author: alanyeung
  16. Migrated to go module from main scope by tobychui
  17. TODO: timezone problems.
  18. */
  19. //returnFormat shoulbn't be exported
  20. type returnFormat struct {
  21. Time string `json:"time"`
  22. Timezone string `json:"timezone"`
  23. }
  24. //WindowsTimeZoneStruct shouldn't be exported.
  25. type WindowsTimeZoneStruct struct {
  26. SupplementalData struct {
  27. Version struct {
  28. Number string `json:"_number"`
  29. } `json:"version"`
  30. WindowsZones struct {
  31. MapTimezones struct {
  32. MapZone []struct {
  33. Other string `json:"_other"`
  34. Territory string `json:"_territory"`
  35. Type string `json:"_type"`
  36. } `json:"mapZone"`
  37. OtherVersion string `json:"_otherVersion"`
  38. TypeVersion string `json:"_typeVersion"`
  39. } `json:"mapTimezones"`
  40. } `json:"windowsZones"`
  41. } `json:"supplementalData"`
  42. }
  43. func ShowTime(w http.ResponseWriter, r *http.Request) {
  44. now := time.Now() // current local time
  45. Timezone := ""
  46. if runtime.GOOS == "linux" {
  47. cmd := exec.Command("timedatectl", "show", "-p", "Timezone")
  48. out, _ := cmd.CombinedOutput()
  49. outString := string(out)
  50. outString = strings.SplitN(outString, "=", 2)[1]
  51. Timezone = outString
  52. } else if runtime.GOOS == "windows" {
  53. cmd := exec.Command("tzutil", "/g")
  54. out, _ := cmd.CombinedOutput()
  55. outString := string(out)
  56. Timezone = ConvertWinTZtoLinuxTZ(outString)
  57. } else if runtime.GOOS == "darwin" {
  58. //no support, just ease my debugging
  59. Timezone = "America/Los_Angeles"
  60. }
  61. returnStruct := returnFormat{
  62. Time: now.Format(time.RFC3339),
  63. Timezone: Timezone,
  64. }
  65. returnString, _ := json.Marshal(returnStruct)
  66. sendJSONResponse(w, string(returnString))
  67. }
  68. func ConvertWinTZtoLinuxTZ(WinTZ string) string {
  69. file, _ := ioutil.ReadFile("./system/time/wintz.json")
  70. WinTZLinuxTz := WindowsTimeZoneStruct{}
  71. json.Unmarshal([]byte(file), &WinTZLinuxTz)
  72. for _, data := range WinTZLinuxTz.SupplementalData.WindowsZones.MapTimezones.MapZone {
  73. if data.Other == WinTZ {
  74. LinuxTZ := strings.SplitN(data.Type, " ", 2)[0]
  75. return LinuxTZ
  76. }
  77. }
  78. return ""
  79. }