惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Schneier on Security
有赞技术团队
有赞技术团队
T
The Blog of Author Tim Ferriss
F
Fortinet All Blogs
D
DataBreaches.Net
F
Full Disclosure
腾讯CDC
博客园 - 【当耐特】
MyScale Blog
MyScale Blog
Stack Overflow Blog
Stack Overflow Blog
小众软件
小众软件
Hugging Face - Blog
Hugging Face - Blog
Last Week in AI
Last Week in AI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
爱范儿
爱范儿
The GitHub Blog
The GitHub Blog
Engineering at Meta
Engineering at Meta
大猫的无限游戏
大猫的无限游戏
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
S
SegmentFault 最新的问题
The Register - Security
The Register - Security
WordPress大学
WordPress大学
博客园 - 聂微东
雷峰网
雷峰网
J
Java Code Geeks
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
P
Privacy International News Feed
酷 壳 – CoolShell
酷 壳 – CoolShell
A
Arctic Wolf
Scott Helme
Scott Helme
C
Cyber Attacks, Cyber Crime and Cyber Security
T
Tor Project blog
博客园 - 三生石上(FineUI控件)
Know Your Adversary
Know Your Adversary
AWS News Blog
AWS News Blog
G
Google Developers Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
C
CERT Recently Published Vulnerability Notes
O
OpenAI News
Project Zero
Project Zero
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Application and Cybersecurity Blog
Application and Cybersecurity Blog
云风的 BLOG
云风的 BLOG
N
News and Events Feed by Topic
MongoDB | Blog
MongoDB | Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Microsoft Security Blog
Microsoft Security Blog
Cisco Talos Blog
Cisco Talos Blog
P
Palo Alto Networks Blog
Schneier on Security
Schneier on Security

博客园 - Net205 Blog

我们怎么做不到呢? Top 7 Coding Standards & Guideline Documents For C#/.NET Developers .Net开发人员必须避免的5个常见的编程错误 You are doing Scrum but the Scrum Master tells the team what to do! Asp.net Mvc中使用HTML 5 data属性 使用扩展方法 使用Javascript制作一个始终可见的区域 阅读优秀代码是提高开发人员修为的一种捷径[收藏] SQL SERVER – Difference between COUNT(DISTINCT) vs COUNT(ALL) SQL Performance MSSQL删除重复数据 jQuery QUnit 万月薪的英语人是如何练成的!!!讲一口漂亮流利的英语[转] 博文阅读密码验证 - 博客园 博文阅读密码验证 - 博客园 asp.net Interview Questions - Net205 Blog jQuery资源 strip invalid xml characters - Net205 Blog 翻译工具,您选哪个?
我第1个可用的golang小程序
Net205 Blog · 2014-04-24 · via 博客园 - Net205 Blog
package main

import (
  "bitbucket.org/kardianos/service"
  "bitbucket.org/kardianos/osext"
  "encoding/xml"
  "errors"
  "fmt"
  "io"
  "io/ioutil"
  "net/http"
  "os"
  "os/exec"
  "time"
)

var log service.Logger

func main() {
  var name = "SyncSystemTimeService"
  var displayName = "Sync System Time Service"
  var desc = "同步更新window时间服务(通过网络获取最新时间)"

  var s, err = service.NewService(name, displayName, desc)
  log = s

  if err != nil {
    fmt.Printf("%s unable to start: %s", displayName, err)
    return
  }
  if len(os.Args) > 1 {
    var err error
    verb := os.Args[1]

    switch verb {
      case "install":
        err = s.Install()
        if err != nil {
          fmt.Printf("Failed to install: %s\n", err)
          return
        }
        fmt.Printf("Service \"%s\" installed.\n", displayName)
      case "remove":
        err = s.Remove()
        if err != nil {
          fmt.Printf("Failed to remove: %s\n", err)
          return
        }
        fmt.Printf("Service \"%s\" removed.\n", displayName)
      case "run":
        DoWork()
      case "start":
        err = s.Start()
        if err != nil {
          fmt.Printf("Failed to start: %s\n", err)
          return
        }
        fmt.Printf("Service \"%s\" started.\n", displayName)
      case "stop":
        err = s.Stop()
        if err != nil {
          fmt.Printf("Failed to stop: %s\n", err)
          return
        }
        fmt.Printf("Service \"%s\" stopped.\n", displayName)
    }
    return
  }

  err = s.Run(func() error {
    go DoWork()
    return nil
  }, func() error {
    StopWork()
    return nil
  })

  if err != nil {
    s.Error(err.Error())
  }
}

