1
0

router.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  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. "fmt"
  17. "net/http"
  18. "os"
  19. "path"
  20. "path/filepath"
  21. "reflect"
  22. "runtime"
  23. "strconv"
  24. "strings"
  25. "sync"
  26. "time"
  27. beecontext "github.com/astaxie/beego/context"
  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]string{
  48. "GET": "GET",
  49. "POST": "POST",
  50. "PUT": "PUT",
  51. "DELETE": "DELETE",
  52. "PATCH": "PATCH",
  53. "OPTIONS": "OPTIONS",
  54. "HEAD": "HEAD",
  55. "TRACE": "TRACE",
  56. "CONNECT": "CONNECT",
  57. "MKCOL": "MKCOL",
  58. "COPY": "COPY",
  59. "MOVE": "MOVE",
  60. "PROPFIND": "PROPFIND",
  61. "PROPPATCH": "PROPPATCH",
  62. "LOCK": "LOCK",
  63. "UNLOCK": "UNLOCK",
  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. "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. type controllerInfo struct {
  101. pattern string
  102. controllerType reflect.Type
  103. methods map[string]string
  104. handler http.Handler
  105. runFunction FilterFunc
  106. routerType int
  107. }
  108. // ControllerRegister containers registered router rules, controller handlers and filters.
  109. type ControllerRegister struct {
  110. routers map[string]*Tree
  111. enablePolicy bool
  112. policies map[string]*Tree
  113. enableFilter bool
  114. filters [FinishRouter + 1][]*FilterRouter
  115. pool sync.Pool
  116. }
  117. // NewControllerRegister returns a new ControllerRegister.
  118. func NewControllerRegister() *ControllerRegister {
  119. cr := &ControllerRegister{
  120. routers: make(map[string]*Tree),
  121. policies: make(map[string]*Tree),
  122. }
  123. cr.pool.New = func() interface{} {
  124. return beecontext.NewContext()
  125. }
  126. return cr
  127. }
  128. // Add controller handler and pattern rules to ControllerRegister.
  129. // usage:
  130. // default methods is the same name as method
  131. // Add("/user",&UserController{})
  132. // Add("/api/list",&RestController{},"*:ListFood")
  133. // Add("/api/create",&RestController{},"post:CreateFood")
  134. // Add("/api/update",&RestController{},"put:UpdateFood")
  135. // Add("/api/delete",&RestController{},"delete:DeleteFood")
  136. // Add("/api",&RestController{},"get,post:ApiFunc"
  137. // Add("/simple",&SimpleController{},"get:GetFunc;post:PostFunc")
  138. func (p *ControllerRegister) Add(pattern string, c ControllerInterface, mappingMethods ...string) {
  139. reflectVal := reflect.ValueOf(c)
  140. t := reflect.Indirect(reflectVal).Type()
  141. methods := make(map[string]string)
  142. if len(mappingMethods) > 0 {
  143. semi := strings.Split(mappingMethods[0], ";")
  144. for _, v := range semi {
  145. colon := strings.Split(v, ":")
  146. if len(colon) != 2 {
  147. panic("method mapping format is invalid")
  148. }
  149. comma := strings.Split(colon[0], ",")
  150. for _, m := range comma {
  151. if _, ok := HTTPMETHOD[strings.ToUpper(m)]; m == "*" || ok {
  152. if val := reflectVal.MethodByName(colon[1]); val.IsValid() {
  153. methods[strings.ToUpper(m)] = colon[1]
  154. } else {
  155. panic("'" + colon[1] + "' method doesn't exist in the controller " + t.Name())
  156. }
  157. } else {
  158. panic(v + " is an invalid method mapping. Method doesn't exist " + m)
  159. }
  160. }
  161. }
  162. }
  163. route := &controllerInfo{}
  164. route.pattern = pattern
  165. route.methods = methods
  166. route.routerType = routerTypeBeego
  167. route.controllerType = t
  168. if len(methods) == 0 {
  169. for _, m := range HTTPMETHOD {
  170. p.addToRouter(m, pattern, route)
  171. }
  172. } else {
  173. for k := range methods {
  174. if k == "*" {
  175. for _, m := range HTTPMETHOD {
  176. p.addToRouter(m, pattern, route)
  177. }
  178. } else {
  179. p.addToRouter(k, pattern, route)
  180. }
  181. }
  182. }
  183. }
  184. func (p *ControllerRegister) addToRouter(method, pattern string, r *controllerInfo) {
  185. if !BConfig.RouterCaseSensitive {
  186. pattern = strings.ToLower(pattern)
  187. }
  188. if t, ok := p.routers[method]; ok {
  189. t.AddRouter(pattern, r)
  190. } else {
  191. t := NewTree()
  192. t.AddRouter(pattern, r)
  193. p.routers[method] = t
  194. }
  195. }
  196. // Include only when the Runmode is dev will generate router file in the router/auto.go from the controller
  197. // Include(&BankAccount{}, &OrderController{},&RefundController{},&ReceiptController{})
  198. func (p *ControllerRegister) Include(cList ...ControllerInterface) {
  199. if BConfig.RunMode == DEV {
  200. skip := make(map[string]bool, 10)
  201. for _, c := range cList {
  202. reflectVal := reflect.ValueOf(c)
  203. t := reflect.Indirect(reflectVal).Type()
  204. gopath := os.Getenv("GOPATH")
  205. if gopath == "" {
  206. panic("you are in dev mode. So please set gopath")
  207. }
  208. pkgpath := ""
  209. wgopath := filepath.SplitList(gopath)
  210. for _, wg := range wgopath {
  211. wg, _ = filepath.EvalSymlinks(filepath.Join(wg, "src", t.PkgPath()))
  212. if utils.FileExists(wg) {
  213. pkgpath = wg
  214. break
  215. }
  216. }
  217. if pkgpath != "" {
  218. if _, ok := skip[pkgpath]; !ok {
  219. skip[pkgpath] = true
  220. parserPkg(pkgpath, t.PkgPath())
  221. }
  222. }
  223. }
  224. }
  225. for _, c := range cList {
  226. reflectVal := reflect.ValueOf(c)
  227. t := reflect.Indirect(reflectVal).Type()
  228. key := t.PkgPath() + ":" + t.Name()
  229. if comm, ok := GlobalControllerRouter[key]; ok {
  230. for _, a := range comm {
  231. p.Add(a.Router, c, strings.Join(a.AllowHTTPMethods, ",")+":"+a.Method)
  232. }
  233. }
  234. }
  235. }
  236. // Get add get method
  237. // usage:
  238. // Get("/", func(ctx *context.Context){
  239. // ctx.Output.Body("hello world")
  240. // })
  241. func (p *ControllerRegister) Get(pattern string, f FilterFunc) {
  242. p.AddMethod("get", pattern, f)
  243. }
  244. // Post add post method
  245. // usage:
  246. // Post("/api", func(ctx *context.Context){
  247. // ctx.Output.Body("hello world")
  248. // })
  249. func (p *ControllerRegister) Post(pattern string, f FilterFunc) {
  250. p.AddMethod("post", pattern, f)
  251. }
  252. // Put add put method
  253. // usage:
  254. // Put("/api/:id", func(ctx *context.Context){
  255. // ctx.Output.Body("hello world")
  256. // })
  257. func (p *ControllerRegister) Put(pattern string, f FilterFunc) {
  258. p.AddMethod("put", pattern, f)
  259. }
  260. // Delete add delete method
  261. // usage:
  262. // Delete("/api/:id", func(ctx *context.Context){
  263. // ctx.Output.Body("hello world")
  264. // })
  265. func (p *ControllerRegister) Delete(pattern string, f FilterFunc) {
  266. p.AddMethod("delete", pattern, f)
  267. }
  268. // Head add head method
  269. // usage:
  270. // Head("/api/:id", func(ctx *context.Context){
  271. // ctx.Output.Body("hello world")
  272. // })
  273. func (p *ControllerRegister) Head(pattern string, f FilterFunc) {
  274. p.AddMethod("head", pattern, f)
  275. }
  276. // Patch add patch method
  277. // usage:
  278. // Patch("/api/:id", func(ctx *context.Context){
  279. // ctx.Output.Body("hello world")
  280. // })
  281. func (p *ControllerRegister) Patch(pattern string, f FilterFunc) {
  282. p.AddMethod("patch", pattern, f)
  283. }
  284. // Options add options method
  285. // usage:
  286. // Options("/api/:id", func(ctx *context.Context){
  287. // ctx.Output.Body("hello world")
  288. // })
  289. func (p *ControllerRegister) Options(pattern string, f FilterFunc) {
  290. p.AddMethod("options", pattern, f)
  291. }
  292. // Any add all method
  293. // usage:
  294. // Any("/api/:id", func(ctx *context.Context){
  295. // ctx.Output.Body("hello world")
  296. // })
  297. func (p *ControllerRegister) Any(pattern string, f FilterFunc) {
  298. p.AddMethod("*", pattern, f)
  299. }
  300. // AddMethod add http method router
  301. // usage:
  302. // AddMethod("get","/api/:id", func(ctx *context.Context){
  303. // ctx.Output.Body("hello world")
  304. // })
  305. func (p *ControllerRegister) AddMethod(method, pattern string, f FilterFunc) {
  306. method = strings.ToUpper(method)
  307. if _, ok := HTTPMETHOD[method]; method != "*" && !ok {
  308. panic("not support http method: " + method)
  309. }
  310. route := &controllerInfo{}
  311. route.pattern = pattern
  312. route.routerType = routerTypeRESTFul
  313. route.runFunction = f
  314. methods := make(map[string]string)
  315. if method == "*" {
  316. for _, val := range HTTPMETHOD {
  317. methods[val] = val
  318. }
  319. } else {
  320. methods[method] = method
  321. }
  322. route.methods = methods
  323. for k := range methods {
  324. if k == "*" {
  325. for _, m := range HTTPMETHOD {
  326. p.addToRouter(m, pattern, route)
  327. }
  328. } else {
  329. p.addToRouter(k, pattern, route)
  330. }
  331. }
  332. }
  333. // Handler add user defined Handler
  334. func (p *ControllerRegister) Handler(pattern string, h http.Handler, options ...interface{}) {
  335. route := &controllerInfo{}
  336. route.pattern = pattern
  337. route.routerType = routerTypeHandler
  338. route.handler = h
  339. if len(options) > 0 {
  340. if _, ok := options[0].(bool); ok {
  341. pattern = path.Join(pattern, "?:all(.*)")
  342. }
  343. }
  344. for _, m := range HTTPMETHOD {
  345. p.addToRouter(m, pattern, route)
  346. }
  347. }
  348. // AddAuto router to ControllerRegister.
  349. // example beego.AddAuto(&MainContorlller{}),
  350. // MainController has method List and Page.
  351. // visit the url /main/list to execute List function
  352. // /main/page to execute Page function.
  353. func (p *ControllerRegister) AddAuto(c ControllerInterface) {
  354. p.AddAutoPrefix("/", c)
  355. }
  356. // AddAutoPrefix Add auto router to ControllerRegister with prefix.
  357. // example beego.AddAutoPrefix("/admin",&MainContorlller{}),
  358. // MainController has method List and Page.
  359. // visit the url /admin/main/list to execute List function
  360. // /admin/main/page to execute Page function.
  361. func (p *ControllerRegister) AddAutoPrefix(prefix string, c ControllerInterface) {
  362. reflectVal := reflect.ValueOf(c)
  363. rt := reflectVal.Type()
  364. ct := reflect.Indirect(reflectVal).Type()
  365. controllerName := strings.TrimSuffix(ct.Name(), "Controller")
  366. for i := 0; i < rt.NumMethod(); i++ {
  367. if !utils.InSlice(rt.Method(i).Name, exceptMethod) {
  368. route := &controllerInfo{}
  369. route.routerType = routerTypeBeego
  370. route.methods = map[string]string{"*": rt.Method(i).Name}
  371. route.controllerType = ct
  372. pattern := path.Join(prefix, strings.ToLower(controllerName), strings.ToLower(rt.Method(i).Name), "*")
  373. patternInit := path.Join(prefix, controllerName, rt.Method(i).Name, "*")
  374. patternFix := path.Join(prefix, strings.ToLower(controllerName), strings.ToLower(rt.Method(i).Name))
  375. patternFixInit := path.Join(prefix, controllerName, rt.Method(i).Name)
  376. route.pattern = pattern
  377. for _, m := range HTTPMETHOD {
  378. p.addToRouter(m, pattern, route)
  379. p.addToRouter(m, patternInit, route)
  380. p.addToRouter(m, patternFix, route)
  381. p.addToRouter(m, patternFixInit, route)
  382. }
  383. }
  384. }
  385. }
  386. // InsertFilter Add a FilterFunc with pattern rule and action constant.
  387. // params is for:
  388. // 1. setting the returnOnOutput value (false allows multiple filters to execute)
  389. // 2. determining whether or not params need to be reset.
  390. func (p *ControllerRegister) InsertFilter(pattern string, pos int, filter FilterFunc, params ...bool) error {
  391. mr := &FilterRouter{
  392. tree: NewTree(),
  393. pattern: pattern,
  394. filterFunc: filter,
  395. returnOnOutput: true,
  396. }
  397. if !BConfig.RouterCaseSensitive {
  398. mr.pattern = strings.ToLower(pattern)
  399. }
  400. paramsLen := len(params)
  401. if paramsLen > 0 {
  402. mr.returnOnOutput = params[0]
  403. }
  404. if paramsLen > 1 {
  405. mr.resetParams = params[1]
  406. }
  407. mr.tree.AddRouter(pattern, true)
  408. return p.insertFilterRouter(pos, mr)
  409. }
  410. // add Filter into
  411. func (p *ControllerRegister) insertFilterRouter(pos int, mr *FilterRouter) (err error) {
  412. if pos < BeforeStatic || pos > FinishRouter {
  413. err = fmt.Errorf("can not find your filter position")
  414. return
  415. }
  416. p.enableFilter = true
  417. p.filters[pos] = append(p.filters[pos], mr)
  418. return nil
  419. }
  420. // URLFor does another controller handler in this request function.
  421. // it can access any controller method.
  422. func (p *ControllerRegister) URLFor(endpoint string, values ...interface{}) string {
  423. paths := strings.Split(endpoint, ".")
  424. if len(paths) <= 1 {
  425. logs.Warn("urlfor endpoint must like path.controller.method")
  426. return ""
  427. }
  428. if len(values)%2 != 0 {
  429. logs.Warn("urlfor params must key-value pair")
  430. return ""
  431. }
  432. params := make(map[string]string)
  433. if len(values) > 0 {
  434. key := ""
  435. for k, v := range values {
  436. if k%2 == 0 {
  437. key = fmt.Sprint(v)
  438. } else {
  439. params[key] = fmt.Sprint(v)
  440. }
  441. }
  442. }
  443. controllName := strings.Join(paths[:len(paths)-1], "/")
  444. methodName := paths[len(paths)-1]
  445. for m, t := range p.routers {
  446. ok, url := p.geturl(t, "/", controllName, methodName, params, m)
  447. if ok {
  448. return url
  449. }
  450. }
  451. return ""
  452. }
  453. func (p *ControllerRegister) geturl(t *Tree, url, controllName, methodName string, params map[string]string, httpMethod string) (bool, string) {
  454. for _, subtree := range t.fixrouters {
  455. u := path.Join(url, subtree.prefix)
  456. ok, u := p.geturl(subtree, u, controllName, methodName, params, httpMethod)
  457. if ok {
  458. return ok, u
  459. }
  460. }
  461. if t.wildcard != nil {
  462. u := path.Join(url, urlPlaceholder)
  463. ok, u := p.geturl(t.wildcard, u, controllName, methodName, params, httpMethod)
  464. if ok {
  465. return ok, u
  466. }
  467. }
  468. for _, l := range t.leaves {
  469. if c, ok := l.runObject.(*controllerInfo); ok {
  470. if c.routerType == routerTypeBeego &&
  471. strings.HasSuffix(path.Join(c.controllerType.PkgPath(), c.controllerType.Name()), controllName) {
  472. find := false
  473. if _, ok := HTTPMETHOD[strings.ToUpper(methodName)]; ok {
  474. if len(c.methods) == 0 {
  475. find = true
  476. } else if m, ok := c.methods[strings.ToUpper(methodName)]; ok && m == strings.ToUpper(methodName) {
  477. find = true
  478. } else if m, ok = c.methods["*"]; ok && m == methodName {
  479. find = true
  480. }
  481. }
  482. if !find {
  483. for m, md := range c.methods {
  484. if (m == "*" || m == httpMethod) && md == methodName {
  485. find = true
  486. }
  487. }
  488. }
  489. if find {
  490. if l.regexps == nil {
  491. if len(l.wildcards) == 0 {
  492. return true, strings.Replace(url, "/"+urlPlaceholder, "", 1) + toURL(params)
  493. }
  494. if len(l.wildcards) == 1 {
  495. if v, ok := params[l.wildcards[0]]; ok {
  496. delete(params, l.wildcards[0])
  497. return true, strings.Replace(url, urlPlaceholder, v, 1) + toURL(params)
  498. }
  499. return false, ""
  500. }
  501. if len(l.wildcards) == 3 && l.wildcards[0] == "." {
  502. if p, ok := params[":path"]; ok {
  503. if e, isok := params[":ext"]; isok {
  504. delete(params, ":path")
  505. delete(params, ":ext")
  506. return true, strings.Replace(url, urlPlaceholder, p+"."+e, -1) + toURL(params)
  507. }
  508. }
  509. }
  510. canskip := false
  511. for _, v := range l.wildcards {
  512. if v == ":" {
  513. canskip = true
  514. continue
  515. }
  516. if u, ok := params[v]; ok {
  517. delete(params, v)
  518. url = strings.Replace(url, urlPlaceholder, u, 1)
  519. } else {
  520. if canskip {
  521. canskip = false
  522. continue
  523. }
  524. return false, ""
  525. }
  526. }
  527. return true, url + toURL(params)
  528. }
  529. var i int
  530. var startreg bool
  531. regurl := ""
  532. for _, v := range strings.Trim(l.regexps.String(), "^$") {
  533. if v == '(' {
  534. startreg = true
  535. continue
  536. } else if v == ')' {
  537. startreg = false
  538. if v, ok := params[l.wildcards[i]]; ok {
  539. delete(params, l.wildcards[i])
  540. regurl = regurl + v
  541. i++
  542. } else {
  543. break
  544. }
  545. } else if !startreg {
  546. regurl = string(append([]rune(regurl), v))
  547. }
  548. }
  549. if l.regexps.MatchString(regurl) {
  550. ps := strings.Split(regurl, "/")
  551. for _, p := range ps {
  552. url = strings.Replace(url, urlPlaceholder, p, 1)
  553. }
  554. return true, url + toURL(params)
  555. }
  556. }
  557. }
  558. }
  559. }
  560. return false, ""
  561. }
  562. func (p *ControllerRegister) execFilter(context *beecontext.Context, urlPath string, pos int) (started bool) {
  563. var preFilterParams map[string]string
  564. for _, filterR := range p.filters[pos] {
  565. if filterR.returnOnOutput && context.ResponseWriter.Started {
  566. return true
  567. }
  568. if filterR.resetParams {
  569. preFilterParams = context.Input.Params()
  570. }
  571. if ok := filterR.ValidRouter(urlPath, context); ok {
  572. filterR.filterFunc(context)
  573. if filterR.resetParams {
  574. context.Input.ResetParams()
  575. for k, v := range preFilterParams {
  576. context.Input.SetParam(k, v)
  577. }
  578. }
  579. }
  580. if filterR.returnOnOutput && context.ResponseWriter.Started {
  581. return true
  582. }
  583. }
  584. return false
  585. }
  586. // Implement http.Handler interface.
  587. func (p *ControllerRegister) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
  588. startTime := time.Now()
  589. var (
  590. runRouter reflect.Type
  591. findRouter bool
  592. runMethod string
  593. routerInfo *controllerInfo
  594. isRunnable bool
  595. )
  596. context := p.pool.Get().(*beecontext.Context)
  597. context.Reset(rw, r)
  598. defer p.pool.Put(context)
  599. if BConfig.RecoverFunc != nil {
  600. defer BConfig.RecoverFunc(context)
  601. }
  602. context.Output.EnableGzip = BConfig.EnableGzip
  603. if BConfig.RunMode == DEV {
  604. context.Output.Header("Server", BConfig.ServerName)
  605. }
  606. var urlPath = r.URL.Path
  607. if !BConfig.RouterCaseSensitive {
  608. urlPath = strings.ToLower(urlPath)
  609. }
  610. // filter wrong http method
  611. if _, ok := HTTPMETHOD[r.Method]; !ok {
  612. http.Error(rw, "Method Not Allowed", 405)
  613. goto Admin
  614. }
  615. // filter for static file
  616. if len(p.filters[BeforeStatic]) > 0 && p.execFilter(context, urlPath, BeforeStatic) {
  617. goto Admin
  618. }
  619. serverStaticRouter(context)
  620. if context.ResponseWriter.Started {
  621. findRouter = true
  622. goto Admin
  623. }
  624. if r.Method != "GET" && r.Method != "HEAD" {
  625. if BConfig.CopyRequestBody && !context.Input.IsUpload() {
  626. context.Input.CopyBody(BConfig.MaxMemory)
  627. }
  628. context.Input.ParseFormOrMulitForm(BConfig.MaxMemory)
  629. }
  630. // session init
  631. if BConfig.WebConfig.Session.SessionOn {
  632. var err error
  633. context.Input.CruSession, err = GlobalSessions.SessionStart(rw, r)
  634. if err != nil {
  635. logs.Error(err)
  636. exception("503", context)
  637. goto Admin
  638. }
  639. defer func() {
  640. if context.Input.CruSession != nil {
  641. context.Input.CruSession.SessionRelease(rw)
  642. }
  643. }()
  644. }
  645. if len(p.filters[BeforeRouter]) > 0 && p.execFilter(context, urlPath, BeforeRouter) {
  646. goto Admin
  647. }
  648. // User can define RunController and RunMethod in filter
  649. if context.Input.RunController != nil && context.Input.RunMethod != "" {
  650. findRouter = true
  651. isRunnable = true
  652. runMethod = context.Input.RunMethod
  653. runRouter = context.Input.RunController
  654. } else {
  655. routerInfo, findRouter = p.FindRouter(context)
  656. }
  657. //if no matches to url, throw a not found exception
  658. if !findRouter {
  659. exception("404", context)
  660. goto Admin
  661. }
  662. if splat := context.Input.Param(":splat"); splat != "" {
  663. for k, v := range strings.Split(splat, "/") {
  664. context.Input.SetParam(strconv.Itoa(k), v)
  665. }
  666. }
  667. //execute middleware filters
  668. if len(p.filters[BeforeExec]) > 0 && p.execFilter(context, urlPath, BeforeExec) {
  669. goto Admin
  670. }
  671. //check policies
  672. if p.execPolicy(context, urlPath) {
  673. goto Admin
  674. }
  675. if routerInfo != nil {
  676. //store router pattern into context
  677. context.Input.SetData("RouterPattern", routerInfo.pattern)
  678. if routerInfo.routerType == routerTypeRESTFul {
  679. if _, ok := routerInfo.methods[r.Method]; ok {
  680. isRunnable = true
  681. routerInfo.runFunction(context)
  682. } else {
  683. exception("405", context)
  684. goto Admin
  685. }
  686. } else if routerInfo.routerType == routerTypeHandler {
  687. isRunnable = true
  688. routerInfo.handler.ServeHTTP(rw, r)
  689. } else {
  690. runRouter = routerInfo.controllerType
  691. method := r.Method
  692. if r.Method == "POST" && context.Input.Query("_method") == "PUT" {
  693. method = "PUT"
  694. }
  695. if r.Method == "POST" && context.Input.Query("_method") == "DELETE" {
  696. method = "DELETE"
  697. }
  698. if m, ok := routerInfo.methods[method]; ok {
  699. runMethod = m
  700. } else if m, ok = routerInfo.methods["*"]; ok {
  701. runMethod = m
  702. } else {
  703. runMethod = method
  704. }
  705. }
  706. }
  707. // also defined runRouter & runMethod from filter
  708. if !isRunnable {
  709. //Invoke the request handler
  710. vc := reflect.New(runRouter)
  711. execController, ok := vc.Interface().(ControllerInterface)
  712. if !ok {
  713. panic("controller is not ControllerInterface")
  714. }
  715. //call the controller init function
  716. execController.Init(context, runRouter.Name(), runMethod, vc.Interface())
  717. //call prepare function
  718. execController.Prepare()
  719. //if XSRF is Enable then check cookie where there has any cookie in the request's cookie _csrf
  720. if BConfig.WebConfig.EnableXSRF {
  721. execController.XSRFToken()
  722. if r.Method == "POST" || r.Method == "DELETE" || r.Method == "PUT" ||
  723. (r.Method == "POST" && (context.Input.Query("_method") == "DELETE" || context.Input.Query("_method") == "PUT")) {
  724. execController.CheckXSRFCookie()
  725. }
  726. }
  727. execController.URLMapping()
  728. if !context.ResponseWriter.Started {
  729. //exec main logic
  730. switch runMethod {
  731. case "GET":
  732. execController.Get()
  733. case "POST":
  734. execController.Post()
  735. case "DELETE":
  736. execController.Delete()
  737. case "PUT":
  738. execController.Put()
  739. case "HEAD":
  740. execController.Head()
  741. case "PATCH":
  742. execController.Patch()
  743. case "OPTIONS":
  744. execController.Options()
  745. default:
  746. if !execController.HandlerFunc(runMethod) {
  747. var in []reflect.Value
  748. method := vc.MethodByName(runMethod)
  749. method.Call(in)
  750. }
  751. }
  752. //render template
  753. if !context.ResponseWriter.Started && context.Output.Status == 0 {
  754. if BConfig.WebConfig.AutoRender {
  755. if err := execController.Render(); err != nil {
  756. logs.Error(err)
  757. }
  758. }
  759. }
  760. }
  761. // finish all runRouter. release resource
  762. execController.Finish()
  763. }
  764. //execute middleware filters
  765. if len(p.filters[AfterExec]) > 0 && p.execFilter(context, urlPath, AfterExec) {
  766. goto Admin
  767. }
  768. if len(p.filters[FinishRouter]) > 0 && p.execFilter(context, urlPath, FinishRouter) {
  769. goto Admin
  770. }
  771. Admin:
  772. //admin module record QPS
  773. if BConfig.Listen.EnableAdmin {
  774. timeDur := time.Since(startTime)
  775. if FilterMonitorFunc(r.Method, r.URL.Path, timeDur) {
  776. if runRouter != nil {
  777. go toolbox.StatisticsMap.AddStatistics(r.Method, r.URL.Path, runRouter.Name(), timeDur)
  778. } else {
  779. go toolbox.StatisticsMap.AddStatistics(r.Method, r.URL.Path, "", timeDur)
  780. }
  781. }
  782. }
  783. if BConfig.RunMode == DEV || BConfig.Log.AccessLogs {
  784. timeDur := time.Since(startTime)
  785. var devInfo string
  786. statusCode := context.ResponseWriter.Status
  787. if statusCode == 0 {
  788. statusCode = 200
  789. }
  790. iswin := (runtime.GOOS == "windows")
  791. statusColor := logs.ColorByStatus(iswin, statusCode)
  792. methodColor := logs.ColorByMethod(iswin, r.Method)
  793. resetColor := logs.ColorByMethod(iswin, "")
  794. if findRouter {
  795. if routerInfo != nil {
  796. devInfo = fmt.Sprintf("|%15s|%s %3d %s|%13s|%8s|%s %-7s %s %-3s r:%s", context.Input.IP(), statusColor, statusCode,
  797. resetColor, timeDur.String(), "match", methodColor, r.Method, resetColor, r.URL.Path,
  798. routerInfo.pattern)
  799. } else {
  800. devInfo = fmt.Sprintf("|%15s|%s %3d %s|%13s|%8s|%s %-7s %s %-3s", context.Input.IP(), statusColor, statusCode, resetColor,
  801. timeDur.String(), "match", methodColor, r.Method, resetColor, r.URL.Path)
  802. }
  803. } else {
  804. devInfo = fmt.Sprintf("|%15s|%s %3d %s|%13s|%8s|%s %-7s %s %-3s", context.Input.IP(), statusColor, statusCode, resetColor,
  805. timeDur.String(), "nomatch", methodColor, r.Method, resetColor, r.URL.Path)
  806. }
  807. if iswin {
  808. logs.W32Debug(devInfo)
  809. } else {
  810. logs.Debug(devInfo)
  811. }
  812. }
  813. // Call WriteHeader if status code has been set changed
  814. if context.Output.Status != 0 {
  815. context.ResponseWriter.WriteHeader(context.Output.Status)
  816. }
  817. }
  818. // FindRouter Find Router info for URL
  819. func (p *ControllerRegister) FindRouter(context *beecontext.Context) (routerInfo *controllerInfo, isFind bool) {
  820. var urlPath = context.Input.URL()
  821. if !BConfig.RouterCaseSensitive {
  822. urlPath = strings.ToLower(urlPath)
  823. }
  824. httpMethod := context.Input.Method()
  825. if t, ok := p.routers[httpMethod]; ok {
  826. runObject := t.Match(urlPath, context)
  827. if r, ok := runObject.(*controllerInfo); ok {
  828. return r, true
  829. }
  830. }
  831. return
  832. }
  833. func toURL(params map[string]string) string {
  834. if len(params) == 0 {
  835. return ""
  836. }
  837. u := "?"
  838. for k, v := range params {
  839. u += k + "=" + v + "&"
  840. }
  841. return strings.TrimRight(u, "&")
  842. }