error.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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. "html/template"
  18. "net/http"
  19. "reflect"
  20. "runtime"
  21. "strconv"
  22. "strings"
  23. "github.com/cnlh/nps/vender/github.com/astaxie/beego/context"
  24. "github.com/cnlh/nps/vender/github.com/astaxie/beego/utils"
  25. )
  26. const (
  27. errorTypeHandler = iota
  28. errorTypeController
  29. )
  30. var tpl = `
  31. <!DOCTYPE html>
  32. <html>
  33. <head>
  34. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  35. <title>beego application error</title>
  36. <style>
  37. html, body, body * {padding: 0; margin: 0;}
  38. #header {background:#ffd; border-bottom:solid 2px #A31515; padding: 20px 10px;}
  39. #header h2{ }
  40. #footer {border-top:solid 1px #aaa; padding: 5px 10px; font-size: 12px; color:green;}
  41. #content {padding: 5px;}
  42. #content .stack b{ font-size: 13px; color: red;}
  43. #content .stack pre{padding-left: 10px;}
  44. table {}
  45. td.t {text-align: right; padding-right: 5px; color: #888;}
  46. </style>
  47. <script type="text/javascript">
  48. </script>
  49. </head>
  50. <body>
  51. <div id="header">
  52. <h2>{{.AppError}}</h2>
  53. </div>
  54. <div id="content">
  55. <table>
  56. <tr>
  57. <td class="t">Request Method: </td><td>{{.RequestMethod}}</td>
  58. </tr>
  59. <tr>
  60. <td class="t">Request URL: </td><td>{{.RequestURL}}</td>
  61. </tr>
  62. <tr>
  63. <td class="t">RemoteAddr: </td><td>{{.RemoteAddr }}</td>
  64. </tr>
  65. </table>
  66. <div class="stack">
  67. <b>Stack</b>
  68. <pre>{{.Stack}}</pre>
  69. </div>
  70. </div>
  71. <div id="footer">
  72. <p>beego {{ .BeegoVersion }} (beego framework)</p>
  73. <p>golang version: {{.GoVersion}}</p>
  74. </div>
  75. </body>
  76. </html>
  77. `
  78. // render default application error page with error and stack string.
  79. func showErr(err interface{}, ctx *context.Context, stack string) {
  80. t, _ := template.New("beegoerrortemp").Parse(tpl)
  81. data := map[string]string{
  82. "AppError": fmt.Sprintf("%s:%v", BConfig.AppName, err),
  83. "RequestMethod": ctx.Input.Method(),
  84. "RequestURL": ctx.Input.URI(),
  85. "RemoteAddr": ctx.Input.IP(),
  86. "Stack": stack,
  87. "BeegoVersion": VERSION,
  88. "GoVersion": runtime.Version(),
  89. }
  90. t.Execute(ctx.ResponseWriter, data)
  91. }
  92. var errtpl = `
  93. <!DOCTYPE html>
  94. <html lang="en">
  95. <head>
  96. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  97. <title>{{.Title}}</title>
  98. <style type="text/css">
  99. * {
  100. margin:0;
  101. padding:0;
  102. }
  103. body {
  104. background-color:#EFEFEF;
  105. font: .9em "Lucida Sans Unicode", "Lucida Grande", sans-serif;
  106. }
  107. #wrapper{
  108. width:600px;
  109. margin:40px auto 0;
  110. text-align:center;
  111. -moz-box-shadow: 5px 5px 10px rgba(0,0,0,0.3);
  112. -webkit-box-shadow: 5px 5px 10px rgba(0,0,0,0.3);
  113. box-shadow: 5px 5px 10px rgba(0,0,0,0.3);
  114. }
  115. #wrapper h1{
  116. color:#FFF;
  117. text-align:center;
  118. margin-bottom:20px;
  119. }
  120. #wrapper a{
  121. display:block;
  122. font-size:.9em;
  123. padding-top:20px;
  124. color:#FFF;
  125. text-decoration:none;
  126. text-align:center;
  127. }
  128. #container {
  129. width:600px;
  130. padding-bottom:15px;
  131. background-color:#FFFFFF;
  132. }
  133. .navtop{
  134. height:40px;
  135. background-color:#24B2EB;
  136. padding:13px;
  137. }
  138. .content {
  139. padding:10px 10px 25px;
  140. background: #FFFFFF;
  141. margin:;
  142. color:#333;
  143. }
  144. a.button{
  145. color:white;
  146. padding:15px 20px;
  147. text-shadow:1px 1px 0 #00A5FF;
  148. font-weight:bold;
  149. text-align:center;
  150. border:1px solid #24B2EB;
  151. margin:0px 200px;
  152. clear:both;
  153. background-color: #24B2EB;
  154. border-radius:100px;
  155. -moz-border-radius:100px;
  156. -webkit-border-radius:100px;
  157. }
  158. a.button:hover{
  159. text-decoration:none;
  160. background-color: #24B2EB;
  161. }
  162. </style>
  163. </head>
  164. <body>
  165. <div id="wrapper">
  166. <div id="container">
  167. <div class="navtop">
  168. <h1>{{.Title}}</h1>
  169. </div>
  170. <div id="content">
  171. {{.Content}}
  172. <a href="/" title="Home" class="button">Go Home</a><br />
  173. <br>Powered by beego {{.BeegoVersion}}
  174. </div>
  175. </div>
  176. </div>
  177. </body>
  178. </html>
  179. `
  180. type errorInfo struct {
  181. controllerType reflect.Type
  182. handler http.HandlerFunc
  183. method string
  184. errorType int
  185. }
  186. // ErrorMaps holds map of http handlers for each error string.
  187. // there is 10 kinds default error(40x and 50x)
  188. var ErrorMaps = make(map[string]*errorInfo, 10)
  189. // show 401 unauthorized error.
  190. func unauthorized(rw http.ResponseWriter, r *http.Request) {
  191. responseError(rw, r,
  192. 401,
  193. "<br>The page you have requested can't be authorized."+
  194. "<br>Perhaps you are here because:"+
  195. "<br><br><ul>"+
  196. "<br>The credentials you supplied are incorrect"+
  197. "<br>There are errors in the website address"+
  198. "</ul>",
  199. )
  200. }
  201. // show 402 Payment Required
  202. func paymentRequired(rw http.ResponseWriter, r *http.Request) {
  203. responseError(rw, r,
  204. 402,
  205. "<br>The page you have requested Payment Required."+
  206. "<br>Perhaps you are here because:"+
  207. "<br><br><ul>"+
  208. "<br>The credentials you supplied are incorrect"+
  209. "<br>There are errors in the website address"+
  210. "</ul>",
  211. )
  212. }
  213. // show 403 forbidden error.
  214. func forbidden(rw http.ResponseWriter, r *http.Request) {
  215. responseError(rw, r,
  216. 403,
  217. "<br>The page you have requested is forbidden."+
  218. "<br>Perhaps you are here because:"+
  219. "<br><br><ul>"+
  220. "<br>Your address may be blocked"+
  221. "<br>The site may be disabled"+
  222. "<br>You need to log in"+
  223. "</ul>",
  224. )
  225. }
  226. // show 422 missing xsrf token
  227. func missingxsrf(rw http.ResponseWriter, r *http.Request) {
  228. responseError(rw, r,
  229. 422,
  230. "<br>The page you have requested is forbidden."+
  231. "<br>Perhaps you are here because:"+
  232. "<br><br><ul>"+
  233. "<br>'_xsrf' argument missing from POST"+
  234. "</ul>",
  235. )
  236. }
  237. // show 417 invalid xsrf token
  238. func invalidxsrf(rw http.ResponseWriter, r *http.Request) {
  239. responseError(rw, r,
  240. 417,
  241. "<br>The page you have requested is forbidden."+
  242. "<br>Perhaps you are here because:"+
  243. "<br><br><ul>"+
  244. "<br>expected XSRF not found"+
  245. "</ul>",
  246. )
  247. }
  248. // show 404 not found error.
  249. func notFound(rw http.ResponseWriter, r *http.Request) {
  250. responseError(rw, r,
  251. 404,
  252. "<br>The page you have requested has flown the coop."+
  253. "<br>Perhaps you are here because:"+
  254. "<br><br><ul>"+
  255. "<br>The page has moved"+
  256. "<br>The page no longer exists"+
  257. "<br>You were looking for your puppy and got lost"+
  258. "<br>You like 404 pages"+
  259. "</ul>",
  260. )
  261. }
  262. // show 405 Method Not Allowed
  263. func methodNotAllowed(rw http.ResponseWriter, r *http.Request) {
  264. responseError(rw, r,
  265. 405,
  266. "<br>The method you have requested Not Allowed."+
  267. "<br>Perhaps you are here because:"+
  268. "<br><br><ul>"+
  269. "<br>The method specified in the Request-Line is not allowed for the resource identified by the Request-URI"+
  270. "<br>The response MUST include an Allow header containing a list of valid methods for the requested resource."+
  271. "</ul>",
  272. )
  273. }
  274. // show 500 internal server error.
  275. func internalServerError(rw http.ResponseWriter, r *http.Request) {
  276. responseError(rw, r,
  277. 500,
  278. "<br>The page you have requested is down right now."+
  279. "<br><br><ul>"+
  280. "<br>Please try again later and report the error to the website administrator"+
  281. "<br></ul>",
  282. )
  283. }
  284. // show 501 Not Implemented.
  285. func notImplemented(rw http.ResponseWriter, r *http.Request) {
  286. responseError(rw, r,
  287. 501,
  288. "<br>The page you have requested is Not Implemented."+
  289. "<br><br><ul>"+
  290. "<br>Please try again later and report the error to the website administrator"+
  291. "<br></ul>",
  292. )
  293. }
  294. // show 502 Bad Gateway.
  295. func badGateway(rw http.ResponseWriter, r *http.Request) {
  296. responseError(rw, r,
  297. 502,
  298. "<br>The page you have requested is down right now."+
  299. "<br><br><ul>"+
  300. "<br>The server, while acting as a gateway or proxy, received an invalid response from the upstream server it accessed in attempting to fulfill the request."+
  301. "<br>Please try again later and report the error to the website administrator"+
  302. "<br></ul>",
  303. )
  304. }
  305. // show 503 service unavailable error.
  306. func serviceUnavailable(rw http.ResponseWriter, r *http.Request) {
  307. responseError(rw, r,
  308. 503,
  309. "<br>The page you have requested is unavailable."+
  310. "<br>Perhaps you are here because:"+
  311. "<br><br><ul>"+
  312. "<br><br>The page is overloaded"+
  313. "<br>Please try again later."+
  314. "</ul>",
  315. )
  316. }
  317. // show 504 Gateway Timeout.
  318. func gatewayTimeout(rw http.ResponseWriter, r *http.Request) {
  319. responseError(rw, r,
  320. 504,
  321. "<br>The page you have requested is unavailable"+
  322. "<br>Perhaps you are here because:"+
  323. "<br><br><ul>"+
  324. "<br><br>The server, while acting as a gateway or proxy, did not receive a timely response from the upstream server specified by the URI."+
  325. "<br>Please try again later."+
  326. "</ul>",
  327. )
  328. }
  329. func responseError(rw http.ResponseWriter, r *http.Request, errCode int, errContent string) {
  330. t, _ := template.New("beegoerrortemp").Parse(errtpl)
  331. data := M{
  332. "Title": http.StatusText(errCode),
  333. "BeegoVersion": VERSION,
  334. "Content": template.HTML(errContent),
  335. }
  336. t.Execute(rw, data)
  337. }
  338. // ErrorHandler registers http.HandlerFunc to each http err code string.
  339. // usage:
  340. // beego.ErrorHandler("404",NotFound)
  341. // beego.ErrorHandler("500",InternalServerError)
  342. func ErrorHandler(code string, h http.HandlerFunc) *App {
  343. ErrorMaps[code] = &errorInfo{
  344. errorType: errorTypeHandler,
  345. handler: h,
  346. method: code,
  347. }
  348. return BeeApp
  349. }
  350. // ErrorController registers ControllerInterface to each http err code string.
  351. // usage:
  352. // beego.ErrorController(&controllers.ErrorController{})
  353. func ErrorController(c ControllerInterface) *App {
  354. reflectVal := reflect.ValueOf(c)
  355. rt := reflectVal.Type()
  356. ct := reflect.Indirect(reflectVal).Type()
  357. for i := 0; i < rt.NumMethod(); i++ {
  358. methodName := rt.Method(i).Name
  359. if !utils.InSlice(methodName, exceptMethod) && strings.HasPrefix(methodName, "Error") {
  360. errName := strings.TrimPrefix(methodName, "Error")
  361. ErrorMaps[errName] = &errorInfo{
  362. errorType: errorTypeController,
  363. controllerType: ct,
  364. method: methodName,
  365. }
  366. }
  367. }
  368. return BeeApp
  369. }
  370. // Exception Write HttpStatus with errCode and Exec error handler if exist.
  371. func Exception(errCode uint64, ctx *context.Context) {
  372. exception(strconv.FormatUint(errCode, 10), ctx)
  373. }
  374. // show error string as simple text message.
  375. // if error string is empty, show 503 or 500 error as default.
  376. func exception(errCode string, ctx *context.Context) {
  377. atoi := func(code string) int {
  378. v, err := strconv.Atoi(code)
  379. if err == nil {
  380. return v
  381. }
  382. if ctx.Output.Status == 0 {
  383. return 503
  384. }
  385. return ctx.Output.Status
  386. }
  387. for _, ec := range []string{errCode, "503", "500"} {
  388. if h, ok := ErrorMaps[ec]; ok {
  389. executeError(h, ctx, atoi(ec))
  390. return
  391. }
  392. }
  393. //if 50x error has been removed from errorMap
  394. ctx.ResponseWriter.WriteHeader(atoi(errCode))
  395. ctx.WriteString(errCode)
  396. }
  397. func executeError(err *errorInfo, ctx *context.Context, code int) {
  398. //make sure to log the error in the access log
  399. logAccess(ctx, nil, code)
  400. if err.errorType == errorTypeHandler {
  401. ctx.ResponseWriter.WriteHeader(code)
  402. err.handler(ctx.ResponseWriter, ctx.Request)
  403. return
  404. }
  405. if err.errorType == errorTypeController {
  406. ctx.Output.SetStatus(code)
  407. //Invoke the request handler
  408. vc := reflect.New(err.controllerType)
  409. execController, ok := vc.Interface().(ControllerInterface)
  410. if !ok {
  411. panic("controller is not ControllerInterface")
  412. }
  413. //call the controller init function
  414. execController.Init(ctx, err.controllerType.Name(), err.method, vc.Interface())
  415. //call prepare function
  416. execController.Prepare()
  417. execController.URLMapping()
  418. method := vc.MethodByName(err.method)
  419. method.Call([]reflect.Value{})
  420. //render template
  421. if BConfig.WebConfig.AutoRender {
  422. if err := execController.Render(); err != nil {
  423. panic(err)
  424. }
  425. }
  426. // finish all runrouter. release resource
  427. execController.Finish()
  428. }
  429. }