github.com/gogf/gf@v1.16.9/net/ghttp/ghttp_unit_router_object_rest1_test.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/gogf/gf. 6 7 package ghttp_test 8 9 import ( 10 "fmt" 11 "testing" 12 "time" 13 14 "github.com/gogf/gf/frame/g" 15 "github.com/gogf/gf/net/ghttp" 16 "github.com/gogf/gf/test/gtest" 17 ) 18 19 type ObjectRest struct{} 20 21 func (o *ObjectRest) Init(r *ghttp.Request) { 22 r.Response.Write("1") 23 } 24 25 func (o *ObjectRest) Shut(r *ghttp.Request) { 26 r.Response.Write("2") 27 } 28 29 func (o *ObjectRest) Get(r *ghttp.Request) { 30 r.Response.Write("Object Get") 31 } 32 33 func (o *ObjectRest) Put(r *ghttp.Request) { 34 r.Response.Write("Object Put") 35 } 36 37 func (o *ObjectRest) Post(r *ghttp.Request) { 38 r.Response.Write("Object Post") 39 } 40 41 func (o *ObjectRest) Delete(r *ghttp.Request) { 42 r.Response.Write("Object Delete") 43 } 44 45 func (o *ObjectRest) Patch(r *ghttp.Request) { 46 r.Response.Write("Object Patch") 47 } 48 49 func (o *ObjectRest) Options(r *ghttp.Request) { 50 r.Response.Write("Object Options") 51 } 52 53 func (o *ObjectRest) Head(r *ghttp.Request) { 54 r.Response.Header().Set("head-ok", "1") 55 } 56 57 func Test_Router_ObjectRest(t *testing.T) { 58 p, _ := ports.PopRand() 59 s := g.Server(p) 60 s.BindObjectRest("/", new(ObjectRest)) 61 s.BindObjectRest("/{.struct}/{.method}", new(ObjectRest)) 62 s.SetPort(p) 63 s.SetDumpRouterMap(false) 64 s.Start() 65 defer s.Shutdown() 66 67 time.Sleep(100 * time.Millisecond) 68 gtest.C(t, func(t *gtest.T) { 69 client := g.Client() 70 client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p)) 71 72 t.Assert(client.GetContent("/"), "1Object Get2") 73 t.Assert(client.PutContent("/"), "1Object Put2") 74 t.Assert(client.PostContent("/"), "1Object Post2") 75 t.Assert(client.DeleteContent("/"), "1Object Delete2") 76 t.Assert(client.PatchContent("/"), "1Object Patch2") 77 t.Assert(client.OptionsContent("/"), "1Object Options2") 78 resp1, err := client.Head("/") 79 if err == nil { 80 defer resp1.Close() 81 } 82 t.Assert(err, nil) 83 t.Assert(resp1.Header.Get("head-ok"), "1") 84 85 t.Assert(client.GetContent("/object-rest/get"), "1Object Get2") 86 t.Assert(client.PutContent("/object-rest/put"), "1Object Put2") 87 t.Assert(client.PostContent("/object-rest/post"), "1Object Post2") 88 t.Assert(client.DeleteContent("/object-rest/delete"), "1Object Delete2") 89 t.Assert(client.PatchContent("/object-rest/patch"), "1Object Patch2") 90 t.Assert(client.OptionsContent("/object-rest/options"), "1Object Options2") 91 resp2, err := client.Head("/object-rest/head") 92 if err == nil { 93 defer resp2.Close() 94 } 95 t.Assert(err, nil) 96 t.Assert(resp2.Header.Get("head-ok"), "1") 97 98 t.Assert(client.GetContent("/none-exist"), "Not Found") 99 }) 100 }