error.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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/astaxie/beego/context"
  24. "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. ctx.ResponseWriter.WriteHeader(500)
  91. t.Execute(ctx.ResponseWriter, data)
  92. }
  93. var errtpl = `
  94. <!DOCTYPE html>
  95. <html lang="en">
  96. <head>
  97. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  98. <title>{{.Title}}</title>
  99. <style type="text/css">
  100. * {
  101. margin:0;
  102. padding:0;
  103. }
  104. body {
  105. background-color:#EFEFEF;
  106. font: .9em "Lucida Sans Unicode", "Lucida Grande", sans-serif;
  107. }
  108. #wrapper{
  109. width:600px;
  110. margin:40px auto 0;
  111. text-align:center;
  112. -moz-box-shadow: 5px 5px 10px rgba(0,0,0,0.3);
  113. -webkit-box-shadow: 5px 5px 10px rgba(0,0,0,0.3);
  114. box-shadow: 5px 5px 10px rgba(0,0,0,0.3);
  115. }
  116. #wrapper h1{
  117. color:#FFF;
  118. text-align:center;
  119. margin-bottom:20px;
  120. }
  121. #wrapper a{
  122. display:block;
  123. font-size:.9em;
  124. padding-top:20px;
  125. color:#FFF;
  126. text-decoration:none;
  127. text-align:center;
  128. }
  129. #container {
  130. width:600px;
  131. padding-bottom:15px;
  132. background-color:#FFFFFF;
  133. }
  134. .navtop{
  135. height:40px;
  136. background-color:#24B2EB;
  137. padding:13px;
  138. }
  139. .content {
  140. padding:10px 10px 25px;
  141. background: #FFFFFF;
  142. margin:;
  143. color:#333;
  144. }
  145. a.button{
  146. color:white;
  147. padding:15px 20px;
  148. text-shadow:1px 1px 0 #00A5FF;
  149. font-weight:bold;
  150. text-align:center;
  151. border:1px solid #24B2EB;
  152. margin:0px 200px;
  153. clear:both;
  154. background-color: #24B2EB;
  155. border-radius:100px;
  156. -moz-border-radius:100px;
  157. -webkit-border-radius:100px;
  158. }
  159. a.button:hover{
  160. text-decoration:none;
  161. background-color: #24B2EB;
  162. }
  163. </style>
  164. </head>
  165. <body>
  166. <div id="wrapper">
  167. <div id="container">
  168. <div class="navtop">
  169. <h1>{{.Title}}</h1>
  170. </div>
  171. <div id="content">
  172. {{.Content}}
  173. <a href="/" title="Home" class="button">Go Home</a><br />
  174. <br>Powered by beego {{.BeegoVersion}}
  175. </div>
  176. </div>
  177. </div>
  178. </body>
  179. </html>
  180. `
  181. type errorInfo struct {
  182. controllerType reflect.Type
  183. handler http.HandlerFunc
  184. method string
  185. errorType int
  186. }
  187. // ErrorMaps holds map of http handlers for each error string.
  188. // there is 10 kinds default error(40x and 50x)
  189. var ErrorMaps = make(map[string]*errorInfo, 10)
  190. // show 401 unauthorized error.
  191. func unauthorized(rw http.ResponseWriter, r *http.Request) {
  192. t, _ := template.New("beegoerrortemp").Parse(errtpl)
  193. data := map[string]interface{}{
  194. "Title": http.StatusText(401),
  195. "BeegoVersion": VERSION,
  196. }
  197. data["Content"] = template.HTML("<br>The page you have requested can't be authorized." +
  198. "<br>Perhaps you are here because:" +
  199. "<br><br><ul>" +
  200. "<br>The credentials you supplied are incorrect" +
  201. "<br>There are errors in the website address" +
  202. "</ul>")
  203. t.Execute(rw, data)
  204. }
  205. // show 402 Payment Required
  206. func paymentRequired(rw http.ResponseWriter, r *http.Request) {
  207. t, _ := template.New("beegoerrortemp").Parse(errtpl)
  208. data := map[string]interface{}{
  209. "Title": http.StatusText(402),
  210. "BeegoVersion": VERSION,
  211. }
  212. data["Content"] = template.HTML("<br>The page you have requested Payment Required." +
  213. "<br>Perhaps you are here because:" +
  214. "<br><br><ul>" +
  215. "<br>The credentials you supplied are incorrect" +
  216. "<br>There are errors in the website address" +
  217. "</ul>")
  218. t.Execute(rw, data)
  219. }
  220. // show 403 forbidden error.
  221. func forbidden(rw http.ResponseWriter, r *http.Request) {
  222. t, _ := template.New("beegoerrortemp").Parse(errtpl)
  223. data := map[string]interface{}{
  224. "Title": http.StatusText(403),
  225. "BeegoVersion": VERSION,
  226. }
  227. data["Content"] = template.HTML("<br>The page you have requested is forbidden." +
  228. "<br>Perhaps you are here because:" +
  229. "<br><br><ul>" +
  230. "<br>Your address may be blocked" +
  231. "<br>The site may be disabled" +
  232. "<br>You need to log in" +
  233. "</ul>")
  234. t.Execute(rw, data)
  235. }
  236. // show 404 notfound error.
  237. func notFound(rw http.ResponseWriter, r *http.Request) {
  238. t, _ := template.New("beegoerrortemp").Parse(errtpl)
  239. data := map[string]interface{}{
  240. "Title": http.StatusText(404),
  241. "BeegoVersion": VERSION,
  242. }
  243. data["Content"] = template.HTML("<br>The page you have requested has flown the coop." +
  244. "<br>Perhaps you are here because:" +
  245. "<br><br><ul>" +
  246. "<br>The page has moved" +
  247. "<br>The page no longer exists" +
  248. "<br>You were looking for your puppy and got lost" +
  249. "<br>You like 404 pages" +
  250. "</ul>")
  251. t.Execute(rw, data)
  252. }
  253. // show 405 Method Not Allowed
  254. func methodNotAllowed(rw http.ResponseWriter, r *http.Request) {
  255. t, _ := template.New("beegoerrortemp").Parse(errtpl)
  256. data := map[string]interface{}{
  257. "Title": http.StatusText(405),
  258. "BeegoVersion": VERSION,
  259. }
  260. data["Content"] = template.HTML("<br>The method you have requested Not Allowed." +
  261. "<br>Perhaps you are here because:" +
  262. "<br><br><ul>" +
  263. "<br>The method specified in the Request-Line is not allowed for the resource identified by the Request-URI" +
  264. "<br>The response MUST include an Allow header containing a list of valid methods for the requested resource." +
  265. "</ul>")
  266. t.Execute(rw, data)
  267. }
  268. // show 500 internal server error.
  269. func internalServerError(rw http.ResponseWriter, r *http.Request) {
  270. t, _ := template.New("beegoerrortemp").Parse(errtpl)
  271. data := map[string]interface{}{
  272. "Title": http.StatusText(500),
  273. "BeegoVersion": VERSION,
  274. }
  275. data["Content"] = template.HTML("<br>The page you have requested is down right now." +
  276. "<br><br><ul>" +
  277. "<br>Please try again later and report the error to the website administrator" +
  278. "<br></ul>")
  279. t.Execute(rw, data)
  280. }
  281. // show 501 Not Implemented.
  282. func notImplemented(rw http.ResponseWriter, r *http.Request) {
  283. t, _ := template.New("beegoerrortemp").Parse(errtpl)
  284. data := map[string]interface{}{
  285. "Title": http.StatusText(504),
  286. "BeegoVersion": VERSION,
  287. }
  288. data["Content"] = template.HTML("<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. t.Execute(rw, data)
  293. }
  294. // show 502 Bad Gateway.
  295. func badGateway(rw http.ResponseWriter, r *http.Request) {
  296. t, _ := template.New("beegoerrortemp").Parse(errtpl)
  297. data := map[string]interface{}{
  298. "Title": http.StatusText(502),
  299. "BeegoVersion": VERSION,
  300. }
  301. data["Content"] = template.HTML("<br>The page you have requested is down right now." +
  302. "<br><br><ul>" +
  303. "<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." +
  304. "<br>Please try again later and report the error to the website administrator" +
  305. "<br></ul>")
  306. t.Execute(rw, data)
  307. }
  308. // show 503 service unavailable error.
  309. func serviceUnavailable(rw http.ResponseWriter, r *http.Request) {
  310. t, _ := template.New("beegoerrortemp").Parse(errtpl)
  311. data := map[string]interface{}{
  312. "Title": http.StatusText(503),
  313. "BeegoVersion": VERSION,
  314. }
  315. data["Content"] = template.HTML("<br>The page you have requested is unavailable." +
  316. "<br>Perhaps you are here because:" +
  317. "<br><br><ul>" +
  318. "<br><br>The page is overloaded" +
  319. "<br>Please try again later." +
  320. "</ul>")
  321. t.Execute(rw, data)
  322. }
  323. // show 504 Gateway Timeout.
  324. func gatewayTimeout(rw http.ResponseWriter, r *http.Request) {
  325. t, _ := template.New("beegoerrortemp").Parse(errtpl)
  326. data := map[string]interface{}{
  327. "Title": http.StatusText(504),
  328. "BeegoVersion": VERSION,
  329. }
  330. data["Content"] = template.HTML("<br>The page you have requested is unavailable." +
  331. "<br>Perhaps you are here because:" +
  332. "<br><br><ul>" +
  333. "<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." +
  334. "<br>Please try again later." +
  335. "</ul>")
  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. // show error string as simple text message.
  371. // if error string is empty, show 503 or 500 error as default.
  372. func exception(errCode string, ctx *context.Context) {
  373. atoi := func(code string) int {
  374. v, err := strconv.Atoi(code)
  375. if err == nil {
  376. return v
  377. }
  378. return 503
  379. }
  380. for _, ec := range []string{errCode, "503", "500"} {
  381. if h, ok := ErrorMaps[ec]; ok {
  382. executeError(h, ctx, atoi(ec))
  383. return
  384. }
  385. }
  386. //if 50x error has been removed from errorMap
  387. ctx.ResponseWriter.WriteHeader(atoi(errCode))
  388. ctx.WriteString(errCode)
  389. }
  390. func executeError(err *errorInfo, ctx *context.Context, code int) {
  391. if err.errorType == errorTypeHandler {
  392. ctx.ResponseWriter.WriteHeader(code)
  393. err.handler(ctx.ResponseWriter, ctx.Request)
  394. return
  395. }
  396. if err.errorType == errorTypeController {
  397. ctx.Output.SetStatus(code)
  398. //Invoke the request handler
  399. vc := reflect.New(err.controllerType)
  400. execController, ok := vc.Interface().(ControllerInterface)
  401. if !ok {
  402. panic("controller is not ControllerInterface")
  403. }
  404. //call the controller init function
  405. execController.Init(ctx, err.controllerType.Name(), err.method, vc.Interface())
  406. //call prepare function
  407. execController.Prepare()
  408. execController.URLMapping()
  409. method := vc.MethodByName(err.method)
  410. method.Call([]reflect.Value{})
  411. //render template
  412. if BConfig.WebConfig.AutoRender {
  413. if err := execController.Render(); err != nil {
  414. panic(err)
  415. }
  416. }
  417. // finish all runrouter. release resource
  418. execController.Finish()
  419. }
  420. }