27 Star 83 Fork 11

lunny/tango

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
error.go 1.58 KB
一键复制 编辑 原始数据 按行查看 历史
lunny 提交于 2015-04-28 15:42 . license & small optimization
// Copyright 2015 The Tango Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tango
import (
"fmt"
"net/http"
)
type AbortError interface {
error
Code() int
}
type abortError struct {
code int
content string
}
func (a *abortError) Code() int {
return a.code
}
func (a *abortError) Error() string {
return fmt.Sprintf("%v", a.content)
}
func Abort(code int, content ...string) AbortError {
if len(content) >= 1 {
return &abortError{code, content[0]}
}
return &abortError{code, http.StatusText(code)}
}
func NotFound(content ...string) AbortError {
return Abort(http.StatusNotFound, content...)
}
func NotSupported(content ...string) AbortError {
return Abort(http.StatusMethodNotAllowed, content...)
}
func InternalServerError(content ...string) AbortError {
return Abort(http.StatusInternalServerError, content...)
}
func Forbidden(content ...string) AbortError {
return Abort(http.StatusForbidden, content...)
}
func Unauthorized(content ...string) AbortError {
return Abort(http.StatusUnauthorized, content...)
}
// default errorhandler, you can use your self handler
func Errors() HandlerFunc {
return func(ctx *Context) {
switch res := ctx.Result.(type) {
case AbortError:
ctx.WriteHeader(res.Code())
ctx.Write([]byte(res.Error()))
case error:
ctx.WriteHeader(http.StatusInternalServerError)
ctx.Write([]byte(res.Error()))
default:
ctx.WriteHeader(http.StatusInternalServerError)
ctx.Write([]byte(http.StatusText(http.StatusInternalServerError)))
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/lunny/tango.git
git@gitee.com:lunny/tango.git
lunny
tango
tango
v0.5.0

搜索帮助

0d507c66 1850385 C8b1a773 1850385