github.com/astaxie/beego@v1.12.3/filter_test.go (about) 1 // Copyright 2014 beego Author. All Rights Reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package beego 16 17 import ( 18 "net/http" 19 "net/http/httptest" 20 "testing" 21 22 "github.com/astaxie/beego/context" 23 ) 24 25 var FilterUser = func(ctx *context.Context) { 26 ctx.Output.Body([]byte("i am " + ctx.Input.Param(":last") + ctx.Input.Param(":first"))) 27 } 28 29 func TestFilter(t *testing.T) { 30 r, _ := http.NewRequest("GET", "/person/asta/Xie", nil) 31 w := httptest.NewRecorder() 32 handler := NewControllerRegister() 33 handler.InsertFilter("/person/:last/:first", BeforeRouter, FilterUser) 34 handler.Add("/person/:last/:first", &TestController{}) 35 handler.ServeHTTP(w, r) 36 if w.Body.String() != "i am astaXie" { 37 t.Errorf("user define func can't run") 38 } 39 } 40 41 var FilterAdminUser = func(ctx *context.Context) { 42 ctx.Output.Body([]byte("i am admin")) 43 } 44 45 // Filter pattern /admin/:all 46 // all url like /admin/ /admin/xie will all get filter 47 48 func TestPatternTwo(t *testing.T) { 49 r, _ := http.NewRequest("GET", "/admin/", nil) 50 w := httptest.NewRecorder() 51 handler := NewControllerRegister() 52 handler.InsertFilter("/admin/?:all", BeforeRouter, FilterAdminUser) 53 handler.ServeHTTP(w, r) 54 if w.Body.String() != "i am admin" { 55 t.Errorf("filter /admin/ can't run") 56 } 57 } 58 59 func TestPatternThree(t *testing.T) { 60 r, _ := http.NewRequest("GET", "/admin/astaxie", nil) 61 w := httptest.NewRecorder() 62 handler := NewControllerRegister() 63 handler.InsertFilter("/admin/:all", BeforeRouter, FilterAdminUser) 64 handler.ServeHTTP(w, r) 65 if w.Body.String() != "i am admin" { 66 t.Errorf("filter /admin/astaxie can't run") 67 } 68 }