github.com/angenalZZZ/gofunc@v0.0.0-20210507121333-48ff1be3917b/f/encoding_test.go (about) 1 package f_test 2 3 import ( 4 "net/http" 5 "testing" 6 7 "github.com/angenalZZZ/gofunc/f" 8 ) 9 10 func TestReadFile(t *testing.T) { 11 filename := "../test/temp/test-list-data.json" 12 enc := f.ReadFileEncoding(filename) 13 t.Logf("Reads file and detected encoding: %s", enc) 14 chr := f.ReadFileCharset(filename) 15 t.Logf("Reads file and detected charset: %+v", chr.Result) 16 buf, err := f.ReadFileAndTrimSpace(filename) 17 if err != nil { 18 t.Fatal(err) 19 } 20 t.Logf("Reads file and trim head-tail space: %c %c", buf[0], buf[len(buf)-1]) 21 } 22 23 func TestHtml_Decode(t *testing.T) { 24 type example struct { 25 Title string `html:"h1"` 26 Files []string `html:"table.files tbody tr.js-navigation-item td.content,text"` 27 } 28 29 res, err := http.Get("https://github.com/andrewstuart/goq") 30 if err != nil { 31 t.Fatal(err) 32 } 33 defer func() { _ = res.Body.Close() }() 34 35 var ex example 36 37 err = f.NewHtmlDecoder(res.Body).Decode(&ex) 38 if err != nil { 39 t.Fatal(err) 40 } 41 42 t.Log(ex.Files[:6]) 43 } 44 45 func TestJson_Get(t *testing.T) { 46 json := f.Json(` { 47 "name": {"first": "Tom", "last": "Anderson"}, 48 "age":37, 49 "children": ["Sara","Alex","Jack"], 50 "friends": [ 51 {"first": "James", "last": "Murphy"}, 52 {"first": "Roger", "last": "Craig"} 53 ] 54 }`) 55 56 t.Log(json.Get("name.last")) 57 t.Log(json.Get("age")) 58 t.Log(json.Get("children")) 59 t.Log(json.Get("children.#")) 60 t.Log(json.Get("children.1")) 61 t.Log(json.Get("child*.2")) 62 t.Log(json.Get("c?ildren.0")) 63 t.Log(json.Get("friends.#.first")) 64 t.Log(json.GetMany("friends")[0]) 65 66 json = json.Sets("name.last", "Chinese") 67 t.Log(json.Get("name.last")) 68 json = json.Sets("age", 20) 69 t.Log(json.Get("age")) 70 json = json.Deletes("friends.1") 71 t.Log(json.GetMany("friends")[0]) 72 } 73 74 func TestJson_Jwt(t *testing.T) { 75 o := struct { 76 Token string 77 Exp int 78 }{"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1OTUyMTA2MjUsImlzcyI6bnVsbCwic3ViIjpudWxsLCJhdWQiOm51bGwsIm5iZiI6bnVsbCwiaWF0IjpudWxsLCJqdGkiOm51bGx9.EN_oGUhyzGlbRJkMr0YpAj-6Uoxqkq2FT1lJYFno1iU", 3600} 79 if p, err := f.EncodeJson(o); err != nil { 80 t.Fatal(err) 81 } else { 82 t.Logf("%s\n", p) 83 } 84 if m, ok := f.IsJwtToken(o.Token); ok { 85 t.Logf("%s\n", f.EncodedMap(m)) 86 } else { 87 t.Fatal("Error", 401) 88 } 89 }