1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-22 17:40:55 +00:00

golint context

This commit is contained in:
astaxie 2015-09-10 15:31:09 +08:00
parent bdd6a6ae40
commit ff5b09fc19
7 changed files with 93 additions and 92 deletions

View File

@ -141,7 +141,7 @@ var (
) )
type beegoAppConfig struct { type beegoAppConfig struct {
innerConfig config.ConfigContainer innerConfig config.Configer
} }
func newAppConfig(AppConfigProvider, AppConfigPath string) (*beegoAppConfig, error) { func newAppConfig(AppConfigProvider, AppConfigPath string) (*beegoAppConfig, error) {

View File

@ -12,6 +12,7 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
// Package context provide the context utils
// Usage: // Usage:
// //
// import "github.com/astaxie/beego/context" // import "github.com/astaxie/beego/context"
@ -34,14 +35,14 @@ import (
"github.com/astaxie/beego/utils" "github.com/astaxie/beego/utils"
) )
// Http request context struct including BeegoInput, BeegoOutput, http.Request and http.ResponseWriter. // Context Http request context struct including BeegoInput, BeegoOutput, http.Request and http.ResponseWriter.
// BeegoInput and BeegoOutput provides some api to operate request and response more easily. // BeegoInput and BeegoOutput provides some api to operate request and response more easily.
type Context struct { type Context struct {
Input *BeegoInput Input *BeegoInput
Output *BeegoOutput Output *BeegoOutput
Request *http.Request Request *http.Request
ResponseWriter http.ResponseWriter ResponseWriter http.ResponseWriter
_xsrf_token string _xsrfToken string
} }
// Redirect does redirection to localurl with http header status code. // Redirect does redirection to localurl with http header status code.
@ -58,25 +59,25 @@ func (ctx *Context) Abort(status int, body string) {
panic(body) panic(body)
} }
// Write string to response body. // WriteString Write string to response body.
// it sends response body. // it sends response body.
func (ctx *Context) WriteString(content string) { func (ctx *Context) WriteString(content string) {
ctx.ResponseWriter.Write([]byte(content)) ctx.ResponseWriter.Write([]byte(content))
} }
// Get cookie from request by a given key. // GetCookie Get cookie from request by a given key.
// It's alias of BeegoInput.Cookie. // It's alias of BeegoInput.Cookie.
func (ctx *Context) GetCookie(key string) string { func (ctx *Context) GetCookie(key string) string {
return ctx.Input.Cookie(key) return ctx.Input.Cookie(key)
} }
// Set cookie for response. // SetCookie Set cookie for response.
// It's alias of BeegoOutput.Cookie. // It's alias of BeegoOutput.Cookie.
func (ctx *Context) SetCookie(name string, value string, others ...interface{}) { func (ctx *Context) SetCookie(name string, value string, others ...interface{}) {
ctx.Output.Cookie(name, value, others...) ctx.Output.Cookie(name, value, others...)
} }
// Get secure cookie from request by a given key. // GetSecureCookie Get secure cookie from request by a given key.
func (ctx *Context) GetSecureCookie(Secret, key string) (string, bool) { func (ctx *Context) GetSecureCookie(Secret, key string) (string, bool) {
val := ctx.Input.Cookie(key) val := ctx.Input.Cookie(key)
if val == "" { if val == "" {
@ -103,7 +104,7 @@ func (ctx *Context) GetSecureCookie(Secret, key string) (string, bool) {
return string(res), true return string(res), true
} }
// Set Secure cookie for response. // SetSecureCookie Set Secure cookie for response.
func (ctx *Context) SetSecureCookie(Secret, name, value string, others ...interface{}) { func (ctx *Context) SetSecureCookie(Secret, name, value string, others ...interface{}) {
vs := base64.URLEncoding.EncodeToString([]byte(value)) vs := base64.URLEncoding.EncodeToString([]byte(value))
timestamp := strconv.FormatInt(time.Now().UnixNano(), 10) timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
@ -114,23 +115,23 @@ func (ctx *Context) SetSecureCookie(Secret, name, value string, others ...interf
ctx.Output.Cookie(name, cookie, others...) ctx.Output.Cookie(name, cookie, others...)
} }
// XsrfToken creates a xsrf token string and returns. // XSRFToken creates a xsrf token string and returns.
func (ctx *Context) XsrfToken(key string, expire int64) string { func (ctx *Context) XSRFToken(key string, expire int64) string {
if ctx._xsrf_token == "" { if ctx._xsrfToken == "" {
token, ok := ctx.GetSecureCookie(key, "_xsrf") token, ok := ctx.GetSecureCookie(key, "_xsrf")
if !ok { if !ok {
token = string(utils.RandomCreateBytes(32)) token = string(utils.RandomCreateBytes(32))
ctx.SetSecureCookie(key, "_xsrf", token, expire) ctx.SetSecureCookie(key, "_xsrf", token, expire)
} }
ctx._xsrf_token = token ctx._xsrfToken = token
} }
return ctx._xsrf_token return ctx._xsrfToken
} }
// CheckXsrfCookie checks xsrf token in this request is valid or not. // CheckXSRFCookie checks xsrf token in this request is valid or not.
// the token can provided in request header "X-Xsrftoken" and "X-CsrfToken" // the token can provided in request header "X-Xsrftoken" and "X-CsrfToken"
// or in form field value named as "_xsrf". // or in form field value named as "_xsrf".
func (ctx *Context) CheckXsrfCookie() bool { func (ctx *Context) CheckXSRFCookie() bool {
token := ctx.Input.Query("_xsrf") token := ctx.Input.Query("_xsrf")
if token == "" { if token == "" {
token = ctx.Request.Header.Get("X-Xsrftoken") token = ctx.Request.Header.Get("X-Xsrftoken")
@ -142,7 +143,7 @@ func (ctx *Context) CheckXsrfCookie() bool {
ctx.Abort(403, "'_xsrf' argument missing from POST") ctx.Abort(403, "'_xsrf' argument missing from POST")
return false return false
} }
if ctx._xsrf_token != token { if ctx._xsrfToken != token {
ctx.Abort(403, "XSRF cookie does not match POST argument") ctx.Abort(403, "XSRF cookie does not match POST argument")
return false return false
} }

View File

@ -31,9 +31,9 @@ import (
// Regexes for checking the accept headers // Regexes for checking the accept headers
// TODO make sure these are correct // TODO make sure these are correct
var ( var (
acceptsHtmlRegex = regexp.MustCompile(`(text/html|application/xhtml\+xml)(?:,|$)`) acceptsHTMLRegex = regexp.MustCompile(`(text/html|application/xhtml\+xml)(?:,|$)`)
acceptsXmlRegex = regexp.MustCompile(`(application/xml|text/xml)(?:,|$)`) acceptsXMLRegex = regexp.MustCompile(`(application/xml|text/xml)(?:,|$)`)
acceptsJsonRegex = regexp.MustCompile(`(application/json)(?:,|$)`) acceptsJSONRegex = regexp.MustCompile(`(application/json)(?:,|$)`)
) )
// BeegoInput operates the http request header, data, cookie and body. // BeegoInput operates the http request header, data, cookie and body.
@ -62,13 +62,13 @@ func (input *BeegoInput) Protocol() string {
return input.Request.Proto return input.Request.Proto
} }
// Uri returns full request url with query string, fragment. // URI returns full request url with query string, fragment.
func (input *BeegoInput) Uri() string { func (input *BeegoInput) URI() string {
return input.Request.RequestURI return input.Request.RequestURI
} }
// Url returns request url path (without query string, fragment). // URL returns request url path (without query string, fragment).
func (input *BeegoInput) Url() string { func (input *BeegoInput) URL() string {
return input.Request.URL.Path return input.Request.URL.Path
} }
@ -117,37 +117,37 @@ func (input *BeegoInput) Is(method string) bool {
return input.Method() == method return input.Method() == method
} }
// Is this a GET method request? // IsGet Is this a GET method request?
func (input *BeegoInput) IsGet() bool { func (input *BeegoInput) IsGet() bool {
return input.Is("GET") return input.Is("GET")
} }
// Is this a POST method request? // IsPost Is this a POST method request?
func (input *BeegoInput) IsPost() bool { func (input *BeegoInput) IsPost() bool {
return input.Is("POST") return input.Is("POST")
} }
// Is this a Head method request? // IsHead Is this a Head method request?
func (input *BeegoInput) IsHead() bool { func (input *BeegoInput) IsHead() bool {
return input.Is("HEAD") return input.Is("HEAD")
} }
// Is this a OPTIONS method request? // IsOptions Is this a OPTIONS method request?
func (input *BeegoInput) IsOptions() bool { func (input *BeegoInput) IsOptions() bool {
return input.Is("OPTIONS") return input.Is("OPTIONS")
} }
// Is this a PUT method request? // IsPut Is this a PUT method request?
func (input *BeegoInput) IsPut() bool { func (input *BeegoInput) IsPut() bool {
return input.Is("PUT") return input.Is("PUT")
} }
// Is this a DELETE method request? // IsDelete Is this a DELETE method request?
func (input *BeegoInput) IsDelete() bool { func (input *BeegoInput) IsDelete() bool {
return input.Is("DELETE") return input.Is("DELETE")
} }
// Is this a PATCH method request? // IsPatch Is this a PATCH method request?
func (input *BeegoInput) IsPatch() bool { func (input *BeegoInput) IsPatch() bool {
return input.Is("PATCH") return input.Is("PATCH")
} }
@ -172,19 +172,19 @@ func (input *BeegoInput) IsUpload() bool {
return strings.Contains(input.Header("Content-Type"), "multipart/form-data") return strings.Contains(input.Header("Content-Type"), "multipart/form-data")
} }
// Checks if request accepts html response // AcceptsHTML Checks if request accepts html response
func (input *BeegoInput) AcceptsHtml() bool { func (input *BeegoInput) AcceptsHTML() bool {
return acceptsHtmlRegex.MatchString(input.Header("Accept")) return acceptsHTMLRegex.MatchString(input.Header("Accept"))
} }
// Checks if request accepts xml response // AcceptsXML Checks if request accepts xml response
func (input *BeegoInput) AcceptsXml() bool { func (input *BeegoInput) AcceptsXML() bool {
return acceptsXmlRegex.MatchString(input.Header("Accept")) return acceptsXMLRegex.MatchString(input.Header("Accept"))
} }
// Checks if request accepts json response // AcceptsJSON Checks if request accepts json response
func (input *BeegoInput) AcceptsJson() bool { func (input *BeegoInput) AcceptsJSON() bool {
return acceptsJsonRegex.MatchString(input.Header("Accept")) return acceptsJSONRegex.MatchString(input.Header("Accept"))
} }
// IP returns request client ip. // IP returns request client ip.
@ -314,7 +314,7 @@ func (input *BeegoInput) SetData(key, val interface{}) {
input.Data[key] = val input.Data[key] = val
} }
// parseForm or parseMultiForm based on Content-type // ParseFormOrMulitForm parseForm or parseMultiForm based on Content-type
func (input *BeegoInput) ParseFormOrMulitForm(maxMemory int64) error { func (input *BeegoInput) ParseFormOrMulitForm(maxMemory int64) error {
// Parse the body depending on the content type. // Parse the body depending on the content type.
if strings.Contains(input.Header("Content-Type"), "multipart/form-data") { if strings.Contains(input.Header("Content-Type"), "multipart/form-data") {

View File

@ -54,7 +54,7 @@ func (output *BeegoOutput) Header(key, val string) {
// if EnableGzip, compress content string. // if EnableGzip, compress content string.
// it sends out response body directly. // it sends out response body directly.
func (output *BeegoOutput) Body(content []byte) { func (output *BeegoOutput) Body(content []byte) {
output_writer := output.Context.ResponseWriter.(io.Writer) outputWriter := output.Context.ResponseWriter.(io.Writer)
if output.EnableGzip == true && output.Context.Input.Header("Accept-Encoding") != "" { if output.EnableGzip == true && output.Context.Input.Header("Accept-Encoding") != "" {
splitted := strings.SplitN(output.Context.Input.Header("Accept-Encoding"), ",", -1) splitted := strings.SplitN(output.Context.Input.Header("Accept-Encoding"), ",", -1)
encodings := make([]string, len(splitted)) encodings := make([]string, len(splitted))
@ -65,12 +65,12 @@ func (output *BeegoOutput) Body(content []byte) {
for _, val := range encodings { for _, val := range encodings {
if val == "gzip" { if val == "gzip" {
output.Header("Content-Encoding", "gzip") output.Header("Content-Encoding", "gzip")
output_writer, _ = gzip.NewWriterLevel(output.Context.ResponseWriter, gzip.BestSpeed) outputWriter, _ = gzip.NewWriterLevel(output.Context.ResponseWriter, gzip.BestSpeed)
break break
} else if val == "deflate" { } else if val == "deflate" {
output.Header("Content-Encoding", "deflate") output.Header("Content-Encoding", "deflate")
output_writer, _ = flate.NewWriter(output.Context.ResponseWriter, flate.BestSpeed) outputWriter, _ = flate.NewWriter(output.Context.ResponseWriter, flate.BestSpeed)
break break
} }
} }
@ -85,12 +85,12 @@ func (output *BeegoOutput) Body(content []byte) {
output.Status = 0 output.Status = 0
} }
output_writer.Write(content) outputWriter.Write(content)
switch output_writer.(type) { switch outputWriter.(type) {
case *gzip.Writer: case *gzip.Writer:
output_writer.(*gzip.Writer).Close() outputWriter.(*gzip.Writer).Close()
case *flate.Writer: case *flate.Writer:
output_writer.(*flate.Writer).Close() outputWriter.(*flate.Writer).Close()
} }
} }
@ -100,29 +100,29 @@ func (output *BeegoOutput) Cookie(name string, value string, others ...interface
var b bytes.Buffer var b bytes.Buffer
fmt.Fprintf(&b, "%s=%s", sanitizeName(name), sanitizeValue(value)) fmt.Fprintf(&b, "%s=%s", sanitizeName(name), sanitizeValue(value))
//fix cookie not work in IE //fix cookie not work in IE
if len(others) > 0 { if len(others) > 0 {
switch v := others[0].(type) { switch v := others[0].(type) {
case int: case int:
if v > 0 { if v > 0 {
fmt.Fprintf(&b, "; Expires=%s; Max-Age=%d", time.Now().Add(time.Duration(v) * time.Second).UTC().Format(time.RFC1123), v) fmt.Fprintf(&b, "; Expires=%s; Max-Age=%d", time.Now().Add(time.Duration(v)*time.Second).UTC().Format(time.RFC1123), v)
} else if v < 0 { } else if v < 0 {
fmt.Fprintf(&b, "; Max-Age=0") fmt.Fprintf(&b, "; Max-Age=0")
} }
case int64: case int64:
if v > 0 { if v > 0 {
fmt.Fprintf(&b, "; Expires=%s; Max-Age=%d", time.Now().Add(time.Duration(v) * time.Second).UTC().Format(time.RFC1123), v) fmt.Fprintf(&b, "; Expires=%s; Max-Age=%d", time.Now().Add(time.Duration(v)*time.Second).UTC().Format(time.RFC1123), v)
} else if v < 0 { } else if v < 0 {
fmt.Fprintf(&b, "; Max-Age=0") fmt.Fprintf(&b, "; Max-Age=0")
} }
case int32: case int32:
if v > 0 { if v > 0 {
fmt.Fprintf(&b, "; Expires=%s; Max-Age=%d", time.Now().Add(time.Duration(v) * time.Second).UTC().Format(time.RFC1123), v) fmt.Fprintf(&b, "; Expires=%s; Max-Age=%d", time.Now().Add(time.Duration(v)*time.Second).UTC().Format(time.RFC1123), v)
} else if v < 0 { } else if v < 0 {
fmt.Fprintf(&b, "; Max-Age=0") fmt.Fprintf(&b, "; Max-Age=0")
} }
} }
} }
// the settings below // the settings below
// Path, Domain, Secure, HttpOnly // Path, Domain, Secure, HttpOnly
@ -188,9 +188,9 @@ func sanitizeValue(v string) string {
return cookieValueSanitizer.Replace(v) return cookieValueSanitizer.Replace(v)
} }
// Json writes json to response body. // JSON writes json to response body.
// if coding is true, it converts utf-8 to \u0000 type. // if coding is true, it converts utf-8 to \u0000 type.
func (output *BeegoOutput) Json(data interface{}, hasIndent bool, coding bool) error { func (output *BeegoOutput) JSON(data interface{}, hasIndent bool, coding bool) error {
output.Header("Content-Type", "application/json; charset=utf-8") output.Header("Content-Type", "application/json; charset=utf-8")
var content []byte var content []byte
var err error var err error
@ -204,14 +204,14 @@ func (output *BeegoOutput) Json(data interface{}, hasIndent bool, coding bool) e
return err return err
} }
if coding { if coding {
content = []byte(stringsToJson(string(content))) content = []byte(stringsToJSON(string(content)))
} }
output.Body(content) output.Body(content)
return nil return nil
} }
// Jsonp writes jsonp to response body. // JSONP writes jsonp to response body.
func (output *BeegoOutput) Jsonp(data interface{}, hasIndent bool) error { func (output *BeegoOutput) JSONP(data interface{}, hasIndent bool) error {
output.Header("Content-Type", "application/javascript; charset=utf-8") output.Header("Content-Type", "application/javascript; charset=utf-8")
var content []byte var content []byte
var err error var err error
@ -228,16 +228,16 @@ func (output *BeegoOutput) Jsonp(data interface{}, hasIndent bool) error {
if callback == "" { if callback == "" {
return errors.New(`"callback" parameter required`) return errors.New(`"callback" parameter required`)
} }
callback_content := bytes.NewBufferString(" " + template.JSEscapeString(callback)) callbackContent := bytes.NewBufferString(" " + template.JSEscapeString(callback))
callback_content.WriteString("(") callbackContent.WriteString("(")
callback_content.Write(content) callbackContent.Write(content)
callback_content.WriteString(");\r\n") callbackContent.WriteString(");\r\n")
output.Body(callback_content.Bytes()) output.Body(callbackContent.Bytes())
return nil return nil
} }
// Xml writes xml string to response body. // XML writes xml string to response body.
func (output *BeegoOutput) Xml(data interface{}, hasIndent bool) error { func (output *BeegoOutput) XML(data interface{}, hasIndent bool) error {
output.Header("Content-Type", "application/xml; charset=utf-8") output.Header("Content-Type", "application/xml; charset=utf-8")
var content []byte var content []byte
var err error var err error
@ -331,7 +331,7 @@ func (output *BeegoOutput) IsNotFound(status int) bool {
return output.Status == 404 return output.Status == 404
} }
// IsClient returns boolean of this request client sends error data. // IsClientError returns boolean of this request client sends error data.
// HTTP 4xx means forbidden. // HTTP 4xx means forbidden.
func (output *BeegoOutput) IsClientError(status int) bool { func (output *BeegoOutput) IsClientError(status int) bool {
return output.Status >= 400 && output.Status < 500 return output.Status >= 400 && output.Status < 500
@ -343,7 +343,7 @@ func (output *BeegoOutput) IsServerError(status int) bool {
return output.Status >= 500 && output.Status < 600 return output.Status >= 500 && output.Status < 600
} }
func stringsToJson(str string) string { func stringsToJSON(str string) string {
rs := []rune(str) rs := []rune(str)
jsons := "" jsons := ""
for _, r := range rs { for _, r := range rs {
@ -357,7 +357,7 @@ func stringsToJson(str string) string {
return jsons return jsons
} }
// Sessions sets session item value with given key. // Session sets session item value with given key.
func (output *BeegoOutput) Session(name interface{}, value interface{}) { func (output *BeegoOutput) Session(name interface{}, value interface{}) {
output.Context.Input.CruSession.Set(name, value) output.Context.Input.CruSession.Set(name, value)
} }

View File

@ -327,7 +327,7 @@ func (c *Controller) ServeJSON(encoding ...bool) {
if len(encoding) > 0 && encoding[0] == true { if len(encoding) > 0 && encoding[0] == true {
hasencoding = true hasencoding = true
} }
c.Ctx.Output.Json(c.Data["json"], hasIndent, hasencoding) c.Ctx.Output.JSON(c.Data["json"], hasIndent, hasencoding)
} }
// ServeJSONP sends a jsonp response. // ServeJSONP sends a jsonp response.
@ -338,7 +338,7 @@ func (c *Controller) ServeJSONP() {
} else { } else {
hasIndent = true hasIndent = true
} }
c.Ctx.Output.Jsonp(c.Data["jsonp"], hasIndent) c.Ctx.Output.JSONP(c.Data["jsonp"], hasIndent)
} }
// ServeXML sends xml response. // ServeXML sends xml response.
@ -349,7 +349,7 @@ func (c *Controller) ServeXML() {
} else { } else {
hasIndent = true hasIndent = true
} }
c.Ctx.Output.Xml(c.Data["xml"], hasIndent) c.Ctx.Output.XML(c.Data["xml"], hasIndent)
} }
// ServeFormatted serve Xml OR Json, depending on the value of the Accept header // ServeFormatted serve Xml OR Json, depending on the value of the Accept header
@ -630,7 +630,7 @@ func (c *Controller) XSRFToken() string {
} else { } else {
expire = int64(XSRFExpire) expire = int64(XSRFExpire)
} }
c._xsrfToken = c.Ctx.XsrfToken(XSRFKEY, expire) c._xsrfToken = c.Ctx.XSRFToken(XSRFKEY, expire)
} }
return c._xsrfToken return c._xsrfToken
} }
@ -642,7 +642,7 @@ func (c *Controller) CheckXSRFCookie() bool {
if !c.EnableXSRF { if !c.EnableXSRF {
return true return true
} }
return c.Ctx.CheckXsrfCookie() return c.Ctx.CheckXSRFCookie()
} }
// XSRFFormHTML writes an input field contains xsrf token value. // XSRFFormHTML writes an input field contains xsrf token value.

View File

@ -87,7 +87,7 @@ func showErr(err interface{}, ctx *context.Context, Stack string) {
data := make(map[string]string) data := make(map[string]string)
data["AppError"] = AppName + ":" + fmt.Sprint(err) data["AppError"] = AppName + ":" + fmt.Sprint(err)
data["RequestMethod"] = ctx.Input.Method() data["RequestMethod"] = ctx.Input.Method()
data["RequestURL"] = ctx.Input.Uri() data["RequestURL"] = ctx.Input.URI()
data["RemoteAddr"] = ctx.Input.IP() data["RemoteAddr"] = ctx.Input.IP()
data["Stack"] = Stack data["Stack"] = Stack
data["BeegoVersion"] = VERSION data["BeegoVersion"] = VERSION

View File

@ -875,7 +875,7 @@ func (p *ControllerRegister) recoverPanic(context *beecontext.Context) {
} }
} }
var stack string var stack string
Critical("the request url is ", context.Input.Url()) Critical("the request url is ", context.Input.URL())
Critical("Handler crashed with error", err) Critical("Handler crashed with error", err)
for i := 1; ; i++ { for i := 1; ; i++ {
_, file, line, ok := runtime.Caller(i) _, file, line, ok := runtime.Caller(i)