func (ws *Webservice) handler_logdata_delete(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) var counter nodedb.Counter switch vars["id"] { case "clients": counter = &nodedb.CountMeshClients{} case "nodes": counter = &nodedb.CountMeshNodes{} default: counter = &nodedb.CountNodeClients{Node: vars["id"]} } var timestamp time.Time err := timestamp.UnmarshalText([]byte(vars["timestamp"])) if err != nil { http.Error(w, "Bad Request", 400) return } counter.SetTimestamp(timestamp) err = ws.db.Logs.Update(func(tx *bolt.Tx) error { return ws.db.Logs.Delete(tx, counter) }) if err != nil { http.Error(w, "Not Found", 404) return } w.Header().Set("Content-type", "application/json") ws.db.GenerateLogJSON(w, counter) }
func UnmarshalTime(data []byte) (time.Time, error) { // example unix time: 1046509689.525204000 // example time.Time: 2003-03-01T09:08:09.525204Z // first try RFC 3339 format var t time.Time err := t.UnmarshalText(data) if err == nil { return t, err } // next try Unix timestamp with and without ns precision s := strings.Split(string(data[:]), ".") if len(s) > 2 { return time.Time{}, fmt.Errorf("not a valid timestamp") } sec, err := strconv.ParseInt(s[0], 10, 64) var nsec int64 = 0 if len(s) == 2 { nsec, err = strconv.ParseInt(s[1], 10, 64) } return time.Unix(sec, nsec), err }
func (store *fileStore) populateCache() (creationTimePopulated bool, err error) { if tmpHeaderFile, err := os.Open(store.headerFname); err == nil { defer tmpHeaderFile.Close() for { var seqNum, size int var offset int64 if cnt, err := fmt.Fscanf(tmpHeaderFile, "%d,%d,%d\n", &seqNum, &offset, &size); err != nil || cnt != 3 { break } store.offsets[seqNum] = msgDef{offset: offset, size: size} } } if timeBytes, err := ioutil.ReadFile(store.sessionFname); err == nil { var ctime time.Time if err := ctime.UnmarshalText(timeBytes); err == nil { store.cache.creationTime = ctime creationTimePopulated = true } } if senderSeqNumBytes, err := ioutil.ReadFile(store.senderSeqNumsFname); err == nil { if senderSeqNum, err := strconv.Atoi(string(senderSeqNumBytes)); err == nil { store.cache.SetNextSenderMsgSeqNum(senderSeqNum) } } if targetSeqNumBytes, err := ioutil.ReadFile(store.targetSeqNumsFname); err == nil { if targetSeqNum, err := strconv.Atoi(string(targetSeqNumBytes)); err == nil { store.cache.SetNextTargetMsgSeqNum(targetSeqNum) } } return creationTimePopulated, nil }
// UnmarshalText unmarshals the data from a text format. func (v *Time) UnmarshalText(text []byte) error { var t time.Time if err := t.UnmarshalText(text); err != nil { // Try parsing without timezone since that is a valid format if t, err = time.Parse("2006-01-02T15:04:05", string(text)); err != nil { return err } } v.Time = t return nil }
func (m *baseModel) getLastUpdated(id string, conn redis.Conn) (*time.Time, error) { timeString, err := redis.String(conn.Do("HGET", m.idType+"s:updated", id)) if err != nil || timeString == "" { return nil, err } t := time.Time{} err = t.UnmarshalText([]byte(timeString)) return &t, err }
func getDefaultServer() *Server { f07, f08 := int16(8), float64(9) f09, f10 := "ankara", []string{"tr", "en"} f12 := 6 * time.Second f12_0, f12_1, f12_2 := time.Millisecond, 2*time.Minute, 3*time.Hour f15_f01_0, f15_f01_1 := uint16(10), uint16(20) date := time.Time{} if err := date.UnmarshalText([]byte("2015-11-05T08:15:30-05:00")); err != nil { log.Fatalln(err) } return &Server{ Name: "koding", Port: 6060, Enabled: true, ID: 1234567890, Labels: []int{123, 456}, Users: []string{"ankara", "istanbul"}, Interval: 10 * time.Second, Postgres: Postgres{ Enabled: true, Port: 5432, Hosts: []string{"192.168.2.1", "192.168.2.2", "192.168.2.3"}, DBName: "configdb", AvailabilityRatio: 8.23, }, F00: 1, F01: int8(2), F02: int16(3), F03: int32(4), F04: int64(5), F05: uint32(6), F06: float32(7.3), F07: &f07, F08: &f08, F09: &f09, F10: &f10, F11: &f12, F12: &[]*time.Duration{&f12_0, &f12_1, &f12_2}, F13: 12, F14: date, F15: CustomStruct{ F00: "turkey", F01: []*uint16{&f15_f01_0, &f15_f01_1}, }, F16: &CustomStruct{ F00: "turkey", F01: []*uint16{&f15_f01_0, &f15_f01_1}, }, } }
func (a *ActivityLogger) Seen(u string) (time.Time, error) { t := time.Time{} s, err := a.store.GetVal("seen", u) if err != nil { log.Println("GetVal Error") return t, err } if err := t.UnmarshalText([]byte(s)); err != nil { return t, err } return t, nil }
// Time type asserts to `time.Time` func (j *Json) Time(path ...interface{}) (time.Time, error) { var t time.Time tmp, err := j.Get(path...) if err != nil { return t, err } if t, ok := tmp.data.(time.Time); ok { return t, nil } else if tStr, ok := tmp.data.(string); ok { if t.UnmarshalText([]byte(tStr)) == nil { return t, nil } } return t, errors.New("type assertion/unmarshalling to time.Time failed") }
func handleList(ctx *cli.Context, client *daemon.Client) error { path := "/" if ctx.NArg() > 0 { path = prefixSlash(ctx.Args().First()) } depth := ctx.Int("depth") if ctx.Bool("recursive") { depth = -1 } entries, err := client.List(path, depth) if err != nil { return ExitCode{ UnknownError, fmt.Sprintf("ls: %v", err), } } for _, entry := range entries { modTime := time.Time{} if err := modTime.UnmarshalText(entry.ModTime); err != nil { log.Warningf("Could not parse mtime (%s): %v", entry.ModTime, err) continue } fmt.Printf( "%s\t%s\t%s\n", colors.Colorize( humanize.Bytes(uint64(entry.NodeSize)), colors.Green, ), colors.Colorize( humanize.Time(modTime), colors.Cyan, ), colors.Colorize( entry.Path, colors.Magenta, ), ) } return nil }
// Time extracts duration expressed as in RFC 3339 format func Time(name string, out *time.Time, predicates ...Predicate) Param { return func(r *http.Request) error { for _, p := range predicates { if err := p.Pass(name, r); err != nil { return err } } v := r.Form.Get(name) if v == "" { return nil } var t time.Time if err := t.UnmarshalText([]byte(v)); err != nil { return &BadParameterError{Param: name, Message: err.Error()} } *out = t return nil } }
func (q *Queryable) TimeT() (time.Time, error) { fvv := fv(q.Raw) switch fvv.Kind() { case reflect.String: t := time.Time{} err := t.UnmarshalText([]byte(fvv.String())) return t, err case reflect.Uint: return time.Unix(int64(fvv.Uint()), 0), nil case reflect.Int: return time.Unix(fvv.Int(), 0), nil case reflect.Struct: t, ok := q.Raw.(time.Time) if ok { return t, nil } } return time.Time{}, ne("not a valid time object " + fvv.Kind().String()) }
func (i *IDB) initLastUpdated(m Model) error { if !i.lastUpdated.IsZero() { return nil } ch := make(chan error) db := i.db t := m.Type() tr := db.Call("transaction", t.Name(), "readonly") s := tr.Call("objectStore", t.Name()) idx := s.Call("index", lastUpdatedIndex) req := idx.Call("openCursor", nil, "prev") req.Set("onsuccess", func(e js.Object) { maxLastUpdated := time.Time{} cursor := e.Get("target").Get("result") if !cursor.IsNull() { value := cursor.Get("value") l := value.Get("Meta").Get("LastUpdated").Str() if err := maxLastUpdated.UnmarshalText([]byte(l)); err != nil { go func() { ch <- err close(ch) }() return } if i.lastUpdated.Before(maxLastUpdated) { i.lastUpdated = maxLastUpdated } } close(ch) }) req.Set("onerror", func(e js.Object) { go func() { ch <- toError(e.Get("target")) close(ch) }() }) return <-ch }
func (m *baseModel) getSyncManifest(conn redis.Conn) (*SyncManifest, error) { var manifest SyncManifest = make(map[string]int64) item, err := redis.Strings(conn.Do("HGETALL", m.idType+"s:updated")) for i := 0; i < len(item); i += 2 { t := time.Time{} err := t.UnmarshalText([]byte(item[i+1])) if err != nil { return nil, err } manifest[item[i]] = t.UnixNano() / int64(time.Millisecond) } if err != nil { return nil, err } return &manifest, nil }
func (sc *serveConn) attrFromFile(file drive_db.File) fuse.Attr { var atime, mtime, crtime time.Time if err := atime.UnmarshalText([]byte(file.LastViewedByMeDate)); err != nil { atime = startup } if err := mtime.UnmarshalText([]byte(file.ModifiedDate)); err != nil { mtime = startup } if err := crtime.UnmarshalText([]byte(file.CreatedDate)); err != nil { crtime = startup } blocks := file.FileSize / int64(blockSize) if r := file.FileSize % int64(blockSize); r > 0 { blocks += 1 } attr := fuse.Attr{ Valid: *driveMetadataLatency, Inode: file.Inode, Atime: atime, Mtime: mtime, Ctime: mtime, Crtime: crtime, Uid: sc.uid, Gid: sc.gid, Mode: 0755, Size: uint64(file.FileSize), Blocks: uint64(blocks), } if file.MimeType == driveFolderMimeType { attr.Mode = os.ModeDir | 0755 } return attr }
func decodeRecordData(data recordData) (*Record, error) { fields := make(map[string]interface{}) rec := &Record{0, -1, fields} for key, v := range data { switch v.Type { case FT_SINGLE_LINE_TEXT: fields[key] = SingleLineTextField(v.Value.(string)) case FT_MULTI_LINE_TEXT: fields[key] = MultiLineTextField(v.Value.(string)) case FT_RICH_TEXT: fields[key] = RichTextField(v.Value.(string)) case FT_DECIMAL: fields[key] = DecimalField(v.Value.(string)) case FT_CALC: fields[key] = CalcField(v.Value.(string)) case FT_CHECK_BOX: fields[key] = CheckBoxField(stringList(v.Value.([]interface{}))) case FT_RADIO: if v.Value == nil { fields[key] = RadioButtonField("") } else { fields[key] = RadioButtonField(v.Value.(string)) } case FT_SINGLE_SELECT: if v.Value == nil { fields[key] = SingleSelectField{Valid: false} } else { fields[key] = SingleSelectField{v.Value.(string), true} } case FT_MULTI_SELECT: fields[key] = MultiSelectField(stringList(v.Value.([]interface{}))) case FT_FILE: b1, err := json.Marshal(v.Value) if err != nil { return nil, err } var fl []File err = json.Unmarshal(b1, &fl) if err != nil { return nil, err } fields[key] = FileField(fl) case FT_LINK: fields[key] = LinkField(v.Value.(string)) case FT_DATE: if v.Value == nil { fields[key] = DateField{Valid: false} } else { d, err := time.Parse("2006-01-02", v.Value.(string)) if err != nil { return nil, fmt.Errorf("Invalid date: %v", v.Value) } fields[key] = DateField{d, true} } case FT_TIME: if v.Value == nil { fields[key] = TimeField{Valid: false} } else { t, err := time.Parse("15:04", v.Value.(string)) if err != nil { t, err = time.Parse("15:04:05", v.Value.(string)) if err != nil { return nil, fmt.Errorf("Invalid time: %v", v.Value) } } fields[key] = TimeField{t, true} } case FT_DATETIME: if v.Value == "" { fields[key] = DateTimeField{Valid: false} } else { if s, ok := v.Value.(string); ok { dt, err := time.Parse(time.RFC3339, s) if err != nil { return nil, fmt.Errorf("Invalid datetime: %v", v.Value) } fields[key] = DateTimeField{dt, true} } } case FT_USER: ul, err := userList(v.Value.([]interface{})) if err != nil { return nil, err } fields[key] = UserField(ul) case FT_ORGANIZATION: ol, err := organizationList(v.Value.([]interface{})) if err != nil { return nil, err } fields[key] = OrganizationField(ol) case FT_GROUP: gl, err := groupList(v.Value.([]interface{})) if err != nil { return nil, err } fields[key] = GroupField(gl) case FT_CATEGORY: fields[key] = CategoryField(stringList(v.Value.([]interface{}))) case FT_STATUS: fields[key] = StatusField(v.Value.(string)) case FT_ASSIGNEE: al, err := userList(v.Value.([]interface{})) if err != nil { return nil, err } fields[key] = AssigneeField(al) case FT_RECNUM: if nid, err := numericId(v.Value.(string)); err != nil { return nil, err } else { rec.id = nid } fields[key] = RecordNumberField(v.Value.(string)) case FT_CREATOR: creator := v.Value.(map[string]interface{}) fields[key] = CreatorField{ creator["code"].(string), creator["name"].(string), } case FT_CTIME: var ctime time.Time if ctime.UnmarshalText([]byte(v.Value.(string))) != nil { return nil, fmt.Errorf("Invalid datetime: %v", v.Value) } fields[key] = CreationTimeField(ctime) case FT_MODIFIER: modifier := v.Value.(map[string]interface{}) fields[key] = ModifierField{ modifier["code"].(string), modifier["name"].(string), } case FT_MTIME: var mtime time.Time if mtime.UnmarshalText([]byte(v.Value.(string))) != nil { return nil, fmt.Errorf("Invalid datetime: %v", v.Value) } fields[key] = CreationTimeField(mtime) case FT_SUBTABLE: b2, err := json.Marshal(v.Value) if err != nil { return nil, err } var stl []SubTableEntry err = json.Unmarshal(b2, &stl) if err != nil { return nil, err } ra := make([]*Record, len(stl)) for i, sr := range stl { b3, err := json.Marshal(sr.Value) if err != nil { return nil, err } var rd recordData err = json.Unmarshal(b3, &rd) if err != nil { return nil, err } r, err := decodeRecordData(recordData(rd)) if err != nil { return nil, err } id, err := strconv.ParseUint(sr.Id, 10, 64) if err != nil { return nil, err } r.id = id ra[i] = r } fields[key] = SubTableField(ra) case FT_ID: id, err := strconv.ParseUint(v.Value.(string), 10, 64) if err != nil { return nil, fmt.Errorf("Invalid record ID: %v", v.Value) } rec.id = id case FT_REVISION: revision, err := strconv.ParseInt(v.Value.(string), 10, 64) if err != nil { return nil, fmt.Errorf("Invalid revision number: %v", v.Value) } rec.revision = revision default: log.Printf("Unknown type: %v", v.Type) } } return rec, nil }
func TestUnmarshalSuccessfulResponse(t *testing.T) { var expiration time.Time expiration.UnmarshalText([]byte("2015-04-07T04:40:23.044979686Z")) tests := []struct { hdr string body string wantRes *Response wantErr bool }{ // Neither PrevNode or Node { hdr: "1", body: `{"action":"delete"}`, wantRes: &Response{Action: "delete", Index: 1}, wantErr: false, }, // PrevNode { hdr: "15", body: `{"action":"delete", "prevNode": {"key": "/foo", "value": "bar", "modifiedIndex": 12, "createdIndex": 10}}`, wantRes: &Response{ Action: "delete", Index: 15, Node: nil, PrevNode: &Node{ Key: "/foo", Value: "bar", ModifiedIndex: 12, CreatedIndex: 10, }, }, wantErr: false, }, // Node { hdr: "15", body: `{"action":"get", "node": {"key": "/foo", "value": "bar", "modifiedIndex": 12, "createdIndex": 10, "ttl": 10, "expiration": "2015-04-07T04:40:23.044979686Z"}}`, wantRes: &Response{ Action: "get", Index: 15, Node: &Node{ Key: "/foo", Value: "bar", ModifiedIndex: 12, CreatedIndex: 10, TTL: 10, Expiration: &expiration, }, PrevNode: nil, }, wantErr: false, }, // Node Dir { hdr: "15", body: `{"action":"get", "node": {"key": "/foo", "dir": true, "modifiedIndex": 12, "createdIndex": 10}}`, wantRes: &Response{ Action: "get", Index: 15, Node: &Node{ Key: "/foo", Dir: true, ModifiedIndex: 12, CreatedIndex: 10, }, PrevNode: nil, }, wantErr: false, }, // PrevNode and Node { hdr: "15", body: `{"action":"update", "prevNode": {"key": "/foo", "value": "baz", "modifiedIndex": 10, "createdIndex": 10}, "node": {"key": "/foo", "value": "bar", "modifiedIndex": 12, "createdIndex": 10}}`, wantRes: &Response{ Action: "update", Index: 15, PrevNode: &Node{ Key: "/foo", Value: "baz", ModifiedIndex: 10, CreatedIndex: 10, }, Node: &Node{ Key: "/foo", Value: "bar", ModifiedIndex: 12, CreatedIndex: 10, }, }, wantErr: false, }, // Garbage in body { hdr: "", body: `garbage`, wantRes: nil, wantErr: true, }, // non-integer index { hdr: "poo", body: `{}`, wantRes: nil, wantErr: true, }, } for i, tt := range tests { h := make(http.Header) h.Add("X-Etcd-Index", tt.hdr) res, err := unmarshalSuccessfulKeysResponse(h, []byte(tt.body)) if tt.wantErr != (err != nil) { t.Errorf("#%d: wantErr=%t, err=%v", i, tt.wantErr, err) } if (res == nil) != (tt.wantRes == nil) { t.Errorf("#%d: received res=%#v, but expected res=%#v", i, res, tt.wantRes) continue } else if tt.wantRes == nil { // expected and successfully got nil response continue } if res.Action != tt.wantRes.Action { t.Errorf("#%d: Action=%s, expected %s", i, res.Action, tt.wantRes.Action) } if res.Index != tt.wantRes.Index { t.Errorf("#%d: Index=%d, expected %d", i, res.Index, tt.wantRes.Index) } if !reflect.DeepEqual(res.Node, tt.wantRes.Node) { t.Errorf("#%d: Node=%v, expected %v", i, res.Node, tt.wantRes.Node) } } }
func Fuzz(data []byte) int { var t time.Time if err := t.UnmarshalText(data); err != nil { return 0 } data1, err := t.MarshalText() if err != nil { panic(err) } var t1 time.Time if err := t1.UnmarshalText(data1); err != nil { panic(err) } if !fuzz.DeepEqual(t, t1) { fmt.Printf("t0: %#v\n", t) fmt.Printf("t1: %#v\n", t1) panic("bad MarshalText") } data2, err := t.GobEncode() if err != nil { panic(err) } var t2 time.Time if err := t2.GobDecode(data2); err != nil { panic(err) } if !fuzz.DeepEqual(t, t2) { fmt.Printf("t0: %#v\n", t) fmt.Printf("t2: %#v\n", t2) panic("bad GobEncode") } data3, err := t.MarshalBinary() if err != nil { panic(err) } var t3 time.Time if err := t3.UnmarshalBinary(data3); err != nil { panic(err) } if !fuzz.DeepEqual(t, t3) { fmt.Printf("t0: %#v\n", t) fmt.Printf("t3: %#v\n", t3) panic("bad MarshalBinary") } data4, err := t.MarshalJSON() if err != nil { panic(err) } var t4 time.Time if err := t4.UnmarshalJSON(data4); err != nil { panic(err) } if !fuzz.DeepEqual(t, t4) { fmt.Printf("t0: %#v\n", t) fmt.Printf("t4: %#v\n", t4) panic("bad MarshalJSON") } data5, err := t.MarshalText() if err != nil { panic(err) } var t5 time.Time if err := t5.UnmarshalText(data5); err != nil { panic(err) } if !fuzz.DeepEqual(t, t5) { fmt.Printf("t0: %#v\n", t) fmt.Printf("t5: %#v\n", t5) panic("bad MarshalText") } data6 := t.Format(time.RFC3339Nano) t6, err := time.Parse(time.RFC3339Nano, data6) if err != nil { panic(err) } if !fuzz.DeepEqual(t, t6) { fmt.Printf("t0: %#v\n", t) fmt.Printf("t6: %#v\n", t6) panic("bad Format") } return 1 }
import ( "bytes" "compress/gzip" "fmt" "io" "net/http" "os" pathpkg "path" "time" ) // assets statically implements the virtual filesystem given to vfsgen as input. var assets = func() http.FileSystem { mustUnmarshalTextTime := func(text string) time.Time { var t time.Time err := t.UnmarshalText([]byte(text)) if err != nil { panic(err) } return t } fs := _vfsgen_fs{ "/": &_vfsgen_dirInfo{ name: "/", modTime: mustUnmarshalTextTime("0001-01-01T00:00:00Z"), }, "/folderA": &_vfsgen_dirInfo{ name: "folderA", modTime: mustUnmarshalTextTime("0001-01-01T00:00:00Z"), },
func main() { switch config.Config.Command { case config.DELETE: api.Delete( *config.Config.Input["delete.repository"].(*string), *config.Config.Input["delete.tag"].(*string), *config.Config.Input["delete.dry"].(*bool), ) if true != *config.Config.Input["delete.dry"].(*bool) { fmt.Printf("Image %s:%s removed\n", *config.Config.Input["delete.repository"].(*string), *config.Config.Input["delete.tag"].(*string)) } case config.TOKEN: token, err := config.Config.TokenManager.GetToken(&http.AuthChallenge{ Service: *config.Config.Input["token.service"].(*string), Realm: *config.Config.Input["token.realm"].(*string), Scope: *config.Config.Input["token.scope"].(*string), }) logger.Logger.CheckError(err) fmt.Println("") fmt.Println("Expires: " + token.ExpireTime().Format("2006-01-02 15:04:05 UTC")) fmt.Println(token.Token) fmt.Println("") case config.LIST: table := helpers.NewTable("REPOSITORY", "TAG", "DATE", "AUTHOR", "SIZE(MB)") list := api.GetList() list.Sort() for _, info := range *list { for _, tag := range info.Tags { manifest := api.GetManifest(info.Name, tag, true) author := "" for _, history := range manifest.History { if value, exist := history.Unpack()["author"]; exist { author = value.(string) break } } time := time.Time{} time.UnmarshalText([]byte(manifest.History[len(manifest.History)-1].Unpack()["created"].(string))) table.AddRow( info.Name, tag, time.Format("2006-01-02 15:04:05.000000"), author, api.GetSize(info.Name, tag)/(1024*1024), ) } } table.Print() case config.SIZE: size := api.GetSize( *config.Config.Input["size.repository"].(*string), *config.Config.Input["size.tag"].(*string), ) fmt.Printf("\n%dMB\n", size/(1024*1024)) case config.HISTORY: manifest := api.GetManifest( *config.Config.Input["history.repository"].(*string), *config.Config.Input["history.tag"].(*string), true, ) if config.Config.Verbose { // Print json set to less path, err := exec.LookPath("less") logger.Logger.CheckError(err) cmd := exec.Command(path, "-egR") stdin, err := cmd.StdinPipe() logger.Logger.CheckError(err) cmd.Stderr = os.Stderr cmd.Stdout = os.Stdout for i := len(manifest.History) - 1; i >= 0; i-- { io.WriteString(stdin, string(manifest.History[i].Print().Bytes())) io.WriteString(stdin, "\n") } stdin.Close() err = cmd.Run() logger.Logger.CheckError(err) } else { // Print only date and command for i := len(manifest.History) - 1; i >= 0; i-- { data := manifest.History[i].Unpack() cmd := data["container_config"].(map[string]interface{})["Cmd"] if cmd != nil { line := "" for _, part := range cmd.([]interface{}) { line += part.(string) + " " } time := time.Time{} time.UnmarshalText([]byte(data["created"].(string))) fmt.Printf("[%s] %s\n", time.Format("2006-01-02 15:04:05.000000"), line) } } } case config.REPOSITORIES: repositories := api.GetRepositories() table := helpers.NewTable("REPOSITORIES") for _, name := range repositories.Images { table.AddRow(name) } table.Print() case config.TAGS: tags := api.GetTags(*config.Config.Input["tag.repository"].(*string)) if tags != nil { table := helpers.NewTable("TAGS(" + *config.Config.Input["tag.repository"].(*string) + ")") for _, name := range tags.Tags { table.AddRow(name) } table.Print() } } }