本文整理匯總了Golang中github.com/dustin/go-humanize.Time函數的典型用法代碼示例。如果您正苦於以下問題:Golang Time函數的具體用法?Golang Time怎麽用?Golang Time使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Time函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: getFromCache
func getFromCache(repo string) (checksResp, error) {
// try and fetch from boltdb
db, err := bolt.Open(DBPath, 0600, &bolt.Options{Timeout: 1 * time.Second})
if err != nil {
return checksResp{}, fmt.Errorf("failed to open bolt database during GET: %v", err)
}
defer db.Close()
resp := checksResp{}
err = db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(RepoBucket))
if b == nil {
return errors.New("No repo bucket")
}
cached := b.Get([]byte(repo))
if cached == nil {
return fmt.Errorf("%q not found in cache", repo)
}
err = json.Unmarshal(cached, &resp)
if err != nil {
return fmt.Errorf("failed to parse JSON for %q in cache", repo)
}
return nil
})
if err != nil {
return resp, err
}
resp.LastRefresh = resp.LastRefresh.UTC()
resp.HumanizedLastRefresh = humanize.Time(resp.LastRefresh.UTC())
return resp, nil
}
示例2: main
func main() {
var simple = flag.Bool("simple", false, "Use simple (debugging) output format")
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "usage: %s [options] <VPN ID>\n", path.Base(os.Args[0]))
flag.PrintDefaults()
}
flag.Parse()
if flag.NArg() != 1 {
flag.Usage()
os.Exit(1)
}
client, err := clcv2.NewCLIClient()
if err != nil {
exit.Fatal(err.Error())
}
vpn, err := client.GetVPN(flag.Arg(0))
if err != nil {
exit.Fatalf("failed to query VPN %s: %s", flag.Arg(0), err)
}
if *simple {
pretty.Println(vpn)
} else {
table := tablewriter.NewWriter(os.Stdout)
table.SetAutoFormatHeaders(false)
table.SetAlignment(tablewriter.ALIGN_LEFT)
table.SetAutoWrapText(false)
// table.SetHeader([]string{"CLC => Remote", "CLC Nets", "Remote", "Remote Nets", "ID", "Last Change", })
modifiedStr := humanize.Time(vpn.ChangeInfo.ModifiedDate)
// The ModifiedBy field can be an email address, or an API Key (hex string)
if _, err := hex.DecodeString(vpn.ChangeInfo.ModifiedBy); err == nil {
modifiedStr += " via API Key"
} else {
modifiedStr += ", by " + vpn.ChangeInfo.ModifiedBy
}
table.Append([]string{fmt.Sprintf("%s subnets:", vpn.Local.LocationAlias), strings.Join(vpn.Local.Subnets, ", ")})
table.Append([]string{fmt.Sprintf("%s endpoint:", vpn.Local.LocationAlias), vpn.Local.Address})
table.Append([]string{fmt.Sprintf("%s endpoint:", vpn.Remote.SiteName), vpn.Remote.Address})
table.Append([]string{fmt.Sprintf("%s subnets:", vpn.Remote.SiteName), strings.Join(vpn.Remote.Subnets, ", ")})
table.Append([]string{"IKE configuration:", fmt.Sprintf("%s, %s/%s, Key: %q, NAT traversal: %t, Lifetime: %s",
vpn.IKE.DiffieHellmanGroup,
vpn.IKE.Encryption, vpn.IKE.Hashing, vpn.IKE.PreSharedKey,
vpn.IKE.NatTraversal,
time.Duration(vpn.IKE.Lifetime)*time.Second)})
table.Append([]string{"IPsec configuration:", fmt.Sprintf("%s, %s/%s, %s, Lifetime: %s",
vpn.IPsec.Pfs, vpn.IPsec.Encryption, vpn.IPsec.Hashing,
strings.ToUpper(vpn.IPsec.Protocol), time.Duration(vpn.IPsec.Lifetime)*time.Second)})
table.Append([]string{"Last change:", modifiedStr})
table.Render()
}
}
示例3: homeHandler
func homeHandler(w http.ResponseWriter, r *http.Request) {
data.Title = "Home"
data.Posts = make([]Post, 5)
for k, v := range posts[:5] {
data.Posts[k] = *v
data.Posts[k].PrettyDate = humanize.Time(v.Date)
}
fmt.Fprint(w, mustache.RenderFileInLayout("templates/home.html.mustache", "templates/layout.html.mustache", data))
}
示例4: prettyPrintChannelStandup
func (a arriba) prettyPrintChannelStandup(cstandup channelStandup) string {
text := "¡Ándale! ¡Ándale! here's the standup status :tada:\n"
for _, userID := range cstandup.getKeysByTimestamp() {
standupMsg := cstandup[userID]
humanTime := humanize.Time(standupMsg.ts)
userName := a.getUserName(userID)
text += fmt.Sprintf("*%s*: %s _(%s)_\n", userName, standupMsg.text, humanTime)
}
return text
}
示例5: printStats
func printStats() {
statTimer := time.NewTicker(30 * time.Second)
for {
<-statTimer.C
var memstats runtime.MemStats
runtime.ReadMemStats(&memstats)
log.Printf("stats [up since: %s]\n", humanize.Time(timeStarted))
log.Printf(" - CPUTemp=%.02f deg C, MemStats.Alloc=%s, MemStats.Sys=%s, totalNetworkMessagesSent=%s\n", globalStatus.CPUTemp, humanize.Bytes(uint64(memstats.Alloc)), humanize.Bytes(uint64(memstats.Sys)), humanize.Comma(int64(totalNetworkMessagesSent)))
log.Printf(" - UAT/min %s/%s [maxSS=%.02f%%], ES/min %s/%s\n", humanize.Comma(int64(globalStatus.UAT_messages_last_minute)), humanize.Comma(int64(globalStatus.UAT_messages_max)), float64(maxSignalStrength)/10.0, humanize.Comma(int64(globalStatus.ES_messages_last_minute)), humanize.Comma(int64(globalStatus.ES_messages_max)))
log.Printf(" - Total traffic targets tracked=%s, last GPS fix: %s, GPS solution type: %d, NACp: %d, est accuracy %.02f m\n", humanize.Comma(int64(len(seenTraffic))), humanize.Time(mySituation.LastFixLocalTime), mySituation.quality, mySituation.NACp, mySituation.Accuracy)
}
}
示例6: main
func main() {
var simple = flag.Bool("simple", false, "Use simple (debugging) output format")
flag.Parse()
client, err := clcv2.NewCLIClient()
if err != nil {
exit.Fatal(err.Error())
}
vpns, err := client.GetVPNs()
if err != nil {
exit.Fatalf("failed to list VPNs: %s", err)
}
if len(vpns) == 0 {
fmt.Printf("No VPNs registered for account %s.\n", client.AccountAlias)
} else if *simple {
pretty.Println(vpns)
} else {
table := tablewriter.NewWriter(os.Stdout)
table.SetAutoFormatHeaders(false)
table.SetAlignment(tablewriter.ALIGN_LEFT)
table.SetAutoWrapText(true)
table.SetHeader([]string{"CLC => Remote", "CLC Nets",
"Remote", "Remote Nets", "ID", "Last Change",
})
for _, v := range vpns {
modifiedStr := humanize.Time(v.ChangeInfo.ModifiedDate)
// The ModifiedBy field can be an email address, or an API Key (hex string)
if _, err := hex.DecodeString(v.ChangeInfo.ModifiedBy); err == nil {
modifiedStr += " via API Key"
} else if len(v.ChangeInfo.ModifiedBy) > 6 {
modifiedStr += " by " + v.ChangeInfo.ModifiedBy[:6]
} else {
modifiedStr += " by " + v.ChangeInfo.ModifiedBy
}
table.Append([]string{
fmt.Sprintf("%s => %-15s", v.Local.LocationAlias, v.Remote.Address),
strings.Join(v.Local.Subnets, ", "),
v.Remote.SiteName,
strings.Join(v.Remote.Subnets, ", "),
v.ID,
modifiedStr,
})
}
table.Render()
}
}
示例7: prettyPrintChannelStandup
func (a arriba) prettyPrintChannelStandup(cstandup channelStandup) string {
text := "¡Ándale! ¡Ándale! here's the standup status :tada:\n"
for _, userID := range cstandup.getKeysByTimestamp() {
standupMsg := cstandup[userID]
humanTime := humanize.Time(standupMsg.ts)
userName := a.getUserName(userID)
// Inject zero-width unicode character in username to avoid notifying users
if len(userName) > 1 {
userName = string(userName[0]) + "\ufeff" + string(userName[1:])
}
text += fmt.Sprintf("*%s*: %s _(%s)_\n", userName, standupMsg.text, humanTime)
}
return text
}
示例8: OutputSignatureSuccess
func (p PgpUI) OutputSignatureSuccess(_ context.Context, arg keybase1.OutputSignatureSuccessArg) error {
signedAt := keybase1.FromTime(arg.SignedAt)
un := ColorString("bold", arg.Username)
output := func(fmtString string, args ...interface{}) {
s := fmt.Sprintf(fmtString, args...)
s = ColorString("green", s)
p.w.Write([]byte(s))
}
if signedAt.IsZero() {
output("Signature verified. Signed by %s.\n", un)
} else {
output("Signature verified. Signed by %s %s (%s).\n", un, humanize.Time(signedAt), signedAt)
}
output("PGP Fingerprint: %s.\n", arg.Fingerprint)
return nil
}
示例9: InitSystem
// InitSystem register's dice commands on module load
func InitSystem(mod *modules.Module) {
owner := &modules.OwnerPermission{}
mod.AddResponse(quitreg, func(r *modules.Response) {
r.Respond("okey, " + r.Nick + "! Goodbye everypony!")
syscall.Kill(syscall.Getpid(), syscall.SIGINT)
}, owner)
mod.AddResponse(restartreg, func(r *modules.Response) {
r.Respond("okey, " + r.Nick + "! Reebooot!")
syscall.Kill(syscall.Getpid(), syscall.SIGUSR2)
}, owner)
mod.AddResponse(joinpartreg, func(r *modules.Response) {
if r.Matches[1] == "join" {
if len(r.Matches)-1 >= 3 && r.Matches[3] != "" {
r.Server.Join("#" + r.Matches[3])
r.Respond("okey, " + r.Nick + "! let'z join " + "#" + r.Matches[3])
} else {
r.Mention("tell me where to join!")
}
} else if r.Matches[1] == "part" {
if len(r.Matches)-1 >= 3 && r.Matches[3] != "" {
r.Respond("okey, " + r.Nick + "! let'z leave " + "#" + r.Matches[3])
r.Server.Part("#" + r.Matches[3])
} else if r.Channel != "" {
r.Respond("okey, " + r.Nick + " leaving from here!")
r.Server.Part(r.Channel)
} else {
r.Mention("tell me from what to leave!")
}
}
}, owner)
mod.AddResponse(nickreg, func(r *modules.Response) {
r.Server.Nick(r.Matches[1])
r.Respond("okey, " + r.Nick + "! Let'z talk as another pony!")
}, owner)
mod.AddResponse(statsreg, func(r *modules.Response) {
mem := &runtime.MemStats{}
runtime.ReadMemStats(mem)
r.Respond("PID: " + strconv.Itoa(syscall.Getpid()) + ", last (re)start: " + human.Time(startTime) + ", sys memory: " + human.Bytes(mem.Sys))
}, owner)
}
示例10: explainDecryptionFailure
func (c *CmdDecrypt) explainDecryptionFailure(info *keybase1.SaltpackEncryptedMessageInfo) {
if info == nil {
return
}
out := c.G().UI.GetTerminalUI().ErrorWriter()
prnt := func(s string, args ...interface{}) {
fmt.Fprintf(out, s, args...)
}
if len(info.Devices) > 0 {
prnt("Decryption failed; try one of these devices instead:\n")
for _, d := range info.Devices {
t := keybase1.FromTime(d.CTime)
prnt(" * %s (%s); provisioned %s (%s)\n", ColorString("bold", d.Name), d.Type,
humanize.Time(t), t.Format("2006-01-02 15:04:05 MST"))
}
if info.NumAnonReceivers > 0 {
prnt("Additionally, there were %d hidden receivers for this message\n", info.NumAnonReceivers)
}
} else if info.NumAnonReceivers > 0 {
prnt("Decryption failed; it was encrypted for %d hidden receivers, which may or may not you\n", info.NumAnonReceivers)
} else {
prnt("Decryption failed; message wasn't encrypted for any of your known keys\n")
}
}
示例11: HumanizeTime
func HumanizeTime(then int64) string {
return humanize.Time(time.Unix(then, 0))
}
示例12: showServers
// Show condensed details of multiple servers
// @client: authenticated CLCv2 Client
// @servnames: server names
func showServers(client *clcv2.CLIClient, servnames ...string) {
var truncate = func(s string, maxlen int) string {
if len(s) >= maxlen {
s = s[:maxlen]
}
return s
}
table := tablewriter.NewWriter(os.Stdout)
table.SetAutoFormatHeaders(false)
table.SetAlignment(tablewriter.ALIGN_LEFT)
table.SetAutoWrapText(true)
table.SetHeader([]string{
"Name", "Group", "Description", "OS",
"IP", "CPU", "Mem", "Storage",
"Status", "Last Change",
})
for _, servname := range servnames {
server, err := client.GetServer(servname)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to list details of server %q: %s", servname, err)
continue
}
grp, err := client.GetGroup(server.GroupId)
if err != nil {
exit.Fatalf("failed to resolve %s group UUID: %s", servname, err)
}
IPs := []string{}
for _, ip := range server.Details.IpAddresses {
if ip.Public != "" {
IPs = append(IPs, ip.Public)
}
if ip.Internal != "" {
IPs = append(IPs, ip.Internal)
}
}
status := server.Details.PowerState
if server.Details.InMaintenanceMode {
status = "MAINTENANCE"
} else if server.Status != "active" {
status = server.Status
}
desc := server.Description
if server.IsTemplate {
desc = "TPL: " + desc
}
modifiedStr := humanize.Time(server.ChangeInfo.ModifiedDate)
/* The ModifiedBy field can be an email address, or an API Key (hex string) */
if _, err := hex.DecodeString(server.ChangeInfo.ModifiedBy); err == nil {
modifiedStr += " via API Key"
} else {
modifiedStr += " by " + truncate(server.ChangeInfo.ModifiedBy, 6)
}
// Append a tilde (~) to indicate it has snapshots
serverName := server.Name
if len(server.Details.Snapshots) > 0 {
serverName += "~"
}
table.Append([]string{
serverName, grp.Name, truncate(desc, 30), truncate(server.OsType, 15),
strings.Join(IPs, " "),
fmt.Sprint(server.Details.Cpu), fmt.Sprintf("%d G", server.Details.MemoryMb/1024),
fmt.Sprintf("%d G", server.Details.StorageGb),
status, modifiedStr,
})
}
table.Render()
}
示例13: representTimeDetailed
func (fi FileInfo) representTimeDetailed() string {
return humanize.Time(fi.f.ModTime()) + " (" + fi.f.ModTime().String() + ")"
}
示例14: newChecksResp
func newChecksResp(repo string, forceRefresh bool) (checksResp, error) {
if !forceRefresh {
resp, err := getFromCache(repo)
if err != nil {
// just log the error and continue
log.Println(err)
} else {
resp.Grade = grade(resp.Average * 100) // grade is not stored for some repos, yet
return resp, nil
}
}
// fetch the repo and grade it
err := goGet(repo, "")
if err != nil {
return checksResp{}, fmt.Errorf("could not clone repo: %v", err)
}
dir := dirName(repo)
filenames, err := check.GoFiles(dir)
if err != nil {
return checksResp{}, fmt.Errorf("could not get filenames: %v", err)
}
if len(filenames) == 0 {
return checksResp{}, fmt.Errorf("no .go files found")
}
checks := []check.Check{
check.GoFmt{Dir: dir, Filenames: filenames},
check.GoVet{Dir: dir, Filenames: filenames},
check.GoLint{Dir: dir, Filenames: filenames},
check.GoCyclo{Dir: dir, Filenames: filenames},
check.License{Dir: dir, Filenames: []string{}},
check.Misspell{Dir: dir, Filenames: filenames},
check.IneffAssign{Dir: dir, Filenames: filenames},
check.ErrCheck{Dir: dir, Filenames: filenames},
}
ch := make(chan score)
for _, c := range checks {
go func(c check.Check) {
p, summaries, err := c.Percentage()
if err != nil {
log.Printf("ERROR: (%s) %v", c.Name(), err)
}
s := score{
Name: c.Name(),
Description: c.Description(),
FileSummaries: summaries,
Weight: c.Weight(),
Percentage: p,
}
ch <- s
}(c)
}
resp := checksResp{
Repo: repo,
Files: len(filenames),
LastRefresh: time.Now().UTC(),
HumanizedLastRefresh: humanize.Time(time.Now().UTC()),
}
var total float64
var totalWeight float64
var issues = make(map[string]bool)
for i := 0; i < len(checks); i++ {
s := <-ch
resp.Checks = append(resp.Checks, s)
total += s.Percentage * s.Weight
totalWeight += s.Weight
for _, fs := range s.FileSummaries {
issues[fs.Filename] = true
}
}
total /= totalWeight
sort.Sort(ByWeight(resp.Checks))
resp.Average = total
resp.Issues = len(issues)
resp.Grade = grade(total * 100)
return resp, nil
}
示例15: representTime
func (fi FileInfo) representTime() string {
return humanize.Time(fi.f.ModTime())
}