router.go 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  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. "path"
  19. "path/filepath"
  20. "reflect"
  21. "runtime"
  22. "strconv"
  23. "strings"
  24. "sync"
  25. "time"
  26. beecontext "github.com/cnlh/nps/vender/github.com/astaxie/beego/context"
  27. "github.com/cnlh/nps/vender/github.com/astaxie/beego/context/param"
  28. "github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
  29. "github.com/cnlh/nps/vender/github.com/astaxie/beego/toolbox"
  30. "github.com/cnlh/nps/vender/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. cr := &ControllerRegister{
  123. routers: make(map[string]*Tree),
  124. policies: make(map[string]*Tree),
  125. }
  126. cr.pool.New = func() interface{} {
  127. return beecontext.NewContext()
  128. }
  129. return cr
  130. }
  131. // Add controller handler and pattern rules to ControllerRegister.
  132. // usage:
  133. // default methods is the same name as method
  134. // Add("/user",&UserController{})
  135. // Add("/api/list",&RestController{},"*:ListFood")
  136. // Add("/api/create",&RestController{},"post:CreateFood")
  137. // Add("/api/update",&RestController{},"put:UpdateFood")
  138. // Add("/api/delete",&RestController{},"delete:DeleteFood")
  139. // Add("/api",&RestController{},"get,post:ApiFunc"
  140. // Add("/simple",&SimpleController{},"get:GetFunc;post:PostFunc")
  141. func (p *ControllerRegister) Add(pattern string, c ControllerInterface, mappingMethods ...string) {
  142. p.addWithMethodParams(pattern, c, nil, mappingMethods...)
  143. }
  144. func (p *ControllerRegister) addWithMethodParams(pattern string, c ControllerInterface, methodParams []*param.MethodParam, mappingMethods ...string) {
  145. reflectVal := reflect.ValueOf(c)
  146. t := reflect.Indirect(reflectVal).Type()
  147. methods := make(map[string]string)
  148. if len(mappingMethods) > 0 {
  149. semi := strings.Split(mappingMethods[0], ";")
  150. for _, v := range semi {
  151. colon := strings.Split(v, ":")
  152. if len(colon) != 2 {
  153. panic("method mapping format is invalid")
  154. }
  155. comma := strings.Split(colon[0], ",")
  156. for _, m := range comma {
  157. if m == "*" || HTTPMETHOD[strings.ToUpper(m)] {
  158. if val := reflectVal.MethodByName(colon[1]); val.IsValid() {
  159. methods[strings.ToUpper(m)] = colon[1]
  160. } else {
  161. panic("'" + colon[1] + "' method doesn't exist in the controller " + t.Name())
  162. }
  163. } else {
  164. panic(v + " is an invalid method mapping. Method doesn't exist " + m)
  165. }
  166. }
  167. }
  168. }
  169. route := &ControllerInfo{}
  170. route.pattern = pattern
  171. route.methods = methods
  172. route.routerType = routerTypeBeego
  173. route.controllerType = t
  174. route.initialize = func() ControllerInterface {
  175. vc := reflect.New(route.controllerType)
  176. execController, ok := vc.Interface().(ControllerInterface)
  177. if !ok {
  178. panic("controller is not ControllerInterface")
  179. }
  180. elemVal := reflect.ValueOf(c).Elem()
  181. elemType := reflect.TypeOf(c).Elem()
  182. execElem := reflect.ValueOf(execController).Elem()
  183. numOfFields := elemVal.NumField()
  184. for i := 0; i < numOfFields; i++ {
  185. fieldType := elemType.Field(i)
  186. elemField := execElem.FieldByName(fieldType.Name)
  187. if elemField.CanSet() {
  188. fieldVal := elemVal.Field(i)
  189. elemField.Set(fieldVal)
  190. }
  191. }
  192. return execController
  193. }
  194. route.methodParams = methodParams
  195. if len(methods) == 0 {
  196. for m := range HTTPMETHOD {
  197. p.addToRouter(m, pattern, route)
  198. }
  199. } else {
  200. for k := range methods {
  201. if k == "*" {
  202. for m := range HTTPMETHOD {
  203. p.addToRouter(m, pattern, route)
  204. }
  205. } else {
  206. p.addToRouter(k, pattern, route)
  207. }
  208. }
  209. }
  210. }
  211. func (p *ControllerRegister) addToRouter(method, pattern string, r *ControllerInfo) {
  212. if !BConfig.RouterCaseSensitive {
  213. pattern = strings.ToLower(pattern)
  214. }
  215. if t, ok := p.routers[method]; ok {
  216. t.AddRouter(pattern, r)
  217. } else {
  218. t := NewTree()
  219. t.AddRouter(pattern, r)
  220. p.routers[method] = t
  221. }
  222. }
  223. // Include only when the Runmode is dev will generate router file in the router/auto.go from the controller
  224. // Include(&BankAccount{}, &OrderController{},&RefundController{},&ReceiptController{})
  225. func (p *ControllerRegister) Include(cList ...ControllerInterface) {
  226. if BConfig.RunMode == DEV {
  227. skip := make(map[string]bool, 10)
  228. for _, c := range cList {
  229. reflectVal := reflect.ValueOf(c)
  230. t := reflect.Indirect(reflectVal).Type()
  231. wgopath := utils.GetGOPATHs()
  232. if len(wgopath) == 0 {
  233. panic("you are in dev mode. So please set gopath")
  234. }
  235. pkgpath := ""
  236. for _, wg := range wgopath {
  237. wg, _ = filepath.EvalSymlinks(filepath.Join(wg, "src", t.PkgPath()))
  238. if utils.FileExists(wg) {
  239. pkgpath = wg
  240. break
  241. }
  242. }
  243. if pkgpath != "" {
  244. if _, ok := skip[pkgpath]; !ok {
  245. skip[pkgpath] = true
  246. parserPkg(pkgpath, t.PkgPath())
  247. }
  248. }
  249. }
  250. }
  251. for _, c := range cList {
  252. reflectVal := reflect.ValueOf(c)
  253. t := reflect.Indirect(reflectVal).Type()
  254. key := t.PkgPath() + ":" + t.Name()
  255. if comm, ok := GlobalControllerRouter[key]; ok {
  256. for _, a := range comm {
  257. for _, f := range a.Filters {
  258. p.InsertFilter(f.Pattern, f.Pos, f.Filter, f.ReturnOnOutput, f.ResetParams)
  259. }
  260. p.addWithMethodParams(a.Router, c, a.MethodParams, strings.Join(a.AllowHTTPMethods, ",")+":"+a.Method)
  261. }
  262. }
  263. }
  264. }
  265. // Get add get method
  266. // usage:
  267. // Get("/", func(ctx *context.Context){
  268. // ctx.Output.Body("hello world")
  269. // })
  270. func (p *ControllerRegister) Get(pattern string, f FilterFunc) {
  271. p.AddMethod("get", pattern, f)
  272. }
  273. // Post add post method
  274. // usage:
  275. // Post("/api", func(ctx *context.Context){
  276. // ctx.Output.Body("hello world")
  277. // })
  278. func (p *ControllerRegister) Post(pattern string, f FilterFunc) {
  279. p.AddMethod("post", pattern, f)
  280. }
  281. // Put add put method
  282. // usage:
  283. // Put("/api/:id", func(ctx *context.Context){
  284. // ctx.Output.Body("hello world")
  285. // })
  286. func (p *ControllerRegister) Put(pattern string, f FilterFunc) {
  287. p.AddMethod("put", pattern, f)
  288. }
  289. // Delete add delete method
  290. // usage:
  291. // Delete("/api/:id", func(ctx *context.Context){
  292. // ctx.Output.Body("hello world")
  293. // })
  294. func (p *ControllerRegister) Delete(pattern string, f FilterFunc) {
  295. p.AddMethod("delete", pattern, f)
  296. }
  297. // Head add head method
  298. // usage:
  299. // Head("/api/:id", func(ctx *context.Context){
  300. // ctx.Output.Body("hello world")
  301. // })
  302. func (p *ControllerRegister) Head(pattern string, f FilterFunc) {
  303. p.AddMethod("head", pattern, f)
  304. }
  305. // Patch add patch method
  306. // usage:
  307. // Patch("/api/:id", func(ctx *context.Context){
  308. // ctx.Output.Body("hello world")
  309. // })
  310. func (p *ControllerRegister) Patch(pattern string, f FilterFunc) {
  311. p.AddMethod("patch", pattern, f)
  312. }
  313. // Options add options method
  314. // usage:
  315. // Options("/api/:id", func(ctx *context.Context){
  316. // ctx.Output.Body("hello world")
  317. // })
  318. func (p *ControllerRegister) Options(pattern string, f FilterFunc) {
  319. p.AddMethod("options", pattern, f)
  320. }
  321. // Any add all method
  322. // usage:
  323. // Any("/api/:id", func(ctx *context.Context){
  324. // ctx.Output.Body("hello world")
  325. // })
  326. func (p *ControllerRegister) Any(pattern string, f FilterFunc) {
  327. p.AddMethod("*", pattern, f)
  328. }
  329. // AddMethod add http method router
  330. // usage:
  331. // AddMethod("get","/api/:id", func(ctx *context.Context){
  332. // ctx.Output.Body("hello world")
  333. // })
  334. func (p *ControllerRegister) AddMethod(method, pattern string, f FilterFunc) {
  335. method = strings.ToUpper(method)
  336. if method != "*" && !HTTPMETHOD[method] {
  337. panic("not support http method: " + method)
  338. }
  339. route := &ControllerInfo{}
  340. route.pattern = pattern
  341. route.routerType = routerTypeRESTFul
  342. route.runFunction = f
  343. methods := make(map[string]string)
  344. if method == "*" {
  345. for val := range HTTPMETHOD {
  346. methods[val] = val
  347. }
  348. } else {
  349. methods[method] = method
  350. }
  351. route.methods = methods
  352. for k := range methods {
  353. if k == "*" {
  354. for m := range HTTPMETHOD {
  355. p.addToRouter(m, pattern, route)
  356. }
  357. } else {
  358. p.addToRouter(k, pattern, route)
  359. }
  360. }
  361. }
  362. // Handler add user defined Handler
  363. func (p *ControllerRegister) Handler(pattern string, h http.Handler, options ...interface{}) {
  364. route := &ControllerInfo{}
  365. route.pattern = pattern
  366. route.routerType = routerTypeHandler
  367. route.handler = h
  368. if len(options) > 0 {
  369. if _, ok := options[0].(bool); ok {
  370. pattern = path.Join(pattern, "?:all(.*)")
  371. }
  372. }
  373. for m := range HTTPMETHOD {
  374. p.addToRouter(m, pattern, route)
  375. }
  376. }
  377. // AddAuto router to ControllerRegister.
  378. // example beego.AddAuto(&MainContorlller{}),
  379. // MainController has method List and Page.
  380. // visit the url /main/list to execute List function
  381. // /main/page to execute Page function.
  382. func (p *ControllerRegister) AddAuto(c ControllerInterface) {
  383. p.AddAutoPrefix("/", c)
  384. }
  385. // AddAutoPrefix Add auto router to ControllerRegister with prefix.
  386. // example beego.AddAutoPrefix("/admin",&MainContorlller{}),
  387. // MainController has method List and Page.
  388. // visit the url /admin/main/list to execute List function
  389. // /admin/main/page to execute Page function.
  390. func (p *ControllerRegister) AddAutoPrefix(prefix string, c ControllerInterface) {
  391. reflectVal := reflect.ValueOf(c)
  392. rt := reflectVal.Type()
  393. ct := reflect.Indirect(reflectVal).Type()
  394. controllerName := strings.TrimSuffix(ct.Name(), "Controller")
  395. for i := 0; i < rt.NumMethod(); i++ {
  396. if !utils.InSlice(rt.Method(i).Name, exceptMethod) {
  397. route := &ControllerInfo{}
  398. route.routerType = routerTypeBeego
  399. route.methods = map[string]string{"*": rt.Method(i).Name}
  400. route.controllerType = ct
  401. pattern := path.Join(prefix, strings.ToLower(controllerName), strings.ToLower(rt.Method(i).Name), "*")
  402. patternInit := path.Join(prefix, controllerName, rt.Method(i).Name, "*")
  403. patternFix := path.Join(prefix, strings.ToLower(controllerName), strings.ToLower(rt.Method(i).Name))
  404. patternFixInit := path.Join(prefix, controllerName, rt.Method(i).Name)
  405. route.pattern = pattern
  406. for m := range HTTPMETHOD {
  407. p.addToRouter(m, pattern, route)
  408. p.addToRouter(m, patternInit, route)
  409. p.addToRouter(m, patternFix, route)
  410. p.addToRouter(m, patternFixInit, route)
  411. }
  412. }
  413. }
  414. }
  415. // InsertFilter Add a FilterFunc with pattern rule and action constant.
  416. // params is for:
  417. // 1. setting the returnOnOutput value (false allows multiple filters to execute)
  418. // 2. determining whether or not params need to be reset.
  419. func (p *ControllerRegister) InsertFilter(pattern string, pos int, filter FilterFunc, params ...bool) error {
  420. mr := &FilterRouter{
  421. tree: NewTree(),
  422. pattern: pattern,
  423. filterFunc: filter,
  424. returnOnOutput: true,
  425. }
  426. if !BConfig.RouterCaseSensitive {
  427. mr.pattern = strings.ToLower(pattern)
  428. }
  429. paramsLen := len(params)
  430. if paramsLen > 0 {
  431. mr.returnOnOutput = params[0]
  432. }
  433. if paramsLen > 1 {
  434. mr.resetParams = params[1]
  435. }
  436. mr.tree.AddRouter(pattern, true)
  437. return p.insertFilterRouter(pos, mr)
  438. }
  439. // add Filter into
  440. func (p *ControllerRegister) insertFilterRouter(pos int, mr *FilterRouter) (err error) {
  441. if pos < BeforeStatic || pos > FinishRouter {
  442. err = fmt.Errorf("can not find your filter position")
  443. return
  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. controllName := 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, "/", controllName, methodName, params, m)
  476. if ok {
  477. return url
  478. }
  479. }
  480. return ""
  481. }
  482. func (p *ControllerRegister) geturl(t *Tree, url, controllName, 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, controllName, 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, controllName, 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()), controllName) {
  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. http.Error(rw, "Method Not Allowed", 405)
  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.MethodPost {
  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.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. default:
  782. if !execController.HandlerFunc(runMethod) {
  783. vc := reflect.ValueOf(execController)
  784. method := vc.MethodByName(runMethod)
  785. in := param.ConvertParams(methodParams, method.Type(), context)
  786. out := method.Call(in)
  787. //For backward compatibility we only handle response if we had incoming methodParams
  788. if methodParams != nil {
  789. p.handleParamResponse(context, execController, out)
  790. }
  791. }
  792. }
  793. //render template
  794. if !context.ResponseWriter.Started && context.Output.Status == 0 {
  795. if BConfig.WebConfig.AutoRender {
  796. if err := execController.Render(); err != nil {
  797. logs.Error(err)
  798. }
  799. }
  800. }
  801. }
  802. // finish all runRouter. release resource
  803. execController.Finish()
  804. }
  805. //execute middleware filters
  806. if len(p.filters[AfterExec]) > 0 && p.execFilter(context, urlPath, AfterExec) {
  807. goto Admin
  808. }
  809. if len(p.filters[FinishRouter]) > 0 && p.execFilter(context, urlPath, FinishRouter) {
  810. goto Admin
  811. }
  812. Admin:
  813. //admin module record QPS
  814. statusCode := context.ResponseWriter.Status
  815. if statusCode == 0 {
  816. statusCode = 200
  817. }
  818. logAccess(context, &startTime, statusCode)
  819. if BConfig.Listen.EnableAdmin {
  820. timeDur := time.Since(startTime)
  821. pattern := ""
  822. if routerInfo != nil {
  823. pattern = routerInfo.pattern
  824. }
  825. if FilterMonitorFunc(r.Method, r.URL.Path, timeDur, pattern, statusCode) {
  826. if runRouter != nil {
  827. go toolbox.StatisticsMap.AddStatistics(r.Method, r.URL.Path, runRouter.Name(), timeDur)
  828. } else {
  829. go toolbox.StatisticsMap.AddStatistics(r.Method, r.URL.Path, "", timeDur)
  830. }
  831. }
  832. }
  833. if BConfig.RunMode == DEV && !BConfig.Log.AccessLogs {
  834. var devInfo string
  835. timeDur := time.Since(startTime)
  836. iswin := (runtime.GOOS == "windows")
  837. statusColor := logs.ColorByStatus(iswin, statusCode)
  838. methodColor := logs.ColorByMethod(iswin, r.Method)
  839. resetColor := logs.ColorByMethod(iswin, "")
  840. if findRouter {
  841. if routerInfo != nil {
  842. devInfo = fmt.Sprintf("|%15s|%s %3d %s|%13s|%8s|%s %-7s %s %-3s r:%s", context.Input.IP(), statusColor, statusCode,
  843. resetColor, timeDur.String(), "match", methodColor, r.Method, resetColor, r.URL.Path,
  844. routerInfo.pattern)
  845. } else {
  846. devInfo = fmt.Sprintf("|%15s|%s %3d %s|%13s|%8s|%s %-7s %s %-3s", context.Input.IP(), statusColor, statusCode, resetColor,
  847. timeDur.String(), "match", methodColor, r.Method, resetColor, r.URL.Path)
  848. }
  849. } else {
  850. devInfo = fmt.Sprintf("|%15s|%s %3d %s|%13s|%8s|%s %-7s %s %-3s", context.Input.IP(), statusColor, statusCode, resetColor,
  851. timeDur.String(), "nomatch", methodColor, r.Method, resetColor, r.URL.Path)
  852. }
  853. if iswin {
  854. logs.W32Debug(devInfo)
  855. } else {
  856. logs.Debug(devInfo)
  857. }
  858. }
  859. // Call WriteHeader if status code has been set changed
  860. if context.Output.Status != 0 {
  861. context.ResponseWriter.WriteHeader(context.Output.Status)
  862. }
  863. }
  864. func (p *ControllerRegister) handleParamResponse(context *beecontext.Context, execController ControllerInterface, results []reflect.Value) {
  865. //looping in reverse order for the case when both error and value are returned and error sets the response status code
  866. for i := len(results) - 1; i >= 0; i-- {
  867. result := results[i]
  868. if result.Kind() != reflect.Interface || !result.IsNil() {
  869. resultValue := result.Interface()
  870. context.RenderMethodResult(resultValue)
  871. }
  872. }
  873. if !context.ResponseWriter.Started && len(results) > 0 && context.Output.Status == 0 {
  874. context.Output.SetStatus(200)
  875. }
  876. }
  877. // FindRouter Find Router info for URL
  878. func (p *ControllerRegister) FindRouter(context *beecontext.Context) (routerInfo *ControllerInfo, isFind bool) {
  879. var urlPath = context.Input.URL()
  880. if !BConfig.RouterCaseSensitive {
  881. urlPath = strings.ToLower(urlPath)
  882. }
  883. httpMethod := context.Input.Method()
  884. if t, ok := p.routers[httpMethod]; ok {
  885. runObject := t.Match(urlPath, context)
  886. if r, ok := runObject.(*ControllerInfo); ok {
  887. return r, true
  888. }
  889. }
  890. return
  891. }
  892. func toURL(params map[string]string) string {
  893. if len(params) == 0 {
  894. return ""
  895. }
  896. u := "?"
  897. for k, v := range params {
  898. u += k + "=" + v + "&"
  899. }
  900. return strings.TrimRight(u, "&")
  901. }
  902. func logAccess(ctx *beecontext.Context, startTime *time.Time, statusCode int) {
  903. //Skip logging if AccessLogs config is false
  904. if !BConfig.Log.AccessLogs {
  905. return
  906. }
  907. //Skip logging static requests unless EnableStaticLogs config is true
  908. if !BConfig.Log.EnableStaticLogs && DefaultAccessLogFilter.Filter(ctx) {
  909. return
  910. }
  911. var (
  912. requestTime time.Time
  913. elapsedTime time.Duration
  914. r = ctx.Request
  915. )
  916. if startTime != nil {
  917. requestTime = *startTime
  918. elapsedTime = time.Since(*startTime)
  919. }
  920. record := &logs.AccessLogRecord{
  921. RemoteAddr: ctx.Input.IP(),
  922. RequestTime: requestTime,
  923. RequestMethod: r.Method,
  924. Request: fmt.Sprintf("%s %s %s", r.Method, r.RequestURI, r.Proto),
  925. ServerProtocol: r.Proto,
  926. Host: r.Host,
  927. Status: statusCode,
  928. ElapsedTime: elapsedTime,
  929. HTTPReferrer: r.Header.Get("Referer"),
  930. HTTPUserAgent: r.Header.Get("User-Agent"),
  931. RemoteUser: r.Header.Get("Remote-User"),
  932. BodyBytesSent: 0, //@todo this one is missing!
  933. }
  934. logs.AccessLog(record, BConfig.Log.AccessLogsFormat)
  935. }