How to use MarshalJSON method of v1 Package

Best K6 code snippet using v1.MarshalJSON

structs_test.go

Source:structs_test.go Github

copy

Full Screen

...3 "fmt"4 "testing"5 "github.com/stretchr/testify/assert"6)7func TestMyInt_MarshalJSON(t *testing.T) {8 a := MyInt(123)9 res, err := a.MarshalJSON()10 assert.NoError(t, err)11 assert.Equal(t, `123`, string(res))12}13func TestMyInt_UnmarshalJSON(t *testing.T) {14 var a MyInt15 err := a.UnmarshalJSON([]byte(`123`))16 assert.NoError(t, err)17 assert.Equal(t, MyInt(123), a)18}19func TestMyString_MarshalJSON(t *testing.T) {20 a := MyString(`foo"bar`)21 res, err := a.MarshalJSON()22 assert.NoError(t, err)23 assert.Equal(t, `"foo\"bar"`, string(res))24}25func TestMyString_UnmarshalJSON(t *testing.T) {26 var a MyString27 err := a.UnmarshalJSON([]byte(`"foo\"bar"`))28 assert.NoError(t, err)29 assert.Equal(t, MyString(`foo"bar`), a)30}31func TestMyFloat_MarshalJSON(t *testing.T) {32 a := MyFloat(12.3)33 res, err := a.MarshalJSON()34 assert.NoError(t, err)35 assert.Equal(t, `12.3`, string(res))36}37func TestMyFloat_UnmarshalJSON(t *testing.T) {38 var a MyFloat39 err := a.UnmarshalJSON([]byte(`12.3`))40 assert.NoError(t, err)41 assert.Equal(t, MyFloat(12.3), a)42}43func TestMyExternal_MarshalJSON(t *testing.T) {44 a := MyExternal{45 Key: "k",46 }47 res, err := a.MarshalJSON()48 assert.NoError(t, err)49 assert.Equal(t, `{"Key":"k"}`, string(res))50}51func TestMyExternal_UnmarshalJSON(t *testing.T) {52 raw := MyExternal{53 Key: "k",54 }55 var got MyExternal56 err := got.UnmarshalJSON([]byte(`{"Key":"k"}`))57 assert.NoError(t, err)58 assert.Equal(t, raw, got)59}60func TestMyExternalAlias_MarshalJSON(t *testing.T) {61 a := MyExternalAlias{62 Key: "k",63 }64 res, err := a.MarshalJSON()65 assert.NoError(t, err)66 assert.Equal(t, `{"Key":"k"}`, string(res))67}68func TestMyExternalAlias_UnmarshalJSON(t *testing.T) {69 raw := MyExternalAlias{70 Key: "k",71 }72 var got MyExternalAlias73 err := got.UnmarshalJSON([]byte(`{"Key":"k"}`))74 assert.NoError(t, err)75 assert.Equal(t, raw, got)76}77func TestMyArray_MarshalJSON(t *testing.T) {78 for _, tt := range []struct {79 arr []string80 want string81 }{82 {83 arr: nil,84 want: `null`,85 },86 {87 arr: []string{},88 want: `[]`,89 },90 {91 arr: []string{"a"},92 want: `["a"]`,93 },94 {95 arr: []string{"a", "b"},96 want: `["a","b"]`,97 },98 } {99 t.Run("", func(t *testing.T) {100 a := MyArray(tt.arr)101 res, err := a.MarshalJSON()102 assert.NoError(t, err)103 assert.Equal(t, tt.want, string(res))104 })105 }106}107func TestMyArray_UnmarshalJSON(t *testing.T) {108 for _, tt := range []struct {109 want MyArray110 raw string111 }{112 {113 want: nil,114 raw: `null`,115 },116 {117 want: []string{},118 raw: `[]`,119 },120 {121 want: []string{"a"},122 raw: `["a"]`,123 },124 {125 want: []string{"a", "b"},126 raw: `["a","b"]`,127 },128 } {129 t.Run("", func(t *testing.T) {130 var got MyArray131 err := got.UnmarshalJSON([]byte(tt.raw))132 assert.NoError(t, err)133 assert.Equal(t, tt.want, got)134 fmt.Printf("%#v %#v\n", tt.want, got)135 })136 }137}138func TestDoubleArray_MarshalJSON(t *testing.T) {139 for _, tt := range []struct {140 arr [][]string141 want string142 }{143 {144 arr: nil,145 want: `null`,146 },147 {148 arr: [][]string{},149 want: `[]`,150 },151 {152 arr: [][]string{{}},153 want: `[[]]`,154 },155 {156 arr: [][]string{nil},157 want: `[null]`,158 },159 {160 arr: [][]string{{"a"}},161 want: `[["a"]]`,162 },163 {164 arr: [][]string{{"a", "b"}},165 want: `[["a","b"]]`,166 },167 {168 arr: [][]string{{"a"}, {"b"}},169 want: `[["a"],["b"]]`,170 },171 {172 arr: [][]string{{"a"}, {"b", "c"}},173 want: `[["a"],["b","c"]]`,174 },175 {176 arr: [][]string{{"a", "b"}, {"c"}},177 want: `[["a","b"],["c"]]`,178 },179 } {180 t.Run("", func(t *testing.T) {181 a := DoubleArray(tt.arr)182 res, err := a.MarshalJSON()183 assert.NoError(t, err)184 assert.Equal(t, tt.want, string(res))185 })186 }187}188func TestDoubleArray_UnmarshalJSON(t *testing.T) {189 for _, tt := range []struct {190 want DoubleArray191 raw string192 }{193 {194 want: nil,195 raw: `null`,196 },197 {198 want: [][]string{},199 raw: `[]`,200 },201 {202 want: [][]string{{}},203 raw: `[[]]`,204 },205 {206 want: [][]string{nil},207 raw: `[null]`,208 },209 {210 want: [][]string{{"a"}},211 raw: `[["a"]]`,212 },213 {214 want: [][]string{{"a", "b"}},215 raw: `[["a","b"]]`,216 },217 {218 want: [][]string{{"a"}, {"b"}},219 raw: `[["a"],["b"]]`,220 },221 {222 want: [][]string{{"a"}, {"b", "c"}},223 raw: `[["a"],["b","c"]]`,224 },225 {226 want: [][]string{{"a", "b"}, {"c"}},227 raw: `[["a","b"],["c"]]`,228 },229 } {230 t.Run("", func(t *testing.T) {231 var got DoubleArray232 err := got.UnmarshalJSON([]byte(tt.raw))233 assert.NoError(t, err)234 assert.Equal(t, tt.want, got)235 fmt.Printf("%#v %#v\n", tt.want, got)236 })237 }238}239func TestMapStringString_MarshalJSON(t *testing.T) {240 for _, tt := range []struct {241 m map[string]string242 want string243 }{244 {245 m: nil,246 want: `null`,247 },248 {249 m: make(MapStringString, 0),250 want: `{}`,251 },252 {253 m: map[string]string{254 "k": "v",255 },256 want: `{"k":"v"}`,257 },258 {259 m: map[string]string{260 "k": "v",261 "k2": "v2",262 },263 want: `{"k":"v","k2":"v2"}`,264 },265 } {266 t.Run("", func(t *testing.T) {267 a := MapStringString(tt.m)268 res, err := a.MarshalJSON()269 assert.NoError(t, err)270 assert.Equal(t, tt.want, string(res))271 })272 }273}274func TestMapStringString_UnmarshalJSON(t *testing.T) {275 for _, tt := range []struct {276 want MapStringString277 raw string278 }{279 {280 want: nil,281 raw: `null`,282 },283 {284 want: make(MapStringString, 0),285 raw: `{}`,286 },287 {288 want: map[string]string{289 "k": "v",290 },291 raw: `{"k":"v"}`,292 },293 {294 want: map[string]string{295 "k": "v",296 "k2": "v2",297 },298 raw: `{"k":"v","k2":"v2"}`,299 },300 } {301 t.Run("", func(t *testing.T) {302 var got MapStringString303 err := got.UnmarshalJSON([]byte(tt.raw))304 assert.NoError(t, err)305 assert.Equal(t, tt.want, got)306 })307 }308}309func TestMapIntString_MarshalJSON(t *testing.T) {310 for _, tt := range []struct {311 m map[int]string312 want string313 }{314 {315 m: map[int]string{316 1: "v",317 },318 want: `{"1":"v"}`,319 },320 {321 m: map[int]string{322 1: "v",323 2: "v2",324 },325 want: `{"1":"v","2":"v2"}`,326 },327 } {328 t.Run("", func(t *testing.T) {329 a := MapIntString(tt.m)330 res, err := a.MarshalJSON()331 assert.NoError(t, err)332 assert.Equal(t, tt.want, string(res))333 })334 }335}336func TestMapIntString_UnmarshalJSON(t *testing.T) {337 for _, tt := range []struct {338 want MapIntString339 raw string340 }{341 {342 want: map[int]string{343 1: "v",344 },345 raw: `{"1":"v"}`,346 },347 {348 want: map[int]string{349 1: "v",350 2: "v2",351 },352 raw: `{"1":"v","2":"v2"}`,353 },354 } {355 t.Run("", func(t *testing.T) {356 var got MapIntString357 err := got.UnmarshalJSON([]byte(tt.raw))358 assert.NoError(t, err)359 assert.Equal(t, tt.want, got)360 })361 }362}363func TestMapFloatString_MarshalJSON(t *testing.T) {364 for _, tt := range []struct {365 m map[float64]string366 want string367 }{368 {369 m: map[float64]string{370 1.2: "v",371 },372 want: `{"1.2":"v"}`,373 },374 {375 m: map[float64]string{376 1.2: "v",377 3.4: "v2",378 },379 want: `{"1.2":"v","3.4":"v2"}`,380 },381 } {382 t.Run("", func(t *testing.T) {383 a := MapFloatString(tt.m)384 res, err := a.MarshalJSON()385 assert.NoError(t, err)386 assert.Equal(t, tt.want, string(res))387 })388 }389}390func TestMapFloatString_UnmarshalJSON(t *testing.T) {391 for _, tt := range []struct {392 want MapFloatString393 raw string394 }{395 {396 want: map[float64]string{397 1.2: "v",398 },399 raw: `{"1.2":"v"}`,400 },401 {402 want: map[float64]string{403 1.2: "v",404 3.4: "v2",405 },406 raw: `{"1.2":"v","3.4":"v2"}`,407 },408 } {409 t.Run("", func(t *testing.T) {410 var got MapFloatString411 err := got.UnmarshalJSON([]byte(tt.raw))412 assert.NoError(t, err)413 assert.Equal(t, tt.want, got)414 })415 }416}417func TestMapMap_MarshalJSON(t *testing.T) {418 for _, tt := range []struct {419 m MapMap420 want string421 }{422 {423 m: nil,424 want: `null`,425 },426 {427 m: make(map[string]map[string]string, 0),428 want: `{}`,429 },430 {431 m: map[string]map[string]string{432 "k": nil,433 },434 want: `{"k":null}`,435 },436 {437 m: map[string]map[string]string{438 "k": make(map[string]string, 0),439 },440 want: `{"k":{}}`,441 },442 {443 m: map[string]map[string]string{444 "k1": {445 "k2": "v2",446 },447 },448 want: `{"k1":{"k2":"v2"}}`,449 },450 } {451 t.Run("", func(t *testing.T) {452 res, err := tt.m.MarshalJSON()453 assert.NoError(t, err)454 assert.Equal(t, tt.want, string(res))455 })456 }457}458func TestMapMap_UnmarshalJSON(t *testing.T) {459 for _, tt := range []struct {460 want MapMap461 raw string462 }{463 {464 want: nil,465 raw: `null`,466 },467 {468 want: make(map[string]map[string]string, 0),469 raw: `{}`,470 },471 {472 want: map[string]map[string]string{473 "k": nil,474 },475 raw: `{"k":null}`,476 },477 {478 want: map[string]map[string]string{479 "k": make(map[string]string, 0),480 },481 raw: `{"k":{}}`,482 },483 {484 want: map[string]map[string]string{485 "k1": {486 "k2": "v2",487 },488 },489 raw: `{"k1":{"k2":"v2"}}`,490 },491 } {492 t.Run("", func(t *testing.T) {493 var got MapMap494 err := got.UnmarshalJSON([]byte(tt.raw))495 assert.NoError(t, err)496 assert.Equal(t, tt.want, got)497 })498 }499}500func TestSimpleStruct_MarshalJSON(t *testing.T) {501 for _, tt := range []struct {502 m SimpleStruct503 want string504 }{505 {506 m: SimpleStruct{507 Key1: "v1",508 Key2: "v2",509 },510 want: `{"Key1":"v1","Key2":"v2"}`,511 },512 {513 m: SimpleStruct{514 Key1: "",515 Key2: "v2",516 },517 want: `{"Key1":"","Key2":"v2"}`,518 },519 } {520 t.Run("", func(t *testing.T) {521 res, err := tt.m.MarshalJSON()522 assert.NoError(t, err)523 assert.Equal(t, tt.want, string(res))524 })525 }526}527func TestSimpleStruct_UnmarshalJSON(t *testing.T) {528 for _, tt := range []struct {529 raw string530 want SimpleStruct531 }{532 {533 raw: `{"Key1":"v1","Key2":"v2"}`,534 want: SimpleStruct{535 Key1: "v1",536 Key2: "v2",537 },538 },539 {540 raw: `{"Key1":"","Key2":"v2"}`,541 want: SimpleStruct{542 Key1: "",543 Key2: "v2",544 },545 },546 } {547 t.Run("", func(t *testing.T) {548 var got SimpleStruct549 err := got.UnmarshalJSON([]byte(tt.raw))550 assert.NoError(t, err)551 assert.Equal(t, tt.want, got)552 })553 }554}555func TestAnonymousStruct_MarshalJSON(t *testing.T) {556 for _, tt := range []struct {557 m AnonymousStruct558 want string559 }{560 {561 m: AnonymousStruct{562 SimpleStruct: SimpleStruct{563 Key1: "v1",564 Key2: "v2",565 },566 Key3: "v3",567 },568 want: `{"Key1":"v1","Key2":"v2","Key3":"v3"}`,569 },570 {571 m: AnonymousStruct{572 SimpleStruct: SimpleStruct{573 Key1: "v1",574 Key2: "",575 },576 Key3: "v3",577 },578 want: `{"Key1":"v1","Key2":"","Key3":"v3"}`,579 },580 } {581 t.Run("", func(t *testing.T) {582 res, err := tt.m.MarshalJSON()583 assert.NoError(t, err)584 assert.Equal(t, tt.want, string(res))585 })586 }587}588func TestAnonymousStruct_UnmarshalJSON(t *testing.T) {589 for _, tt := range []struct {590 want AnonymousStruct591 raw string592 }{593 {594 want: AnonymousStruct{595 SimpleStruct: SimpleStruct{596 Key1: "v1",597 Key2: "v2",598 },599 Key3: "v3",600 },601 raw: `{"Key1":"v1","Key2":"v2","Key3":"v3"}`,602 },603 {604 want: AnonymousStruct{605 SimpleStruct: SimpleStruct{606 Key1: "v1",607 Key2: "",608 },609 Key3: "v3",610 },611 raw: `{"Key1":"v1","Key2":"","Key3":"v3"}`,612 },613 } {614 t.Run("", func(t *testing.T) {615 var got AnonymousStruct616 err := got.UnmarshalJSON([]byte(tt.raw))617 assert.NoError(t, err)618 assert.Equal(t, tt.want, got)619 })620 }621}622func TestAnonymousAnonymousStruct_MarshalJSON(t *testing.T) {623 for _, tt := range []struct {624 m AnonymousAnonymousStruct625 want string626 }{627 {628 m: AnonymousAnonymousStruct{629 AnonymousStruct: AnonymousStruct{630 SimpleStruct: SimpleStruct{631 Key1: "v1",632 Key2: "v2",633 },634 Key3: "v3",635 },636 Key4: "v4",637 },638 want: `{"Key1":"v1","Key2":"v2","Key3":"v3","Key4":"v4"}`,639 },640 {641 m: AnonymousAnonymousStruct{642 AnonymousStruct: AnonymousStruct{643 SimpleStruct: SimpleStruct{644 Key1: "v1",645 Key2: "v2",646 },647 Key3: "v3",648 },649 Key4: "",650 },651 want: `{"Key1":"v1","Key2":"v2","Key3":"v3","Key4":""}`,652 },653 } {654 t.Run("", func(t *testing.T) {655 res, err := tt.m.MarshalJSON()656 assert.NoError(t, err)657 assert.Equal(t, tt.want, string(res))658 })659 }660}661func TestAnonymousAnonymousStruct_UnmarshalJSON(t *testing.T) {662 for _, tt := range []struct {663 want AnonymousAnonymousStruct664 raw string665 }{666 {667 want: AnonymousAnonymousStruct{668 AnonymousStruct: AnonymousStruct{669 SimpleStruct: SimpleStruct{670 Key1: "v1",671 Key2: "v2",672 },673 Key3: "v3",674 },675 Key4: "v4",676 },677 raw: `{"Key1":"v1","Key2":"v2","Key3":"v3","Key4":"v4"}`,678 },679 {680 want: AnonymousAnonymousStruct{681 AnonymousStruct: AnonymousStruct{682 SimpleStruct: SimpleStruct{683 Key1: "v1",684 Key2: "v2",685 },686 Key3: "v3",687 },688 Key4: "",689 },690 raw: `{"Key1":"v1","Key2":"v2","Key3":"v3","Key4":""}`,691 },692 } {693 t.Run("", func(t *testing.T) {694 var got AnonymousAnonymousStruct695 err := got.UnmarshalJSON([]byte(tt.raw))696 assert.NoError(t, err)697 assert.Equal(t, tt.want, got)698 })699 }700}701func TestStructInStruct_MarshalJSON(t *testing.T) {702 for _, tt := range []struct {703 m StructInStruct704 want string705 }{706 {707 m: StructInStruct{708 Key1: struct {709 Key2 string710 }{711 Key2: "v3",712 },713 },714 want: `{"Key1":{"Key2":"v3"}}`,715 },716 {717 m: StructInStruct{718 Key1: struct {719 Key2 string720 }{721 Key2: "v0",722 },723 },724 want: `{"Key1":{"Key2":"v0"}}`,725 },726 } {727 t.Run("", func(t *testing.T) {728 res, err := tt.m.MarshalJSON()729 assert.NoError(t, err)730 assert.Equal(t, tt.want, string(res))731 })732 }733}734func TestStructInStruct_UnmarshalJSON(t *testing.T) {735 for _, tt := range []struct {736 want StructInStruct737 raw string738 }{739 {740 want: StructInStruct{741 Key1: struct {742 Key2 string743 }{744 Key2: "v3",745 },746 },747 raw: `{"Key1":{"Key2":"v3"}}`,748 },749 {750 want: StructInStruct{751 Key1: struct {752 Key2 string753 }{754 Key2: "v0",755 },756 },757 raw: `{"Key1":{"Key2":"v0"}}`,758 },759 } {760 t.Run("", func(t *testing.T) {761 var got StructInStruct762 err := got.UnmarshalJSON([]byte(tt.raw))763 assert.NoError(t, err)764 assert.Equal(t, tt.want, got)765 })766 }767}768func TestTaggedStruct_MarshalJSON(t *testing.T) {769 for _, tt := range []struct {770 m TaggedStruct771 want string772 }{773 {774 m: TaggedStruct{775 Key1: "v1",776 Key2: "v2",777 },778 want: `{"key_1":"v1","key_2":"v2"}`,779 },780 {781 m: TaggedStruct{782 Key1: "",783 Key2: "v2",784 },785 want: `{"key_1":"","key_2":"v2"}`,786 },787 {788 m: TaggedStruct{789 Key1: "v1",790 Key2: "",791 },792 want: `{"key_1":"v1","key_2":""}`,793 },794 } {795 t.Run("", func(t *testing.T) {796 res, err := tt.m.MarshalJSON()797 assert.NoError(t, err)798 assert.Equal(t, tt.want, string(res))799 })800 }801}802func TestTaggedStruct_UnmarshalJSON(t *testing.T) {803 for _, tt := range []struct {804 want TaggedStruct805 raw string806 }{807 {808 want: TaggedStruct{809 Key1: "v1",810 Key2: "v2",811 },812 raw: `{"key_1":"v1","key_2":"v2"}`,813 },814 {815 want: TaggedStruct{816 Key1: "",817 Key2: "v2",818 },819 raw: `{"key_1":"","key_2":"v2"}`,820 },821 {822 want: TaggedStruct{823 Key1: "v1",824 Key2: "",825 },826 raw: `{"key_1":"v1","key_2":""}`,827 },828 } {829 t.Run("", func(t *testing.T) {830 var got TaggedStruct831 err := got.UnmarshalJSON([]byte(tt.raw))832 assert.NoError(t, err)833 assert.Equal(t, tt.want, got)834 })835 }836}837func TestStructA1_MarshalJSON(t *testing.T) {838 for _, tt := range []struct {839 m StructA1840 want string841 }{842 {843 m: StructA1{844 A: "a0",845 StructB: StructB{846 B: "b0",847 },848 },849 want: `{"a":"a0"}`,850 },851 {852 m: StructA1{853 A: "a0",854 StructB: StructB{855 B: "b1",856 },857 },858 want: `{"a":"a0"}`,859 },860 {861 m: StructA1{862 A: "a0",863 StructB: StructB{864 B: "",865 },866 },867 want: `{"a":"a0"}`,868 },869 {870 m: StructA1{871 A: "",872 StructB: StructB{873 B: "b0",874 },875 },876 want: `{"a":""}`,877 },878 } {879 t.Run("", func(t *testing.T) {880 res, err := tt.m.MarshalJSON()881 assert.NoError(t, err)882 assert.Equal(t, tt.want, string(res))883 })884 }885}886func TestStructA1_UnmarshalJSON(t *testing.T) {887 for _, tt := range []struct {888 want StructA1889 raw string890 }{891 {892 want: StructA1{893 A: "a0",894 },895 raw: `{"a":"a0","B":"b0"}`,896 },897 {898 want: StructA1{899 A: "a0",900 },901 raw: `{"a":"a0","B":"b1"}`,902 },903 {904 want: StructA1{905 A: "a0",906 },907 raw: `{"a":"a0"}`,908 },909 {910 want: StructA1{911 A: "",912 },913 raw: `{"a":""}`,914 },915 } {916 t.Run("", func(t *testing.T) {917 var got StructA1918 err := got.UnmarshalJSON([]byte(tt.raw))919 assert.NoError(t, err)920 assert.Equal(t, tt.want, got)921 })922 }923}924func TestStructA2_MarshalJSON(t *testing.T) {925 for _, tt := range []struct {926 m StructA2927 want string928 }{929 {930 m: StructA2{931 A: "a0",932 StructC: StructC{933 C: "c0",934 },935 },936 want: `{"a":"a0","c":"c0"}`,937 },938 {939 m: StructA2{940 A: "",941 StructC: StructC{942 C: "c0",943 },944 },945 want: `{"a":"","c":"c0"}`,946 },947 {948 m: StructA2{949 A: "a0",950 StructC: StructC{951 C: "",952 },953 },954 want: `{"a":"a0","c":""}`,955 },956 } {957 t.Run("", func(t *testing.T) {958 res, err := tt.m.MarshalJSON()959 assert.NoError(t, err)960 assert.Equal(t, tt.want, string(res))961 })962 }963}964func TestStructA2_UnmarshalJSON(t *testing.T) {965 for _, tt := range []struct {966 want StructA2967 raw string968 }{969 {970 want: StructA2{971 A: "a0",972 StructC: StructC{973 C: "c0",974 },975 },976 raw: `{"a":"a0","c":"c0"}`,977 },978 {979 want: StructA2{980 A: "",981 StructC: StructC{982 C: "c0",983 },984 },985 raw: `{"a":"","c":"c0"}`,986 },987 {988 want: StructA2{989 A: "a0",990 StructC: StructC{991 C: "",992 },993 },994 raw: `{"a":"a0","c":""}`,995 },996 } {997 t.Run("", func(t *testing.T) {998 var got StructA2999 err := got.UnmarshalJSON([]byte(tt.raw))1000 assert.NoError(t, err)1001 assert.Equal(t, tt.want, got)1002 })1003 }1004}1005func TestStructA3_MarshalJSON(t *testing.T) {1006 for _, tt := range []struct {1007 m StructA31008 want string1009 }{1010 {1011 m: StructA3{1012 A1: "1",1013 A2: "2",1014 A3: "3",1015 },1016 want: `{"a3":"3"}`,1017 },1018 {1019 m: StructA3{1020 A1: "",1021 A2: "2",1022 A3: "3",1023 },1024 want: `{"a3":"3"}`,1025 },1026 {1027 m: StructA3{1028 A1: "1",1029 A2: "",1030 A3: "3",1031 },1032 want: `{"a3":"3"}`,1033 },1034 } {1035 t.Run("", func(t *testing.T) {1036 res, err := tt.m.MarshalJSON()1037 assert.NoError(t, err)1038 assert.Equal(t, tt.want, string(res))1039 })1040 }1041}1042func TestStructA3_UnmarshalJSON(t *testing.T) {1043 for _, tt := range []struct {1044 want StructA31045 raw string1046 }{1047 {1048 want: StructA3{1049 A3: "3",1050 },1051 raw: `{"A1":"1","A2":"2","a3":"3","A3":"3+"}`,1052 },1053 {1054 want: StructA3{1055 A3: "3",1056 },1057 raw: `{"A1":"1","A2":"2","A3":"3+","a3":"3"}`,1058 },1059 {1060 want: StructA3{1061 A3: "3",1062 },1063 raw: `{"a3":"3"}`,1064 },1065 {1066 want: StructA3{1067 A3: "3",1068 },1069 raw: `{"A2":"2","a3":"3","A3":"3+"}`,1070 },1071 {1072 want: StructA3{1073 A3: "3",1074 },1075 raw: `{"A1":"1","a3":"3","A3":"3+"}`,1076 },1077 } {1078 t.Run("", func(t *testing.T) {1079 var got StructA31080 err := got.UnmarshalJSON([]byte(tt.raw))1081 assert.NoError(t, err)1082 assert.Equal(t, tt.want, got)1083 })1084 }1085}1086func TestStructA4_MarshalJSON(t *testing.T) {1087 for _, tt := range []struct {1088 m StructA41089 want string1090 }{1091 {1092 m: StructA4{1093 A: "a",1094 StructB: StructB{1095 B: "b",1096 },1097 StructD: StructD{1098 D: "d",1099 D2: "d2",1100 },1101 },1102 want: `{"a":"a","d":"d2"}`,1103 },1104 } {1105 t.Run("", func(t *testing.T) {1106 res, err := tt.m.MarshalJSON()1107 assert.NoError(t, err)1108 assert.Equal(t, tt.want, string(res))1109 })1110 }1111}1112func TestStructA4_UnmarshalJSON(t *testing.T) {1113 for _, tt := range []struct {1114 want StructA41115 raw string1116 }{1117 {1118 want: StructA4{1119 A: "a",1120 StructD: StructD{1121 D2: "d2",1122 },1123 },1124 raw: `{"a":"a","B":"b","d":"d2","D":"d","D2":"d3"}`,1125 },1126 } {1127 t.Run("", func(t *testing.T) {1128 var got StructA41129 err := got.UnmarshalJSON([]byte(tt.raw))1130 assert.NoError(t, err)1131 assert.Equal(t, tt.want, got)1132 })1133 }1134}1135func TestStructA5_MarshalJSON(t *testing.T) {1136 for _, tt := range []struct {1137 m StructA51138 want string1139 }{1140 {1141 m: StructA5{1142 StructB: StructB{1143 B: "b",1144 },1145 StructD: StructD{1146 D: "d",1147 D2: "d2",1148 },1149 },1150 want: `{"d":"d2"}`,1151 },1152 } {1153 t.Run("", func(t *testing.T) {1154 res, err := tt.m.MarshalJSON()1155 assert.NoError(t, err)1156 assert.Equal(t, tt.want, string(res))1157 })1158 }1159}1160func TestStructA5_UnmarshalJSON(t *testing.T) {1161 for _, tt := range []struct {1162 want StructA51163 raw string1164 }{1165 {1166 want: StructA5{1167 StructD: StructD{1168 D2: "d2",1169 },1170 },1171 raw: `{"B":"b","D":"d","d":"d2","D2":"d2+"}`,1172 },1173 } {1174 t.Run("", func(t *testing.T) {1175 var got StructA51176 err := got.UnmarshalJSON([]byte(tt.raw))1177 assert.NoError(t, err)1178 assert.Equal(t, tt.want, got)1179 })1180 }1181}1182func TestStructA6_MarshalJSON(t *testing.T) {1183 for _, tt := range []struct {1184 m StructA61185 want string1186 }{1187 {1188 m: StructA6{1189 StructB: StructB{1190 B: "b1",1191 },1192 StructE: StructE{1193 StructB: StructB{1194 B: "b2",1195 },1196 },1197 },1198 want: `{"a":"b1"}`,1199 },1200 } {1201 t.Run("", func(t *testing.T) {1202 res, err := tt.m.MarshalJSON()1203 assert.NoError(t, err)1204 assert.Equal(t, tt.want, string(res))1205 })1206 }1207}1208func TestStructA6_UnmarshalJSON(t *testing.T) {1209 for _, tt := range []struct {1210 want StructA61211 raw string1212 }{1213 {1214 want: StructA6{1215 StructB: StructB{1216 B: "b1",1217 },1218 },1219 raw: `{"a":"b1","B":"b2"}`,1220 },1221 } {1222 t.Run("", func(t *testing.T) {1223 var got StructA61224 err := got.UnmarshalJSON([]byte(tt.raw))1225 assert.NoError(t, err)1226 assert.Equal(t, tt.want, got)1227 })1228 }1229}1230func TestStructA7_MarshalJSON(t *testing.T) {1231 for _, tt := range []struct {1232 m StructA71233 want string1234 }{1235 {1236 m: StructA7{1237 StructB: StructB{1238 B: "b1",1239 },1240 StructD: StructD{1241 D: "d1",1242 D2: "d2",1243 },1244 },1245 want: `{"a":"d1","b":{"a":"b1"},"d":"d2"}`,1246 },1247 } {1248 t.Run("", func(t *testing.T) {1249 res, err := tt.m.MarshalJSON()1250 assert.NoError(t, err)1251 assert.Equal(t, tt.want, string(res))1252 })1253 }1254}1255func TestStructA7_UnmarshalJSON(t *testing.T) {1256 for _, tt := range []struct {1257 want StructA71258 raw string1259 }{1260 {1261 want: StructA7{1262 StructB: StructB{1263 B: "b1",...

Full Screen

Full Screen

handlers.go

Source:handlers.go Github

copy

Full Screen

...66 w.WriteHeader(http.StatusBadRequest)67 response, _ := types.ServerResponse{68 Status: http.StatusText(http.StatusBadRequest),69 Message: "invalid_request_format",70 }.MarshalJSON()71 _, _ = w.Write(response)72 return73 }74 if registrationInfo.Login == "" {75 w.WriteHeader(http.StatusUnprocessableEntity)76 response, _ := types.ServerResponse{77 Status: http.StatusText(http.StatusUnprocessableEntity),78 Message: "empty_login",79 }.MarshalJSON()80 _, _ = w.Write(response)81 return82 }83 if len(registrationInfo.Password) < 5 {84 w.WriteHeader(http.StatusUnprocessableEntity)85 response, _ := types.ServerResponse{86 Status: http.StatusText(http.StatusUnprocessableEntity),87 Message: "weak_password",88 }.MarshalJSON()89 _, _ = w.Write(response)90 return91 }92 userID, isDuplicate, err := e.DB.InsertIntoUser(registrationInfo.Login, defaultAvatarURL, false)93 if isDuplicate {94 w.WriteHeader(http.StatusConflict)95 response, _ := types.ServerResponse{96 Status: http.StatusText(http.StatusConflict),97 Message: "login_is_not_unique",98 }.MarshalJSON()99 _, _ = w.Write(response)100 return101 }102 if err != nil {103 w.WriteHeader(http.StatusInternalServerError)104 response, _ := types.ServerResponse{105 Status: http.StatusText(http.StatusInternalServerError),106 Message: "database_error",107 }.MarshalJSON()108 _, _ = w.Write(response)109 return110 }111 err = e.DB.InsertIntoRegularLoginInformation(userID, sha256hash(registrationInfo.Password))112 if err != nil {113 log.Print(err)114 w.WriteHeader(http.StatusInternalServerError)115 response, _ := types.ServerResponse{116 Status: http.StatusText(http.StatusInternalServerError),117 Message: "database_error",118 }.MarshalJSON()119 _, _ = w.Write(response)120 return121 }122 err = e.DB.InsertIntoGameStatistics(userID, 0, 0)123 if err != nil {124 log.Print(err)125 w.WriteHeader(http.StatusInternalServerError)126 response, _ := types.ServerResponse{127 Status: http.StatusText(http.StatusInternalServerError),128 Message: "database_error",129 }.MarshalJSON()130 _, _ = w.Write(response)131 return132 }133 // создаём токены авторизации.134 authorizationToken := randomToken()135 err = e.DB.UpsertIntoCurrentLogin(userID, authorizationToken)136 if err != nil {137 log.Print(err)138 w.WriteHeader(http.StatusInternalServerError)139 response, _ := types.ServerResponse{140 Status: http.StatusText(http.StatusInternalServerError),141 Message: "database_error",142 }.MarshalJSON()143 _, _ = w.Write(response)144 return145 }146 // Отсылаем нормальный ответ.147 http.SetCookie(w, &http.Cookie{148 Name: "SessionId",149 Value: authorizationToken,150 Path: "/",151 Expires: time.Now().AddDate(0, 0, 7),152 Secure: true,153 HttpOnly: true,154 SameSite: http.SameSiteLaxMode,155 })156 w.WriteHeader(http.StatusCreated)157 response, _ := types.ServerResponse{158 Status: http.StatusText(http.StatusCreated),159 Message: "successful_reusable_registration",160 }.MarshalJSON()161 _, _ = w.Write(response)162}163// RegistrationTemporary godoc164// @Summary Temporary user registration.165// @Description Сreates user without statistics and password, stub so that you can play 1 session without creating an account.166// @Tags user167// @Accept application/json168// @Produce application/json169// @Param registrationInfo body types.NewUserRegistration true "login password"170// @Success 200 {object} types.ServerResponse171// @Failure 500 {object} types.ServerResponse172// @Router /api/v1/user&temporary=true [post]173func (e *Environment) RegistrationTemporary(w http.ResponseWriter, r *http.Request) {174 w.Header().Set("Content-Type", "application/json")175 bodyBytes, err := ioutil.ReadAll(r.Body)176 _ = r.Body.Close()177 registrationInfo := types.NewUserRegistration{}178 err = registrationInfo.UnmarshalJSON(bodyBytes)179 if err != nil {180 w.WriteHeader(http.StatusBadRequest)181 response, _ := types.ServerResponse{182 Status: http.StatusText(http.StatusBadRequest),183 Message: "invalid_request_format",184 }.MarshalJSON()185 _, _ = w.Write(response)186 return187 }188 if registrationInfo.Login == "" {189 w.WriteHeader(http.StatusUnprocessableEntity)190 response, _ := types.ServerResponse{191 Status: http.StatusText(http.StatusUnprocessableEntity),192 Message: "empty_login",193 }.MarshalJSON()194 _, _ = w.Write(response)195 return196 }197 userID, isDuplicate, err := e.DB.InsertIntoUser(registrationInfo.Login, defaultAvatarURL, true)198 if isDuplicate {199 w.WriteHeader(http.StatusConflict)200 response, _ := types.ServerResponse{201 Status: http.StatusText(http.StatusConflict),202 Message: "login_is_not_unique",203 }.MarshalJSON()204 _, _ = w.Write(response)205 return206 }207 if err != nil {208 log.Print(err)209 w.WriteHeader(http.StatusInternalServerError)210 response, _ := types.ServerResponse{211 Status: http.StatusText(http.StatusInternalServerError),212 Message: "database_error",213 }.MarshalJSON()214 _, _ = w.Write(response)215 return216 }217 // создаём токены авторизации.218 authorizationToken := randomToken()219 err = e.DB.UpsertIntoCurrentLogin(userID, authorizationToken)220 if err != nil {221 log.Print(err)222 w.WriteHeader(http.StatusInternalServerError)223 response, _ := types.ServerResponse{224 Status: http.StatusText(http.StatusInternalServerError),225 Message: "database_error",226 }.MarshalJSON()227 _, _ = w.Write(response)228 return229 }230 http.SetCookie(w, &http.Cookie{231 Name: "SessionId",232 Value: authorizationToken,233 Path: "/",234 Expires: time.Now().AddDate(0, 0, 7),235 Secure: true,236 HttpOnly: true,237 SameSite: http.SameSiteLaxMode,238 })239 w.WriteHeader(http.StatusCreated)240 response, _ := types.ServerResponse{241 Status: http.StatusText(http.StatusCreated),242 Message: "successful_disposable_registration",243 }.MarshalJSON()244 _, _ = w.Write(response)245}246// LeaderBoard godoc247// @Summary Get liderboard with best user information.248// @Description Return login, avatarAddress, gamesPlayed and wins information for earch user.249// @Tags users250// @Accept application/json251// @Produce application/json252// @Param limit query int false "Lenth of returning user list."253// @Param offset query int false "Offset relative to the leader."254// @Success 200 {array} accessor.PublicUserInformation255// @Failure 500 {object} types.ServerResponse256// @Router /api/v1/users [get]257func (e *Environment) LeaderBoard(w http.ResponseWriter, r *http.Request) {258 w.Header().Set("Content-Type", "application/json")259 getParams := r.URL.Query()260 _ = r.Body.Close()261 limit := 20262 if customLimitStrings, ok := getParams["limit"]; ok {263 if len(customLimitStrings) == 1 {264 if customLimitInt, err := strconv.Atoi(customLimitStrings[0]); err == nil {265 limit = customLimitInt266 }267 }268 }269 offset := 0270 if customOffsetStrings, ok := getParams["offset"]; ok {271 if len(customOffsetStrings) == 1 {272 if customOffsetInt, err := strconv.Atoi(customOffsetStrings[0]); err == nil {273 offset = customOffsetInt274 }275 }276 }277 LeaderBoard, err := e.DB.SelectLeaderBoard(limit, offset)278 if err != nil {279 log.Print(err)280 w.WriteHeader(http.StatusInternalServerError)281 response, _ := types.ServerResponse{282 Status: http.StatusText(http.StatusInternalServerError),283 Message: "database_error",284 }.MarshalJSON()285 _, _ = w.Write(response)286 return287 }288 w.WriteHeader(http.StatusOK)289 response, _ := LeaderBoard.MarshalJSON()290 _, _ = w.Write(response)291}292// UserProfile godoc293// @Summary Get user information.294// @Description Return login, avatarAddress, gamesPlayed, wins, information.295// @Tags user296// @Accept application/json297// @Produce application/json298// @Param login query string true "login password"299// @Success 200 {object} accessor.PublicUserInformation300// @Failure 422 {object} types.ServerResponse301// @Failure 500 {object} types.ServerResponse302// @Router /api/v1/user [get]303func (e *Environment) UserProfile(w http.ResponseWriter, r *http.Request) {304 getParams := r.URL.Query()305 _ = r.Body.Close()306 login := ""307 if loginStrings, ok := getParams["login"]; ok {308 if len(loginStrings) == 1 {309 login = loginStrings[0]310 if login != "" {311 // just working on312 } else {313 w.WriteHeader(http.StatusUnprocessableEntity)314 response, _ := types.ServerResponse{315 Status: http.StatusText(http.StatusUnprocessableEntity),316 Message: "empty_login_field",317 }.MarshalJSON()318 _, _ = w.Write(response)319 return320 }321 } else {322 w.WriteHeader(http.StatusUnprocessableEntity)323 response, _ := types.ServerResponse{324 Status: http.StatusText(http.StatusUnprocessableEntity),325 Message: "login_must_be_only_1",326 }.MarshalJSON()327 _, _ = w.Write(response)328 return329 }330 } else {331 w.WriteHeader(http.StatusUnprocessableEntity)332 response, _ := types.ServerResponse{333 Status: http.StatusText(http.StatusUnprocessableEntity),334 Message: "field_login_required",335 }.MarshalJSON()336 _, _ = w.Write(response)337 return338 }339 userProfile, err := e.DB.SelectUserByLogin(login)340 if err != nil {341 log.Print(err)342 w.WriteHeader(http.StatusInternalServerError)343 response, _ := types.ServerResponse{344 Status: http.StatusText(http.StatusInternalServerError),345 Message: "database_error",346 }.MarshalJSON()347 _, _ = w.Write(response)348 return349 }350 w.WriteHeader(http.StatusOK)351 response, _ := userProfile.MarshalJSON()352 _, _ = w.Write(response)353}354// Login godoc355// @Summary Login into account.356// @Description Set cookie on client and save them in database.357// @Tags session358// @Accept application/json359// @Produce application/json360// @Param registrationInfo body types.NewUserRegistration true "login password"361// @Success 202 {object} types.ServerResponse362// @Failure 400 {object} types.ServerResponse363// @Failure 403 {object} types.ServerResponse364// @Failure 500 {object} types.ServerResponse365// @Router /api/v1/session [post]366func (e *Environment) Login(w http.ResponseWriter, r *http.Request) {367 w.Header().Set("Content-Type", "application/json")368 bodyBytes, err := ioutil.ReadAll(r.Body)369 _ = r.Body.Close()370 registrationInfo := types.NewUserRegistration{}371 err = registrationInfo.UnmarshalJSON(bodyBytes)372 if err != nil {373 w.WriteHeader(http.StatusBadRequest)374 response, _ := types.ServerResponse{375 Status: http.StatusText(http.StatusBadRequest),376 Message: "invalid_request_format",377 }.MarshalJSON()378 _, _ = w.Write(response)379 return380 }381 exists, userId, err := e.DB.SelectUserIdByLoginPasswordHash(registrationInfo.Login, sha256hash(registrationInfo.Password))382 if err != nil {383 log.Print(err)384 w.WriteHeader(http.StatusInternalServerError)385 response, _ := types.ServerResponse{386 Status: http.StatusText(http.StatusInternalServerError),387 Message: "database_error",388 }.MarshalJSON()389 _, _ = w.Write(response)390 return391 }392 if exists {393 authorizationToken := randomToken()394 err = e.DB.UpsertIntoCurrentLogin(userId, authorizationToken)395 if err != nil {396 log.Print(err)397 w.WriteHeader(http.StatusInternalServerError)398 response, _ := types.ServerResponse{399 Status: http.StatusText(http.StatusInternalServerError),400 Message: "database_error",401 }.MarshalJSON()402 _, _ = w.Write(response)403 return404 }405 // Уже нормальный ответ отсылаем.406 http.SetCookie(w, &http.Cookie{407 Name: "SessionId",408 Value: authorizationToken,409 Path: "/",410 Expires: time.Now().AddDate(0, 0, 7),411 Secure: true,412 HttpOnly: true,413 SameSite: http.SameSiteLaxMode,414 })415 w.WriteHeader(http.StatusAccepted)416 response, _ := types.ServerResponse{417 Status: http.StatusText(http.StatusAccepted),418 Message: "successful_password_login",419 }.MarshalJSON()420 _, _ = w.Write(response)421 } else {422 w.WriteHeader(http.StatusForbidden)423 response, _ := types.ServerResponse{424 Status: http.StatusText(http.StatusFailedDependency),425 Message: "wrong_login_or_password",426 }.MarshalJSON()427 _, _ = w.Write(response)428 }429}430// Logout godoc431// @Summary Log registered user out.432// @Description Delete cookie in client and database.433// @Tags session434// @Accept application/json435// @Produce application/json436// @Success 200 {object} types.ServerResponse437// @Failure 404 {object} types.ServerResponse438// @Failure 401 {object} types.ServerResponse439// @Router /api/v1/session [delete]440func (e *Environment) Logout(w http.ResponseWriter, r *http.Request) {441 //get sid from cookies442 inCookie, err := r.Cookie("SessionId")443 if err != nil {444 log.Print(err)445 w.WriteHeader(http.StatusUnauthorized)446 response, _ := types.ServerResponse{447 Status: http.StatusText(http.StatusUnauthorized),448 Message: "unauthorized_user",449 }.MarshalJSON()450 _, _ = w.Write(response)451 return452 }453 err = e.DB.DropUsersSession(inCookie.Value)454 if err != nil {455 log.Print(err)456 w.WriteHeader(http.StatusNotFound)457 response, _ := types.ServerResponse{458 Status: http.StatusText(http.StatusNotFound),459 Message: "target_session_not_found",460 }.MarshalJSON()461 _, _ = w.Write(response)462 return463 }464 http.SetCookie(w, &http.Cookie{465 Name: "SessionId",466 Expires: time.Unix(0, 0),467 Secure: true,468 HttpOnly: true,469 SameSite: http.SameSiteLaxMode,470 })471 w.WriteHeader(http.StatusOK)472 response, _ := types.ServerResponse{473 Status: http.StatusText(http.StatusOK),474 Message: "successful_logout",475 }.MarshalJSON()476 _, _ = w.Write(response)477}478// Logout godoc479// @Summary Upload user avatar.480// @Description Upload avatar from \<form enctype='multipart/form-data' action='/api/v1/avatar'>\<input type="file" name="avatar"></form>.481// @Tags avatar482// @Accept multipart/form-data483// @Produce application/json484// @Success 201 {object} types.ServerResponse485// @Failure 400 {object} types.ServerResponse486// @Failure 401 {object} types.ServerResponse487// @Failure 500 {object} types.ServerResponse488// @Router /api/v1/avatar [post]489func (e *Environment) SetAvatar(w http.ResponseWriter, r *http.Request) {490 defer func() { _ = r.Body.Close() }()491 w.Header().Set("Content-Type", "application/json")492 //get SessionId from cookies493 cookie, err := r.Cookie("SessionId")494 if err != nil || cookie.Value == "" {495 log.Print(err)496 w.WriteHeader(http.StatusForbidden)497 response, _ := types.ServerResponse{498 Status: http.StatusText(http.StatusForbidden),499 Message: "unauthorized_user",500 }.MarshalJSON()501 _, _ = w.Write(response)502 return503 }504 exist, user, err := e.DB.SelectUserBySessionId(cookie.Value)505 if err != nil {506 log.Print(err)507 w.WriteHeader(http.StatusInternalServerError)508 response, _ := types.ServerResponse{509 Status: http.StatusText(http.StatusInternalServerError),510 Message: "cannot_create_file",511 }.MarshalJSON()512 _, _ = w.Write(response)513 return514 }515 if !exist {516 w.WriteHeader(http.StatusForbidden)517 response, _ := types.ServerResponse{518 Status: http.StatusText(http.StatusForbidden),519 Message: "unauthorized_user",520 }.MarshalJSON()521 _, _ = w.Write(response)522 return523 }524 err = r.ParseMultipartForm(0)525 if err != nil {526 log.Print("handlers SetAvatar ParseMultipartForm: " + err.Error())527 return528 }529 file, handler, err := r.FormFile("avatar")530 if err != nil {531 fmt.Println(err)532 w.WriteHeader(http.StatusBadRequest)533 response, _ := types.ServerResponse{534 Status: http.StatusText(http.StatusBadRequest),535 Message: "cannot_get_file",536 }.MarshalJSON()537 _, _ = w.Write(response)538 return539 }540 defer func() { _ = file.Close() }()541 // /var/www/media/images/login.jpeg542 fileName := user.Login + filepath.Ext(handler.Filename)543 f, err := os.Create(*e.Config.ImagesRoot + "/" + fileName)544 if err != nil {545 fmt.Println(err)546 w.WriteHeader(http.StatusInternalServerError)547 response, _ := types.ServerResponse{548 Status: http.StatusText(http.StatusInternalServerError),549 Message: "cannot_create_file",550 }.MarshalJSON()551 _, _ = w.Write(response)552 return553 }554 defer func() { _ = f.Close() }()555 //put avatar path to db556 err = e.DB.UpdateUsersAvatarByLogin(user.Login, "/media/images/"+fileName)557 if err != nil {558 log.Print(err)559 w.WriteHeader(http.StatusInternalServerError)560 response, _ := types.ServerResponse{561 Status: http.StatusText(http.StatusInternalServerError),562 Message: "database_error",563 }.MarshalJSON()564 _, _ = w.Write(response)565 return566 }567 _, _ = io.Copy(f, file)568 w.WriteHeader(http.StatusCreated)569 response, _ := types.ServerResponse{570 Status: http.StatusText(http.StatusCreated),571 Message: "successful_avatar_uploading",572 }.MarshalJSON()573 _, _ = w.Write(response)574}575func (e *Environment) ErrorMethodNotAllowed(w http.ResponseWriter, r *http.Request) {576 _ = r.Body.Close()577 w.WriteHeader(http.StatusMethodNotAllowed)578 response, _ := types.ServerResponse{579 Status: http.StatusText(http.StatusMethodNotAllowed),580 Message: "this_method_is_not_supported",581 }.MarshalJSON()582 _, _ = w.Write(response)583}584func (e *Environment) ErrorRequiredField(w http.ResponseWriter, r *http.Request) {585 _ = r.Body.Close()586 w.WriteHeader(http.StatusBadRequest)587 response, _ := types.ServerResponse{588 Status: http.StatusText(http.StatusBadRequest),589 Message: "field_'temporary'_required",590 }.MarshalJSON()591 _, _ = w.Write(response)592}...

Full Screen

Full Screen

server.go

Source:server.go Github

copy

Full Screen

...36 })37 }38 server.cluster.Store.Unlock()39 response := api.NewOrigins(origins)40 json, err := response.MarshalJSON()41 if err != nil {42 return err43 }44 return c.Send(json)45 })46 app.Get("/api/v1/origins/:originId", func(c *fiber.Ctx) error {47 origin, ok := server.cluster.Store.GetOrigin(c.Params("originId"))48 if !ok {49 response := api.NewErrorResponse("Not found")50 json, err := response.MarshalJSON()51 if err != nil {52 return err53 }54 return c.Send(json)55 }56 response := api.Origin{57 Id: origin.Id,58 }59 json, err := response.MarshalJSON()60 if err != nil {61 return err62 }63 return c.Send(json)64 })65 app.Get("/api/v1/services", func(c *fiber.Ctx) error {66 services := make([]api.Service, 0)67 for _, service := range server.cluster.Store.GetServices() {68 serviceResult := api.Service{69 Id: service.Id,70 Status: api.ServiceStatus{71 Status: service.Status().String(),72 },73 }74 services = append(services, serviceResult)75 }76 response := api.NewServices(services)77 json, err := response.MarshalJSON()78 if err != nil {79 return err80 }81 return c.Send(json)82 })83 app.Get("/api/v1/origins/:originId/services", func(c *fiber.Ctx) error {84 services := make([]api.Service, 0)85 origin, ok := server.cluster.Store.GetOrigin(c.Params("originId"))86 if !ok {87 response := api.NewErrorResponse("Not found")88 json, err := response.MarshalJSON()89 if err != nil {90 return err91 }92 return c.Send(json)93 }94 origin.Lock()95 for _, service := range origin.Services {96 serviceResult := api.Service{97 Id: service.Id,98 }99 services = append(services, serviceResult)100 }101 origin.Unlock()102 response := api.NewServices(services)103 json, err := response.MarshalJSON()104 if err != nil {105 return err106 }107 return c.Send(json)108 })109 app.Get("/api/v1/origins/:originId/services/:serviceId", func(c *fiber.Ctx) error {110 origin, ok := server.cluster.Store.GetOrigin(c.Params("originId"))111 if !ok {112 response := api.NewErrorResponse("Not found")113 json, err := response.MarshalJSON()114 if err != nil {115 return err116 }117 return c.Status(404).Send(json)118 }119 service, ok := origin.GetService(c.Params("serviceId"))120 if !ok {121 response := api.NewErrorResponse("Not found")122 json, err := response.MarshalJSON()123 if err != nil {124 return err125 }126 return c.Status(404).Send(json)127 }128 response := api.Service{129 Id: service.Id,130 }131 json, err := response.MarshalJSON()132 if err != nil {133 return err134 }135 return c.Status(200).Send(json)136 })137 app.Get("/api/v1/origins/:originId/services/:serviceId/status", func(c *fiber.Ctx) error {138 origin, ok := server.cluster.Store.GetOrigin(c.Params("originId"))139 if !ok {140 response := api.NewErrorResponse("Not found")141 json, err := response.MarshalJSON()142 if err != nil {143 return err144 }145 return c.Status(404).Send(json)146 }147 service, ok := origin.GetService(c.Params("serviceId"))148 if !ok {149 response := api.NewErrorResponse("Not found")150 json, err := response.MarshalJSON()151 if err != nil {152 return err153 }154 return c.Status(404).Send(json)155 }156 response := api.ServiceStatus{157 Status: service.Status().String(),158 }159 json, err := response.MarshalJSON()160 if err != nil {161 return err162 }163 return c.Status(200).Send(json)164 })165 app.Get("/api/v1/origins/:originId/services/:serviceId/monitors", func(c *fiber.Ctx) error {166 origin, ok := server.cluster.Store.GetOrigin(c.Params("originId"))167 if !ok {168 response := api.NewErrorResponse("Not found")169 json, err := response.MarshalJSON()170 if err != nil {171 return err172 }173 return c.Status(404).Send(json)174 }175 service, ok := origin.GetService(c.Params("serviceId"))176 if !ok {177 response := api.NewErrorResponse("Not found")178 json, err := response.MarshalJSON()179 if err != nil {180 return err181 }182 return c.Status(404).Send(json)183 }184 service.Lock()185 monitors := make([]api.Monitor, 0)186 for _, monitor := range service.Monitors {187 monitors = append(monitors, api.Monitor{188 Id: monitor.Id,189 })190 }191 service.Unlock()192 response := api.NewMonitors(monitors)193 json, err := response.MarshalJSON()194 if err != nil {195 return err196 }197 return c.Status(200).Send(json)198 })199 app.Get("/api/v1/origins/:originId/services/:serviceId/monitors/:monitorId", func(c *fiber.Ctx) error {200 origin, ok := server.cluster.Store.GetOrigin(c.Params("originId"))201 if !ok {202 response := api.NewErrorResponse("Not found")203 json, err := response.MarshalJSON()204 if err != nil {205 return err206 }207 return c.Status(404).Send(json)208 }209 service, ok := origin.GetService(c.Params("serviceId"))210 if !ok {211 response := api.NewErrorResponse("Not found")212 json, err := response.MarshalJSON()213 if err != nil {214 return err215 }216 return c.Status(404).Send(json)217 }218 monitor, ok := service.GetMonitor(c.Params("monitorId"))219 if !ok {220 response := api.NewErrorResponse("Not found")221 json, err := response.MarshalJSON()222 if err != nil {223 return err224 }225 return c.Status(404).Send(json)226 }227 response := api.Monitor{228 Id: monitor.Id,229 }230 json, err := response.MarshalJSON()231 if err != nil {232 return err233 }234 return c.Status(200).Send(json)235 })236 app.Get("/api/v1/origins/:originId/services/:serviceId/monitors/:monitorId/status", func(c *fiber.Ctx) error {237 origin, ok := server.cluster.Store.GetOrigin(c.Params("originId"))238 if !ok {239 response := api.NewErrorResponse("Not found")240 json, err := response.MarshalJSON()241 if err != nil {242 return err243 }244 return c.Status(404).Send(json)245 }246 service, ok := origin.GetService(c.Params("serviceId"))247 if !ok {248 response := api.NewErrorResponse("Not found")249 json, err := response.MarshalJSON()250 if err != nil {251 return err252 }253 return c.Status(404).Send(json)254 }255 monitor, ok := service.GetMonitor(c.Params("monitorId"))256 if !ok {257 response := api.NewErrorResponse("Not found")258 json, err := response.MarshalJSON()259 if err != nil {260 return err261 }262 return c.Status(404).Send(json)263 }264 status := monitor.Status()265 response := api.MonitorStatus{266 Up: int32(status.Occurances(monitoring.StatusUp)),267 Down: int32(status.Occurances(monitoring.StatusDown)),268 TransitioningUp: int32(status.Occurances(monitoring.StatusTransitioningUp)),269 TransitioningDown: int32(status.Occurances(monitoring.StatusTransitioningDown)),270 }271 json, err := response.MarshalJSON()272 if err != nil {273 return err274 }275 return c.Status(200).Send(json)276 })277 app.Get("/api/v1/peers", func(c *fiber.Ctx) error {278 peers := make([]api.Peer, len(server.cluster.Memberlist.Members()))279 fmt.Printf("Got %d members vs %d members", server.cluster.Memberlist.NumMembers(), len(server.cluster.Memberlist.Members()))280 for i, member := range server.cluster.Memberlist.Members() {281 peer := api.Peer{282 Name: member.Name,283 Bind: member.FullAddress().Addr,284 Status: fmt.Sprintf("%d", member.State),285 }286 peers[i] = peer287 }288 response := api.NewPeers(peers)289 json, err := response.MarshalJSON()290 if err != nil {291 return err292 }293 return c.Send(json)294 })295 app.Get("/api/v1/peers/:peerId", func(c *fiber.Ctx) error {296 response := api.NewErrorResponse("Not found")297 json, err := response.MarshalJSON()298 if err != nil {299 return err300 }301 return c.Status(404).Send(json)302 })303 log.Infof("starting API server on %s", bind)304 return app.Listen(bind)305}...

