1、时间格式化
基于模式的布局进行时间格式化和解析
1 package main 2 3 import "fmt" 4 import "time" 5 6 func main() { 7 p := fmt.Println 8 9 t := time.Now() 10 p(t.Format(time.RFC3339)) 11 12 t1, e := time.Parse( 13 time.RFC3339, 14 "2012-11-01T22:08:41+00:00") 15 p(t1) 16 17 p(t.Format("3:04PM")) 18 p(t.Format("Mon Jan _2 15:04:05 2006")) 19 p(t.Format("2006-01-02T15:04:05.999999-07:00")) 20 form := "3 04 PM" 21 t2, e := time.Parse(form, "8 41 PM") 22 p(t2) 23 24 fmt.Printf("%d-%02d-%02dT%02d:%02d:%02d-00:00\n", 25 t.Year(), t.Month(), t.Day(), 26 t.Hour(), t.Minute(), t.Second()) 27 28 ansic := "Mon Jan _2 15:04:05 2006" 29 _, e = time.Parse(ansic, "8:41PM") 30 p(e) 31 }
执行上面代码,将得到以下输出结果
1 2017-03-23T11:41:52+08:00 2 2012-11-01 22:08:41 +0000 +0000 3 11:41AM 4 Thu Mar 23 11:41:52 2017 5 2017-03-23T11:41:52.246508+08:00 6 0000-01-01 20:41:00 +0000 UTC 7 2017-03-23T11:41:52-00:00 8 parsing time "8:41PM" as "Mon Jan _2 15:04:05 2006": cannot parse "8:41PM" as "Mon"
2、字符串格式化
1 package main 2 3 import "fmt" 4 import "os" 5 6 type point struct { 7 x, y int 8 } 9 10 func main() { 11 p := point{1, 2} 12 fmt.Printf("%v\n", p) 13 14 fmt.Printf("%+v\n", p) 15 16 fmt.Printf("%#v\n", p) 17 18 fmt.Printf("%T\n", p) 19 20 fmt.Printf("%t\n", true) 21 22 fmt.Printf("%d\n", 123) 23 24 fmt.Printf("%b\n", 14) 25 26 fmt.Printf("%c\n", 33) 27 28 fmt.Printf("%x\n", 456) 29 30 fmt.Printf("%f\n", 78.9) 31 32 fmt.Printf("%e\n", 123400000.0) 33 fmt.Printf("%E\n", 123400000.0) 34 35 fmt.Printf("%s\n", "\"string\"") 36 37 fmt.Printf("%q\n", "\"string\"") 38 39 fmt.Printf("%x\n", "hex this") 40 41 fmt.Printf("%p\n", &p) 42 43 fmt.Printf("|%6d|%6d|\n", 12, 345) 44 45 fmt.Printf("|%6.2f|%6.2f|\n", 1.2, 3.45) 46 47 fmt.Printf("|%-6.2f|%-6.2f|\n", 1.2, 3.45) 48 49 fmt.Printf("|%6s|%6s|\n", "foo", "b") 50 51 fmt.Printf("|%-6s|%-6s|\n", "foo", "b") 52 53 s := fmt.Sprintf("a %s", "string") 54 fmt.Println(s) 55 56 fmt.Fprintf(os.Stderr, "an %s\n", "error") 57 }
1 {1 2} 2 {x:1 y:2} 3 main.point{x:1, y:2} 4 main.point 5 true 6 123 7 1110 8 ! 9 1c8 10 78.900000 11 1.234000e+08 12 1.234000E+08 13 "string" 14 "\"string\"" 15 6865782074686973 16 0xc042004280 17 | 12| 345| 18 | 1.20| 3.45| 19 |1.20 |3.45 | 20 | foo| b| 21 |foo |b | 22 a string 23 an error
3、正则表达式
1 package main 2 3 import "bytes" 4 import "fmt" 5 import "regexp" 6 7 func main() { 8 9 // This tests whether a pattern matches a string. 10 match, _ := regexp.MatchString("p([a-z]+)ch", "peach") 11 fmt.Println(match) 12 13 // Above we used a string pattern directly, but for 14 // other regexp tasks you\'ll need to `Compile` an 15 // optimized `Regexp` struct. 16 r, _ := regexp.Compile("p([a-z]+)ch") 17 18 // Many methods are available on these structs. Here\'s 19 // a match test like we saw earlier. 20 fmt.Println(r.MatchString("peach")) 21 22 // This finds the match for the regexp. 23 fmt.Println(r.FindString("peach punch")) 24 25 // This also finds the first match but returns the 26 // start and end indexes for the match instead of the 27 // matching text. 28 fmt.Println(r.FindStringIndex("peach punch")) 29 30 // The `Submatch` variants include information about 31 // both the whole-pattern matches and the submatches 32 // within those matches. For example this will return 33 // information for both `p([a-z]+)ch` and `([a-z]+)`. 34 fmt.Println(r.FindStringSubmatch("peach punch")) 35 36 // Similarly this will return information about the 37 // indexes of matches and submatches. 38 fmt.Println(r.FindStringSubmatchIndex("peach punch")) 39 40 // The `All` variants of these functions apply to all 41 // matches in the input, not just the first. For 42 // example to find all matches for a regexp. 43 fmt.Println(r.FindAllString("peach punch pinch", -1)) 44 45 // These `All` variants are available for the other 46 // functions we saw above as well. 47 fmt.Println(r.FindAllStringSubmatchIndex( 48 "peach punch pinch", -1)) 49 50 // Providing a non-negative integer as the second 51 // argument to these functions will limit the number 52 // of matches. 53 fmt.Println(r.FindAllString("peach punch pinch", 2)) 54 55 // Our examples above had string arguments and used 56 // names like `MatchString`. We can also provide 57 // `[]byte` arguments and drop `String` from the 58 // function name. 59 fmt.Println(r.Match([]byte("peach"))) 60 61 // When creating constants with regular expressions 62 // you can use the `MustCompile` variation of 63 // `Compile`. A plain `Compile` won\'t work for 64 // constants because it has 2 return values. 65 r = regexp.MustCompile("p([a-z]+)ch") 66 fmt.Println(r) 67 68 // The `regexp` package can also be used to replace 69 // subsets of strings with other values. 70 fmt.Println(r.ReplaceAllString("a peach", "<fruit>")) 71 72 // The `Func` variant allows you to transform matched 73 // text with a given function. 74 in := []byte("a peach") 75 out := r.ReplaceAllFunc(in, bytes.ToUpper) 76 fmt.Println(string(out)) 77 }
执行上面代码,将得到以下输出结果
1 true 2 true 3 peach 4 [0 5] 5 [peach ea] 6 [0 5 1 3] 7 [peach punch pinch] 8 [[0 5 1 3] [6 11 7 9] [12 17 13 15]] 9 [peach punch] 10 true 11 p([a-z]+)ch 12 a <fruit> 13 a PEACH
4、Json
1 package main 2 3 import "encoding/json" 4 import "fmt" 5 import "os" 6 7 // We\'ll use these two structs to demonstrate encoding and 8 // decoding of custom types below. 9 type Response1 struct { 10 Page int 11 Fruits []string 12 } 13 type Response2 struct { 14 Page int `json:"page"` 15 Fruits []string `json:"fruits"` 16 } 17 18 func main() { 19 20 // First we\'ll look at encoding basic data types to 21 // JSON strings. Here are some examples for atomic 22 // values. 23 bolB, _ := json.Marshal(true) 24 fmt.Println(string(bolB)) 25 26 intB, _ := json.Marshal(1) 27 fmt.Println(string(intB)) 28 29 fltB, _ := json.Marshal(2.34) 30 fmt.Println(string(fltB)) 31 32 strB, _ := json.Marshal("gopher") 33 fmt.Println(string(strB)) 34 35 // And here are some for slices and maps, which encode 36 // to JSON arrays and objects as you\'d expect. 37 slcD := []string{"apple", "peach", "pear"} 38 slcB, _ := json.Marshal(slcD) 39 fmt.Println(string(slcB)) 40 41 mapD := map[string]int{"apple": 5, "lettuce": 7} 42 mapB, _ := json.Marshal(mapD) 43 fmt.Println(string(mapB)) 44 45 // The JSON package can automatically encode your 46 // custom data types. It will only include exported 47 // fields in the encoded output and will by default 48 // use those names as the JSON keys. 49 res1D := &Response1{ 50 Page: 1, 51 Fruits: []string{"apple", "peach", "pear"}} 52 res1B, _ := json.Marshal(res1D) 53 fmt.Println(string(res1B)) 54 55 // You can use tags on struct field declarations 56 // to customize the encoded JSON key names. Check the 57 // definition of `Response2` above to see an example 58 // of such tags. 59 res2D := &Response2{ 60 Page: 1, 61 Fruits: []string{"apple", "peach", "pear"}} 62 res2B, _ := json.Marshal(res2D) 63 fmt.Println(string(res2B)) 64 65 // Now let\'s look at decoding JSON data into Go 66 // values. Here\'s an example for a generic data 67 // structure. 68 byt := []byte(`{"num":6.13,"strs":["a","b"]}`) 69 70 // We need to provide a variable where the JSON 71 // package can put the decoded data. This 72 // `map[string]interface{}` will hold a map of strings 73 // to arbitrary data types. 74 var dat map[string]interface{} 75 76 // Here\'s the actual decoding, and a check for 77 // associated errors. 78 if err := json.Unmarshal(byt, &dat); err != nil { 79 panic(err) 80 } 81 fmt.Println(dat) 82 83 // In order to use the values in the decoded map, 84 // we\'ll need to cast them to their appropriate type. 85 // For example here we cast the value in `num` to 86 // the expected `float64` type. 87 num := dat["num"].(float64) 88 fmt.Println(num) 89 90 // Accessing nested data requires a series of 91 // casts. 92 strs := dat["strs"].([]interface{}) 93 str1 := strs[0].(string) 94 fmt.Println(str1) 95 96 // We can also decode JSON into custom data types. 97 // This has the advantages of adding additional 98 // type-safety to our programs and eliminating the 99 // need for type assertions when accessing the decoded 100 // data. 101 str := `{"page": 1, "fruits": ["apple", "peach"]}` 102 res := Response2{} 103 json.Unmarshal([]byte(str), &res) 104 fmt.Println(res) 105 fmt.Println(res.Fruits[0]) 106 107 // In the examples above we always used bytes and 108 // strings as intermediates between the data and 109 // JSON representation on standard out. We can also 110 // stream JSON encodings directly to `os.Writer`s like 111 // `os.Stdout` or even HTTP response bodies. 112 enc := json.NewEncoder(os.Stdout) 113 d := map[string]int{"apple": 5, "lettuce": 7} 114 enc.Encode(d) 115 }
执行上面代码,将得到以下输出结果
全部评论
请发表评论