error.go 12 KB

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