func DoWork() {
  log.Info("I'm Running!")

  const defaultSchedulingTime = "30m" // minutes
  schedulingTime := defaultSchedulingTime
  configFile := "config.txt"
  configPath, err := osext.ExecutableFolder()
  if err != nil {
    log.Warning(err.Error())
  } else {
    configFile = configPath + configFile
  }
  log.Info(configFile)

  timeConfig, err := ioutil.ReadFile(configFile)
  if err == nil {
    schedulingTime = string(timeConfig)
  } else {
    log.Warning(err.Error())
  }
  timeDuration, err := time.ParseDuration(schedulingTime)
  if err != nil {
    log.Warning(err.Error())
    timeDuration, err = time.ParseDuration(defaultSchedulingTime)
  }

  Go()
  timer := time.NewTicker(timeDuration)
  for {
    select {
      case <-timer.C:
      Go()
    }
  }
  select {}
}

func StopWork() {
  log.Info("I'm Stopping!")
}

func Go() {
  networkTime := GetNetworkTime()
  SetSystemTime(networkTime)
}

/**
<timezone xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.earthtools.org/timezone.xsd">
 <version>1.0</version>
 <location>
  <latitude>35.86166</latitude>
  <longitude>104.195397</longitude>
 </location>
 <offset>8</offset>
 <suffix>H</suffix>
 <localtime>21 Apr 2014 23:08:09</localtime>
 <isotime>2014-04-21 23:08:09 +0800</isotime>
 <utctime>2014-04-21 15:08:09</utctime>
 <dst>Unknown</dst>
</timezone>
*/
type Timezone struct {
  LocalTime string `xml:"localtime"`
  IsoTime string `xml:"isotime"`
  UtcTime string `xml:"utctime"`
}

func charsetReader(charset string, r io.Reader) (io.Reader, error) {
  if charset == "ISO-8859-1" || charset == "iso-8859-1" {
    return r, nil
  }
  return nil, errors.New("Unsupported character set encoding: " + charset)
}

func GetNetworkTime() string {
  const web_service_url = "http://www.earthtools.org/timezone-1.1/35.86166/104.195397"
  result, err1 := http.Get(web_service_url)
  if err1 != nil {
    log.Warning(err1.Error())
    return ""
  }
  defer result.Body.Close()

  var timezone Timezone
  data := xml.NewDecoder(result.Body)
  data.CharsetReader = charsetReader
  if err := data.Decode(&timezone); err != nil {
    return ""
  }

  // fmt.Println(timezone.UtcTime)
  return timezone.UtcTime
}

func SetSystemTime(dateTime string) {
  if dateTime == "" {
    return
  }

  currentTime := time.Now().Format("2006-01-02 15:04:05")
  logContent := currentTime
  convertTime, err1 := time.Parse("2006-01-02 15:04:05", dateTime)
  if err1 != nil {
    log.Warning(err1.Error())
    return
  }

  convertTime = convertTime.Add(8 * time.Hour)
  logContent = logContent + " --> " + convertTime.Format("2006-01-02 15:04:05")
  compareValue := convertTime.Format("2006-01-02 15:04:05")
  // 如果时间(年月日时分)相同,则不更新
  if currentTime[0:len(currentTime)-3] == compareValue[0:len(compareValue)-3] {
    log.Info("same time, not to update: " + currentTime + " | " + compareValue)
    return
  }

  _, err2 := exec.Command("CMD", "/C", "DATE", convertTime.Format("2006-01-02")).Output()
  if err2 != nil {
    log.Error(err2.Error())
  }
  _, err2 = exec.Command("CMD", "/C", "TIME", convertTime.Format("15:04:05")).Output()
  if err2 != nil {
    log.Error(err2.Error())
  }
  currentTime = time.Now().Format("2006-01-02 15:04:05")
  logContent = logContent + " --> " + currentTime
  log.Info(logContent)
  // WriteLogFile(logContent)
}

/*
func WriteLogFile(logContent string) error {
  fileName := "log.txt"
  file, err := os.OpenFile(fileName, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
  if err != nil {
    log.Fatal("error opening file: %v", err)
    return err
  }
  defer file.Close()

  log.SetOutput(file)
  log.Println(logContent)
  return nil
}
*/