Micro & pluggable web framework for Go
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

94 lines
2.2KB

  1. // Copyright 2015 The Tango Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package tango
  5. import (
  6. "fmt"
  7. "net/http"
  8. )
  9. // AbortError defines an interface to describe HTTP error
  10. type AbortError interface {
  11. error
  12. Code() int
  13. }
  14. type abortError struct {
  15. code int
  16. content string
  17. }
  18. func (a *abortError) Code() int {
  19. return a.code
  20. }
  21. func (a *abortError) Error() string {
  22. return fmt.Sprintf("%v", a.content)
  23. }
  24. // Abort returns an AbortError
  25. func Abort(code int, content ...string) AbortError {
  26. if len(content) >= 1 {
  27. return &abortError{code, content[0]}
  28. }
  29. return &abortError{code, http.StatusText(code)}
  30. }
  31. // NotFound returns not found HTTP error
  32. func NotFound(content ...string) AbortError {
  33. return Abort(http.StatusNotFound, content...)
  34. }
  35. // NotSupported returns not supported HTTP error
  36. func NotSupported(content ...string) AbortError {
  37. return Abort(http.StatusMethodNotAllowed, content...)
  38. }
  39. // InternalServerError returns internal server HTTP error
  40. func InternalServerError(content ...string) AbortError {
  41. return Abort(http.StatusInternalServerError, content...)
  42. }
  43. // Forbidden returns forbidden HTTP error
  44. func Forbidden(content ...string) AbortError {
  45. return Abort(http.StatusForbidden, content...)
  46. }
  47. // Unauthorized returns unauthorized HTTP error
  48. func Unauthorized(content ...string) AbortError {
  49. return Abort(http.StatusUnauthorized, content...)
  50. }
  51. // Errors returns default errorhandler, you can use your self handler
  52. func Errors() HandlerFunc {
  53. return func(ctx *Context) {
  54. switch res := ctx.Result.(type) {
  55. case AbortError:
  56. ctx.WriteHeader(res.Code())
  57. ctx.WriteString(res.Error())
  58. case error:
  59. ctx.WriteHeader(http.StatusInternalServerError)
  60. ctx.WriteString(res.Error())
  61. default:
  62. ctx.WriteHeader(http.StatusInternalServerError)
  63. ctx.WriteString(http.StatusText(http.StatusInternalServerError))
  64. }
  65. }
  66. }
  67. // ErrorWithCode descripts an error that with error code
  68. type ErrorWithCode interface {
  69. error
  70. ErrorCode() int
  71. }
  72. type ErrorKeyIsNotExist struct {
  73. Key string
  74. }
  75. func (e ErrorKeyIsNotExist) Error() string {
  76. return fmt.Sprintf("Key %s is not exist", e.Key)
  77. }