router.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008
  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. package beego
  15. import (
  16. "errors"
  17. "fmt"
  18. "net/http"
  19. "path"
  20. "path/filepath"
  21. "reflect"
  22. "strconv"
  23. "strings"
  24. "sync"
  25. "time"
  26. beecontext "github.com/astaxie/beego/context"
  27. "github.com/astaxie/beego/context/param"
  28. "github.com/astaxie/beego/logs"
  29. "github.com/astaxie/beego/toolbox"
  30. "github.com/astaxie/beego/utils"
  31. )
  32. // default filter execution points
  33. const (
  34. BeforeStatic = iota
  35. BeforeRouter
  36. BeforeExec
  37. AfterExec
  38. FinishRouter
  39. )
  40. const (
  41. routerTypeBeego = iota
  42. routerTypeRESTFul
  43. routerTypeHandler
  44. )
  45. var (
  46. // HTTPMETHOD list the supported http methods.
  47. HTTPMETHOD = map[string]bool{
  48. "GET": true,
  49. "POST": true,
  50. "PUT": true,
  51. "DELETE": true,
  52. "PATCH": true,
  53. "OPTIONS": true,
  54. "HEAD": true,
  55. "TRACE": true,
  56. "CONNECT": true,
  57. "MKCOL": true,
  58. "COPY": true,
  59. "MOVE": true,
  60. "PROPFIND": true,
  61. "PROPPATCH": true,
  62. "LOCK": true,
  63. "UNLOCK": true,
  64. }
  65. // these beego.Controller's methods shouldn't reflect to AutoRouter
  66. exceptMethod = []string{"Init", "Prepare", "Finish", "Render", "RenderString",
  67. "RenderBytes", "Redirect", "Abort", "StopRun", "UrlFor", "ServeJSON", "ServeJSONP",
  68. "ServeYAML", "ServeXML", "Input", "ParseForm", "GetString", "GetStrings", "GetInt", "GetBool",
  69. "GetFloat", "GetFile", "SaveToFile", "StartSession", "SetSession", "GetSession",
  70. "DelSession", "SessionRegenerateID", "DestroySession", "IsAjax", "GetSecureCookie",
  71. "SetSecureCookie", "XsrfToken", "CheckXsrfCookie", "XsrfFormHtml",
  72. "GetControllerAndAction", "ServeFormatted"}
  73. urlPlaceholder = "{{placeholder}}"
  74. // DefaultAccessLogFilter will skip the accesslog if return true
  75. DefaultAccessLogFilter FilterHandler = &logFilter{}
  76. )
  77. // FilterHandler is an interface for
  78. type FilterHandler interface {
  79. Filter(*beecontext.Context) bool
  80. }
  81. // default log filter static file will not show
  82. type logFilter struct {
  83. }
  84. func (l *logFilter) Filter(ctx *beecontext.Context) bool {
  85. requestPath := path.Clean(ctx.Request.URL.Path)
  86. if requestPath == "/favicon.ico" || requestPath == "/robots.txt" {
  87. return true
  88. }
  89. for prefix := range BConfig.WebConfig.StaticDir {
  90. if strings.HasPrefix(requestPath, prefix) {
  91. return true
  92. }
  93. }
  94. return false
  95. }
  96. // ExceptMethodAppend to append a slice's value into "exceptMethod", for controller's methods shouldn't reflect to AutoRouter
  97. func ExceptMethodAppend(action string) {
  98. exceptMethod = append(exceptMethod, action)
  99. }
  100. // ControllerInfo holds information about the controller.
  101. type ControllerInfo struct {
  102. pattern string
  103. controllerType reflect.Type
  104. methods map[string]string
  105. handler http.Handler
  106. runFunction FilterFunc
  107. routerType int
  108. initialize func() ControllerInterface
  109. methodParams []*param.MethodParam
  110. }
  111. // ControllerRegister containers registered router rules, controller handlers and filters.
  112. type ControllerRegister struct {
  113. routers map[string]*Tree
  114. enablePolicy bool
  115. policies map[string]*Tree
  116. enableFilter bool
  117. filters [FinishRouter + 1][]*FilterRouter
  118. pool sync.Pool
  119. }
  120. // NewControllerRegister returns a new ControllerRegister.
  121. func NewControllerRegister() *ControllerRegister {
  122. return &ControllerRegister{
  123. routers: make(map[string]*Tree),
  124. policies: make(map[string]*Tree),
  125. pool: sync.Pool{
  126. New: func() interface{} {
  127. return beecontext.NewContext()
  128. },
  129. },
  130. }
  131. }
  132. // Add controller handler and pattern rules to ControllerRegister.
  133. // usage:
  134. // default methods is the same name as method
  135. // Add("/user",&UserController{})
  136. // Add("/api/list",&RestController{},"*:ListFood")
  137. // Add("/api/create",&RestController{},"post:CreateFood")
  138. // Add("/api/update",&RestController{},"put:UpdateFood")
  139. // Add("/api/delete",&RestController{},"delete:DeleteFood")
  140. // Add("/api",&RestController{},"get,post:ApiFunc"
  141. // Add("/simple",&SimpleController{},"get:GetFunc;post:PostFunc")
  142. func (p *ControllerRegister) Add(pattern string, c ControllerInterface, mappingMethods ...string) {
  143. p.addWithMethodParams(pattern, c, nil, mappingMethods...)
  144. }
  145. func (p *ControllerRegister) addWithMethodParams(pattern string, c ControllerInterface, methodParams []*param.MethodParam, mappingMethods ...string) {
  146. reflectVal := reflect.ValueOf(c)
  147. t := reflect.Indirect(reflectVal).Type()
  148. methods := make(map[string]string)
  149. if len(mappingMethods) > 0 {
  150. semi := strings.Split(mappingMethods[0], ";")
  151. for _, v := range semi {
  152. colon := strings.Split(v, ":")
  153. if len(colon) != 2 {
  154. panic("method mapping format is invalid")
  155. }
  156. comma := strings.Split(colon[0], ",")
  157. for _, m := range comma {
  158. if m == "*" || HTTPMETHOD[strings.ToUpper(m)] {
  159. if val := reflectVal.MethodByName(colon[1]); val.IsValid() {
  160. methods[strings.ToUpper(m)] = colon[1]
  161. } else {
  162. panic("'" + colon[1] + "' method doesn't exist in the controller " + t.Name())
  163. }
  164. } else {
  165. panic(v + " is an invalid method mapping. Method doesn't exist " + m)
  166. }
  167. }
  168. }
  169. }
  170. route := &ControllerInfo{}
  171. route.pattern = pattern
  172. route.methods = methods
  173. route.routerType = routerTypeBeego
  174. route.controllerType = t
  175. route.initialize = func() ControllerInterface {
  176. vc := reflect.New(route.controllerType)
  177. execController, ok := vc.Interface().(ControllerInterface)
  178. if !ok {
  179. panic("controller is not ControllerInterface")
  180. }
  181. elemVal := reflect.ValueOf(c).Elem()
  182. elemType := reflect.TypeOf(c).Elem()
  183. execElem := reflect.ValueOf(execController).Elem()
  184. numOfFields := elemVal.NumField()
  185. for i := 0; i < numOfFields; i++ {
  186. fieldType := elemType.Field(i)
  187. elemField := execElem.FieldByName(fieldType.Name)
  188. if elemField.CanSet() {
  189. fieldVal := elemVal.Field(i)
  190. elemField.Set(fieldVal)
  191. }
  192. }
  193. return execController
  194. }
  195. route.methodParams = methodParams
  196. if len(methods) == 0 {
  197. for m := range HTTPMETHOD {
  198. p.addToRouter(m, pattern, route)
  199. }
  200. } else {
  201. for k := range methods {
  202. if k == "*" {
  203. for m := range HTTPMETHOD {
  204. p.addToRouter(m, pattern, route)
  205. }
  206. } else {
  207. p.addToRouter(k, pattern, route)
  208. }
  209. }
  210. }
  211. }
  212. func (p *ControllerRegister) addToRouter(method, pattern string, r *ControllerInfo) {
  213. if !BConfig.RouterCaseSensitive {
  214. pattern = strings.ToLower(pattern)
  215. }
  216. if t, ok := p.routers[method]; ok {
  217. t.AddRouter(pattern, r)
  218. } else {
  219. t := NewTree()
  220. t.AddRouter(pattern, r)
  221. p.routers[method] = t
  222. }
  223. }
  224. // Include only when the Runmode is dev will generate router file in the router/auto.go from the controller
  225. // Include(&BankAccount{}, &OrderController{},&RefundController{},&ReceiptController{})
  226. func (p *ControllerRegister) Include(cList ...ControllerInterface) {
  227. if BConfig.RunMode == DEV {
  228. skip := make(map[string]bool, 10)
  229. for _, c := range cList {
  230. reflectVal := reflect.ValueOf(c)
  231. t := reflect.Indirect(reflectVal).Type()
  232. wgopath := utils.GetGOPATHs()
  233. if len(wgopath) == 0 {
  234. panic("you are in dev mode. So please set gopath")
  235. }
  236. pkgpath := ""
  237. for _, wg := range wgopath {
  238. wg, _ = filepath.EvalSymlinks(filepath.Join(wg, "src", t.PkgPath()))
  239. if utils.FileExists(wg) {
  240. pkgpath = wg
  241. break
  242. }
  243. }
  244. if pkgpath != "" {
  245. if _, ok := skip[pkgpath]; !ok {
  246. skip[pkgpath] = true
  247. parserPkg(pkgpath, t.PkgPath())
  248. }
  249. }
  250. }
  251. }
  252. for _, c := range cList {
  253. reflectVal := reflect.ValueOf(c)
  254. t := reflect.Indirect(reflectVal).Type()
  255. key := t.PkgPath() + ":" + t.Name()
  256. if comm, ok := GlobalControllerRouter[key]; ok {
  257. for _, a := range comm {
  258. for _, f := range a.Filters {
  259. p.InsertFilter(f.Pattern, f.Pos, f.Filter, f.ReturnOnOutput, f.ResetParams)
  260. }
  261. p.addWithMethodParams(a.Router, c, a.MethodParams, strings.Join(a.AllowHTTPMethods, ",")+":"+a.Method)
  262. }
  263. }
  264. }
  265. }
  266. // Get add get method
  267. // usage:
  268. // Get("/", func(ctx *context.Context){
  269. // ctx.Output.Body("hello world")
  270. // })
  271. func (p *ControllerRegister) Get(pattern string, f FilterFunc) {
  272. p.AddMethod("get", pattern, f)
  273. }
  274. // Post add post method
  275. // usage:
  276. // Post("/api", func(ctx *context.Context){
  277. // ctx.Output.Body("hello world")
  278. // })
  279. func (p *ControllerRegister) Post(pattern string, f FilterFunc) {
  280. p.AddMethod("post", pattern, f)
  281. }
  282. // Put add put method
  283. // usage:
  284. // Put("/api/:id", func(ctx *context.Context){
  285. // ctx.Output.Body("hello world")
  286. // })
  287. func (p *ControllerRegister) Put(pattern string, f FilterFunc) {
  288. p.AddMethod("put", pattern, f)
  289. }
  290. // Delete add delete method
  291. // usage:
  292. // Delete("/api/:id", func(ctx *context.Context){
  293. // ctx.Output.Body("hello world")
  294. // })
  295. func (p *ControllerRegister) Delete(pattern string, f FilterFunc) {
  296. p.AddMethod("delete", pattern, f)
  297. }
  298. // Head add head method
  299. // usage:
  300. // Head("/api/:id", func(ctx *context.Context){
  301. // ctx.Output.Body("hello world")
  302. // })
  303. func (p *ControllerRegister) Head(pattern string, f FilterFunc) {
  304. p.AddMethod("head", pattern, f)
  305. }
  306. // Patch add patch method
  307. // usage:
  308. // Patch("/api/:id", func(ctx *context.Context){
  309. // ctx.Output.Body("hello world")
  310. // })
  311. func (p *ControllerRegister) Patch(pattern string, f FilterFunc) {
  312. p.AddMethod("patch", pattern, f)
  313. }
  314. // Options add options method
  315. // usage:
  316. // Options("/api/:id", func(ctx *context.Context){
  317. // ctx.Output.Body("hello world")
  318. // })
  319. func (p *ControllerRegister) Options(pattern string, f FilterFunc) {
  320. p.AddMethod("options", pattern, f)
  321. }
  322. // Any add all method
  323. // usage:
  324. // Any("/api/:id", func(ctx *context.Context){
  325. // ctx.Output.Body("hello world")
  326. // })
  327. func (p *ControllerRegister) Any(pattern string, f FilterFunc) {
  328. p.AddMethod("*", pattern, f)
  329. }
  330. // AddMethod add http method router
  331. // usage:
  332. // AddMethod("get","/api/:id", func(ctx *context.Context){
  333. // ctx.Output.Body("hello world")
  334. // })
  335. func (p *ControllerRegister) AddMethod(method, pattern string, f FilterFunc) {
  336. method = strings.ToUpper(method)
  337. if method != "*" && !HTTPMETHOD[method] {
  338. panic("not support http method: " + method)
  339. }
  340. route := &ControllerInfo{}
  341. route.pattern = pattern
  342. route.routerType = routerTypeRESTFul
  343. route.runFunction = f
  344. methods := make(map[string]string)
  345. if method == "*" {
  346. for val := range HTTPMETHOD {
  347. methods[val] = val
  348. }
  349. } else {
  350. methods[method] = method
  351. }
  352. route.methods = methods
  353. for k := range methods {
  354. if k == "*" {
  355. for m := range HTTPMETHOD {
  356. p.addToRouter(m, pattern, route)
  357. }
  358. } else {
  359. p.addToRouter(k, pattern, route)
  360. }
  361. }
  362. }
  363. // Handler add user defined Handler
  364. func (p *ControllerRegister) Handler(pattern string, h http.Handler, options ...interface{}) {
  365. route := &ControllerInfo{}
  366. route.pattern = pattern
  367. route.routerType = routerTypeHandler
  368. route.handler = h
  369. if len(options) > 0 {
  370. if _, ok := options[0].(bool); ok {
  371. pattern = path.Join(pattern, "?:all(.*)")
  372. }
  373. }
  374. for m := range HTTPMETHOD {
  375. p.addToRouter(m, pattern, route)
  376. }
  377. }
  378. // AddAuto router to ControllerRegister.
  379. // example beego.AddAuto(&MainContorlller{}),
  380. // MainController has method List and Page.
  381. // visit the url /main/list to execute List function
  382. // /main/page to execute Page function.
  383. func (p *ControllerRegister) AddAuto(c ControllerInterface) {
  384. p.AddAutoPrefix("/", c)
  385. }
  386. // AddAutoPrefix Add auto router to ControllerRegister with prefix.
  387. // example beego.AddAutoPrefix("/admin",&MainContorlller{}),
  388. // MainController has method List and Page.
  389. // visit the url /admin/main/list to execute List function
  390. // /admin/main/page to execute Page function.
  391. func (p *ControllerRegister) AddAutoPrefix(prefix string, c ControllerInterface) {
  392. reflectVal := reflect.ValueOf(c)
  393. rt := reflectVal.Type()
  394. ct := reflect.Indirect(reflectVal).Type()
  395. controllerName := strings.TrimSuffix(ct.Name(), "Controller")
  396. for i := 0; i < rt.NumMethod(); i++ {
  397. if !utils.InSlice(rt.Method(i).Name, exceptMethod) {
  398. route := &ControllerInfo{}
  399. route.routerType = routerTypeBeego
  400. route.methods = map[string]string{"*": rt.Method(i).Name}
  401. route.controllerType = ct
  402. pattern := path.Join(prefix, strings.ToLower(controllerName), strings.ToLower(rt.Method(i).Name), "*")
  403. patternInit := path.Join(prefix, controllerName, rt.Method(i).Name, "*")
  404. patternFix := path.Join(prefix, strings.ToLower(controllerName), strings.ToLower(rt.Method(i).Name))
  405. patternFixInit := path.Join(prefix, controllerName, rt.Method(i).Name)
  406. route.pattern = pattern
  407. for m := range HTTPMETHOD {
  408. p.addToRouter(m, pattern, route)
  409. p.addToRouter(m, patternInit, route)
  410. p.addToRouter(m, patternFix, route)
  411. p.addToRouter(m, patternFixInit, route)
  412. }
  413. }
  414. }
  415. }
  416. // InsertFilter Add a FilterFunc with pattern rule and action constant.
  417. // params is for:
  418. // 1. setting the returnOnOutput value (false allows multiple filters to execute)
  419. // 2. determining whether or not params need to be reset.
  420. func (p *ControllerRegister) InsertFilter(pattern string, pos int, filter FilterFunc, params ...bool) error {
  421. mr := &FilterRouter{
  422. tree: NewTree(),
  423. pattern: pattern,
  424. filterFunc: filter,
  425. returnOnOutput: true,
  426. }
  427. if !BConfig.RouterCaseSensitive {
  428. mr.pattern = strings.ToLower(pattern)
  429. }
  430. paramsLen := len(params)
  431. if paramsLen > 0 {
  432. mr.returnOnOutput = params[0]
  433. }
  434. if paramsLen > 1 {
  435. mr.resetParams = params[1]
  436. }
  437. mr.tree.AddRouter(pattern, true)
  438. return p.insertFilterRouter(pos, mr)
  439. }
  440. // add Filter into
  441. func (p *ControllerRegister) insertFilterRouter(pos int, mr *FilterRouter) (err error) {
  442. if pos < BeforeStatic || pos > FinishRouter {
  443. return errors.New("can not find your filter position")
  444. }
  445. p.enableFilter = true
  446. p.filters[pos] = append(p.filters[pos], mr)
  447. return nil
  448. }
  449. // URLFor does another controller handler in this request function.
  450. // it can access any controller method.
  451. func (p *ControllerRegister) URLFor(endpoint string, values ...interface{}) string {
  452. paths := strings.Split(endpoint, ".")
  453. if len(paths) <= 1 {
  454. logs.Warn("urlfor endpoint must like path.controller.method")
  455. return ""
  456. }
  457. if len(values)%2 != 0 {
  458. logs.Warn("urlfor params must key-value pair")
  459. return ""
  460. }
  461. params := make(map[string]string)
  462. if len(values) > 0 {
  463. key := ""
  464. for k, v := range values {
  465. if k%2 == 0 {
  466. key = fmt.Sprint(v)
  467. } else {
  468. params[key] = fmt.Sprint(v)
  469. }
  470. }
  471. }
  472. controllerName := strings.Join(paths[:len(paths)-1], "/")
  473. methodName := paths[len(paths)-1]
  474. for m, t := range p.routers {
  475. ok, url := p.getURL(t, "/", controllerName, methodName, params, m)
  476. if ok {
  477. return url
  478. }
  479. }
  480. return ""
  481. }
  482. func (p *ControllerRegister) getURL(t *Tree, url, controllerName, methodName string, params map[string]string, httpMethod string) (bool, string) {
  483. for _, subtree := range t.fixrouters {
  484. u := path.Join(url, subtree.prefix)
  485. ok, u := p.getURL(subtree, u, controllerName, methodName, params, httpMethod)
  486. if ok {
  487. return ok, u
  488. }
  489. }
  490. if t.wildcard != nil {
  491. u := path.Join(url, urlPlaceholder)
  492. ok, u := p.getURL(t.wildcard, u, controllerName, methodName, params, httpMethod)
  493. if ok {
  494. return ok, u
  495. }
  496. }
  497. for _, l := range t.leaves {
  498. if c, ok := l.runObject.(*ControllerInfo); ok {
  499. if c.routerType == routerTypeBeego &&
  500. strings.HasSuffix(path.Join(c.controllerType.PkgPath(), c.controllerType.Name()), controllerName) {
  501. find := false
  502. if HTTPMETHOD[strings.ToUpper(methodName)] {
  503. if len(c.methods) == 0 {
  504. find = true
  505. } else if m, ok := c.methods[strings.ToUpper(methodName)]; ok && m == strings.ToUpper(methodName) {
  506. find = true
  507. } else if m, ok = c.methods["*"]; ok && m == methodName {
  508. find = true
  509. }
  510. }
  511. if !find {
  512. for m, md := range c.methods {
  513. if (m == "*" || m == httpMethod) && md == methodName {
  514. find = true
  515. }
  516. }
  517. }
  518. if find {
  519. if l.regexps == nil {
  520. if len(l.wildcards) == 0 {
  521. return true, strings.Replace(url, "/"+urlPlaceholder, "", 1) + toURL(params)
  522. }
  523. if len(l.wildcards) == 1 {
  524. if v, ok := params[l.wildcards[0]]; ok {
  525. delete(params, l.wildcards[0])
  526. return true, strings.Replace(url, urlPlaceholder, v, 1) + toURL(params)
  527. }
  528. return false, ""
  529. }
  530. if len(l.wildcards) == 3 && l.wildcards[0] == "." {
  531. if p, ok := params[":path"]; ok {
  532. if e, isok := params[":ext"]; isok {
  533. delete(params, ":path")
  534. delete(params, ":ext")
  535. return true, strings.Replace(url, urlPlaceholder, p+"."+e, -1) + toURL(params)
  536. }
  537. }
  538. }
  539. canSkip := false
  540. for _, v := range l.wildcards {
  541. if v == ":" {
  542. canSkip = true
  543. continue
  544. }
  545. if u, ok := params[v]; ok {
  546. delete(params, v)
  547. url = strings.Replace(url, urlPlaceholder, u, 1)
  548. } else {
  549. if canSkip {
  550. canSkip = false
  551. continue
  552. }
  553. return false, ""
  554. }
  555. }
  556. return true, url + toURL(params)
  557. }
  558. var i int
  559. var startReg bool
  560. regURL := ""
  561. for _, v := range strings.Trim(l.regexps.String(), "^$") {
  562. if v == '(' {
  563. startReg = true
  564. continue
  565. } else if v == ')' {
  566. startReg = false
  567. if v, ok := params[l.wildcards[i]]; ok {
  568. delete(params, l.wildcards[i])
  569. regURL = regURL + v
  570. i++
  571. } else {
  572. break
  573. }
  574. } else if !startReg {
  575. regURL = string(append([]rune(regURL), v))
  576. }
  577. }
  578. if l.regexps.MatchString(regURL) {
  579. ps := strings.Split(regURL, "/")
  580. for _, p := range ps {
  581. url = strings.Replace(url, urlPlaceholder, p, 1)
  582. }
  583. return true, url + toURL(params)
  584. }
  585. }
  586. }
  587. }
  588. }
  589. return false, ""
  590. }
  591. func (p *ControllerRegister) execFilter(context *beecontext.Context, urlPath string, pos int) (started bool) {
  592. var preFilterParams map[string]string
  593. for _, filterR := range p.filters[pos] {
  594. if filterR.returnOnOutput && context.ResponseWriter.Started {
  595. return true
  596. }
  597. if filterR.resetParams {
  598. preFilterParams = context.Input.Params()
  599. }
  600. if ok := filterR.ValidRouter(urlPath, context); ok {
  601. filterR.filterFunc(context)
  602. if filterR.resetParams {
  603. context.Input.ResetParams()
  604. for k, v := range preFilterParams {
  605. context.Input.SetParam(k, v)
  606. }
  607. }
  608. }
  609. if filterR.returnOnOutput && context.ResponseWriter.Started {
  610. return true
  611. }
  612. }
  613. return false
  614. }
  615. // Implement http.Handler interface.
  616. func (p *ControllerRegister) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
  617. startTime := time.Now()
  618. var (
  619. runRouter reflect.Type
  620. findRouter bool
  621. runMethod string
  622. methodParams []*param.MethodParam
  623. routerInfo *ControllerInfo
  624. isRunnable bool
  625. )
  626. context := p.pool.Get().(*beecontext.Context)
  627. context.Reset(rw, r)
  628. defer p.pool.Put(context)
  629. if BConfig.RecoverFunc != nil {
  630. defer BConfig.RecoverFunc(context)
  631. }
  632. context.Output.EnableGzip = BConfig.EnableGzip
  633. if BConfig.RunMode == DEV {
  634. context.Output.Header("Server", BConfig.ServerName)
  635. }
  636. var urlPath = r.URL.Path
  637. if !BConfig.RouterCaseSensitive {
  638. urlPath = strings.ToLower(urlPath)
  639. }
  640. // filter wrong http method
  641. if !HTTPMETHOD[r.Method] {
  642. exception("405", context)
  643. goto Admin
  644. }
  645. // filter for static file
  646. if len(p.filters[BeforeStatic]) > 0 && p.execFilter(context, urlPath, BeforeStatic) {
  647. goto Admin
  648. }
  649. serverStaticRouter(context)
  650. if context.ResponseWriter.Started {
  651. findRouter = true
  652. goto Admin
  653. }
  654. if r.Method != http.MethodGet && r.Method != http.MethodHead {
  655. if BConfig.CopyRequestBody && !context.Input.IsUpload() {
  656. context.Input.CopyBody(BConfig.MaxMemory)
  657. }
  658. context.Input.ParseFormOrMulitForm(BConfig.MaxMemory)
  659. }
  660. // session init
  661. if BConfig.WebConfig.Session.SessionOn {
  662. var err error
  663. context.Input.CruSession, err = GlobalSessions.SessionStart(rw, r)
  664. if err != nil {
  665. logs.Error(err)
  666. exception("503", context)
  667. goto Admin
  668. }
  669. defer func() {
  670. if context.Input.CruSession != nil {
  671. context.Input.CruSession.SessionRelease(rw)
  672. }
  673. }()
  674. }
  675. if len(p.filters[BeforeRouter]) > 0 && p.execFilter(context, urlPath, BeforeRouter) {
  676. goto Admin
  677. }
  678. // User can define RunController and RunMethod in filter
  679. if context.Input.RunController != nil && context.Input.RunMethod != "" {
  680. findRouter = true
  681. runMethod = context.Input.RunMethod
  682. runRouter = context.Input.RunController
  683. } else {
  684. routerInfo, findRouter = p.FindRouter(context)
  685. }
  686. //if no matches to url, throw a not found exception
  687. if !findRouter {
  688. exception("404", context)
  689. goto Admin
  690. }
  691. if splat := context.Input.Param(":splat"); splat != "" {
  692. for k, v := range strings.Split(splat, "/") {
  693. context.Input.SetParam(strconv.Itoa(k), v)
  694. }
  695. }
  696. //execute middleware filters
  697. if len(p.filters[BeforeExec]) > 0 && p.execFilter(context, urlPath, BeforeExec) {
  698. goto Admin
  699. }
  700. //check policies
  701. if p.execPolicy(context, urlPath) {
  702. goto Admin
  703. }
  704. if routerInfo != nil {
  705. //store router pattern into context
  706. context.Input.SetData("RouterPattern", routerInfo.pattern)
  707. if routerInfo.routerType == routerTypeRESTFul {
  708. if _, ok := routerInfo.methods[r.Method]; ok {
  709. isRunnable = true
  710. routerInfo.runFunction(context)
  711. } else {
  712. exception("405", context)
  713. goto Admin
  714. }
  715. } else if routerInfo.routerType == routerTypeHandler {
  716. isRunnable = true
  717. routerInfo.handler.ServeHTTP(rw, r)
  718. } else {
  719. runRouter = routerInfo.controllerType
  720. methodParams = routerInfo.methodParams
  721. method := r.Method
  722. if r.Method == http.MethodPost && context.Input.Query("_method") == http.MethodPut {
  723. method = http.MethodPut
  724. }
  725. if r.Method == http.MethodPost && context.Input.Query("_method") == http.MethodDelete {
  726. method = http.MethodDelete
  727. }
  728. if m, ok := routerInfo.methods[method]; ok {
  729. runMethod = m
  730. } else if m, ok = routerInfo.methods["*"]; ok {
  731. runMethod = m
  732. } else {
  733. runMethod = method
  734. }
  735. }
  736. }
  737. // also defined runRouter & runMethod from filter
  738. if !isRunnable {
  739. //Invoke the request handler
  740. var execController ControllerInterface
  741. if routerInfo != nil && routerInfo.initialize != nil {
  742. execController = routerInfo.initialize()
  743. } else {
  744. vc := reflect.New(runRouter)
  745. var ok bool
  746. execController, ok = vc.Interface().(ControllerInterface)
  747. if !ok {
  748. panic("controller is not ControllerInterface")
  749. }
  750. }
  751. //call the controller init function
  752. execController.Init(context, runRouter.Name(), runMethod, execController)
  753. //call prepare function
  754. execController.Prepare()
  755. //if XSRF is Enable then check cookie where there has any cookie in the request's cookie _csrf
  756. if BConfig.WebConfig.EnableXSRF {
  757. execController.XSRFToken()
  758. if r.Method == http.MethodPost || r.Method == http.MethodDelete || r.Method == http.MethodPut ||
  759. (r.Method == http.MethodPost && (context.Input.Query("_method") == http.MethodDelete || context.Input.Query("_method") == http.MethodPut)) {
  760. execController.CheckXSRFCookie()
  761. }
  762. }
  763. execController.URLMapping()
  764. if !context.ResponseWriter.Started {
  765. //exec main logic
  766. switch runMethod {
  767. case http.MethodGet:
  768. execController.Get()
  769. case http.MethodPost:
  770. execController.Post()
  771. case http.MethodDelete:
  772. execController.Delete()
  773. case http.MethodPut:
  774. execController.Put()
  775. case http.MethodHead:
  776. execController.Head()
  777. case http.MethodPatch:
  778. execController.Patch()
  779. case http.MethodOptions:
  780. execController.Options()
  781. case http.MethodTrace:
  782. execController.Trace()
  783. default:
  784. if !execController.HandlerFunc(runMethod) {
  785. vc := reflect.ValueOf(execController)
  786. method := vc.MethodByName(runMethod)
  787. in := param.ConvertParams(methodParams, method.Type(), context)
  788. out := method.Call(in)
  789. //For backward compatibility we only handle response if we had incoming methodParams
  790. if methodParams != nil {
  791. p.handleParamResponse(context, execController, out)
  792. }
  793. }
  794. }
  795. //render template
  796. if !context.ResponseWriter.Started && context.Output.Status == 0 {
  797. if BConfig.WebConfig.AutoRender {
  798. if err := execController.Render(); err != nil {
  799. logs.Error(err)
  800. }
  801. }
  802. }
  803. }
  804. // finish all runRouter. release resource
  805. execController.Finish()
  806. }
  807. //execute middleware filters
  808. if len(p.filters[AfterExec]) > 0 && p.execFilter(context, urlPath, AfterExec) {
  809. goto Admin
  810. }
  811. if len(p.filters[FinishRouter]) > 0 && p.execFilter(context, urlPath, FinishRouter) {
  812. goto Admin
  813. }
  814. Admin:
  815. //admin module record QPS
  816. statusCode := context.ResponseWriter.Status
  817. if statusCode == 0 {
  818. statusCode = 200
  819. }
  820. LogAccess(context, &startTime, statusCode)
  821. timeDur := time.Since(startTime)
  822. context.ResponseWriter.Elapsed = timeDur
  823. if BConfig.Listen.EnableAdmin {
  824. pattern := ""
  825. if routerInfo != nil {
  826. pattern = routerInfo.pattern
  827. }
  828. if FilterMonitorFunc(r.Method, r.URL.Path, timeDur, pattern, statusCode) {
  829. routerName := ""
  830. if runRouter != nil {
  831. routerName = runRouter.Name()
  832. }
  833. go toolbox.StatisticsMap.AddStatistics(r.Method, r.URL.Path, routerName, timeDur)
  834. }
  835. }
  836. if BConfig.RunMode == DEV && !BConfig.Log.AccessLogs {
  837. match := map[bool]string{true: "match", false: "nomatch"}
  838. devInfo := fmt.Sprintf("|%15s|%s %3d %s|%13s|%8s|%s %-7s %s %-3s",
  839. context.Input.IP(),
  840. logs.ColorByStatus(statusCode), statusCode, logs.ResetColor(),
  841. timeDur.String(),
  842. match[findRouter],
  843. logs.ColorByMethod(r.Method), r.Method, logs.ResetColor(),
  844. r.URL.Path)
  845. if routerInfo != nil {
  846. devInfo += fmt.Sprintf(" r:%s", routerInfo.pattern)
  847. }
  848. logs.Debug(devInfo)
  849. }
  850. // Call WriteHeader if status code has been set changed
  851. if context.Output.Status != 0 {
  852. context.ResponseWriter.WriteHeader(context.Output.Status)
  853. }
  854. }
  855. func (p *ControllerRegister) handleParamResponse(context *beecontext.Context, execController ControllerInterface, results []reflect.Value) {
  856. //looping in reverse order for the case when both error and value are returned and error sets the response status code
  857. for i := len(results) - 1; i >= 0; i-- {
  858. result := results[i]
  859. if result.Kind() != reflect.Interface || !result.IsNil() {
  860. resultValue := result.Interface()
  861. context.RenderMethodResult(resultValue)
  862. }
  863. }
  864. if !context.ResponseWriter.Started && len(results) > 0 && context.Output.Status == 0 {
  865. context.Output.SetStatus(200)
  866. }
  867. }
  868. // FindRouter Find Router info for URL
  869. func (p *ControllerRegister) FindRouter(context *beecontext.Context) (routerInfo *ControllerInfo, isFind bool) {
  870. var urlPath = context.Input.URL()
  871. if !BConfig.RouterCaseSensitive {
  872. urlPath = strings.ToLower(urlPath)
  873. }
  874. httpMethod := context.Input.Method()
  875. if t, ok := p.routers[httpMethod]; ok {
  876. runObject := t.Match(urlPath, context)
  877. if r, ok := runObject.(*ControllerInfo); ok {
  878. return r, true
  879. }
  880. }
  881. return
  882. }
  883. func toURL(params map[string]string) string {
  884. if len(params) == 0 {
  885. return ""
  886. }
  887. u := "?"
  888. for k, v := range params {
  889. u += k + "=" + v + "&"
  890. }
  891. return strings.TrimRight(u, "&")
  892. }
  893. // LogAccess logging info HTTP Access
  894. func LogAccess(ctx *beecontext.Context, startTime *time.Time, statusCode int) {
  895. //Skip logging if AccessLogs config is false
  896. if !BConfig.Log.AccessLogs {
  897. return
  898. }
  899. //Skip logging static requests unless EnableStaticLogs config is true
  900. if !BConfig.Log.EnableStaticLogs && DefaultAccessLogFilter.Filter(ctx) {
  901. return
  902. }
  903. var (
  904. requestTime time.Time
  905. elapsedTime time.Duration
  906. r = ctx.Request
  907. )
  908. if startTime != nil {
  909. requestTime = *startTime
  910. elapsedTime = time.Since(*startTime)
  911. }
  912. record := &logs.AccessLogRecord{
  913. RemoteAddr: ctx.Input.IP(),
  914. RequestTime: requestTime,
  915. RequestMethod: r.Method,
  916. Request: fmt.Sprintf("%s %s %s", r.Method, r.RequestURI, r.Proto),
  917. ServerProtocol: r.Proto,
  918. Host: r.Host,
  919. Status: statusCode,
  920. ElapsedTime: elapsedTime,
  921. HTTPReferrer: r.Header.Get("Referer"),
  922. HTTPUserAgent: r.Header.Get("User-Agent"),
  923. RemoteUser: r.Header.Get("Remote-User"),
  924. BodyBytesSent: 0, //@todo this one is missing!
  925. }
  926. logs.AccessLog(record, BConfig.Log.AccessLogsFormat)
  927. }