Full Screen

Full Screen

MarshalJSON

Using AI Code Generation

copy

Full Screen

1var v1 = &v1{}2b, err := json.Marshal(v1)3if err != nil {4}5fmt.Println(string(b))6var v2 = &v2{}7b, err := json.Marshal(v2)8if err != nil {9}10fmt.Println(string(b))11var v1 = &v1{}12b, err := json.Marshal(v1)13if err != nil {14}15fmt.Println(string(b))16var v2 = &v2{}17b, err := json.Marshal(v2)18if err != nil {19}20fmt.Println(string(b))21var v3 = &v3{}22b, err := json.Marshal(v3)23if err != nil {24}25fmt.Println(string(b))26var v1 = &v1{}27b, err := json.Marshal(v1)28if err != nil {29}30fmt.Println(string(b))31var v2 = &v2{}32b, err := json.Marshal(v2)33if err != nil {34}35fmt.Println(string(b))36var v3 = &v3{}37b, err := json.Marshal(v3)38if err != nil {39}40fmt.Println(string(b))

Full Screen

Full Screen

MarshalJSON

Using AI Code Generation

copy

Full Screen

1v1, err = v1.NewV1()2if err != nil {3 panic(err)4}5data, err := json.Marshal(v1)6if err != nil {7 panic(err)8}9fmt.Println(string(data))10{"name":"v1","age":10,"address":"v1 address"}11v2, err = v2.NewV2()12if err != nil {13 panic(err)14}15data, err := json.Marshal(v2)16if err != nil {17 panic(err)18}19fmt.Println(string(data))20{"name":"v2","age":20,"address":"v2 address"}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful