github.com/astaxie/beego@v1.12.3/policy.go (about) 1 // Copyright 2016 beego authors. 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 "strings" 19 20 "github.com/astaxie/beego/context" 21 ) 22 23 // PolicyFunc defines a policy function which is invoked before the controller handler is executed. 24 type PolicyFunc func(*context.Context) 25 26 // FindPolicy Find Router info for URL 27 func (p *ControllerRegister) FindPolicy(cont *context.Context) []PolicyFunc { 28 var urlPath = cont.Input.URL() 29 if !BConfig.RouterCaseSensitive { 30 urlPath = strings.ToLower(urlPath) 31 } 32 httpMethod := cont.Input.Method() 33 isWildcard := false 34 // Find policy for current method 35 t, ok := p.policies[httpMethod] 36 // If not found - find policy for whole controller 37 if !ok { 38 t, ok = p.policies["*"] 39 isWildcard = true 40 } 41 if ok { 42 runObjects := t.Match(urlPath, cont) 43 if r, ok := runObjects.([]PolicyFunc); ok { 44 return r 45 } else if !isWildcard { 46 // If no policies found and we checked not for "*" method - try to find it 47 t, ok = p.policies["*"] 48 if ok { 49 runObjects = t.Match(urlPath, cont) 50 if r, ok = runObjects.([]PolicyFunc); ok { 51 return r 52 } 53 } 54 } 55 } 56 return nil 57 } 58 59 func (p *ControllerRegister) addToPolicy(method, pattern string, r ...PolicyFunc) { 60 method = strings.ToUpper(method) 61 p.enablePolicy = true 62 if !BConfig.RouterCaseSensitive { 63 pattern = strings.ToLower(pattern) 64 } 65 if t, ok := p.policies[method]; ok { 66 t.AddRouter(pattern, r) 67 } else { 68 t := NewTree() 69 t.AddRouter(pattern, r) 70 p.policies[method] = t 71 } 72 } 73 74 // Policy Register new policy in beego 75 func Policy(pattern, method string, policy ...PolicyFunc) { 76 BeeApp.Handlers.addToPolicy(method, pattern, policy...) 77 } 78 79 // Find policies and execute if were found 80 func (p *ControllerRegister) execPolicy(cont *context.Context, urlPath string) (started bool) { 81 if !p.enablePolicy { 82 return false 83 } 84 // Find Policy for method 85 policyList := p.FindPolicy(cont) 86 if len(policyList) > 0 { 87 // Run policies 88 for _, runPolicy := range policyList { 89 runPolicy(cont) 90 if cont.ResponseWriter.Started { 91 return true 92 } 93 } 94 return false 95 } 96 return false 97 }