1
0
mirror of https://github.com/astaxie/beego.git synced 2024-09-28 18:11:51 +00:00

Merge pull request #1044 from fuxiaohei/develop

code style simplify
This commit is contained in:
astaxie 2015-02-23 22:25:34 +08:00
commit 71b9854f48
10 changed files with 76 additions and 80 deletions

View File

@ -155,8 +155,11 @@ func (ctx *Context) CheckXsrfCookie() bool {
} }
if token == "" { if token == "" {
ctx.Abort(403, "'_xsrf' argument missing from POST") ctx.Abort(403, "'_xsrf' argument missing from POST")
} else if ctx._xsrf_token != token { return false
}
if ctx._xsrf_token != token {
ctx.Abort(403, "XSRF cookie does not match POST argument") ctx.Abort(403, "XSRF cookie does not match POST argument")
return false
} }
return true return true
} }

View File

@ -72,11 +72,11 @@ func (input *BeegoInput) Site() string {
func (input *BeegoInput) Scheme() string { func (input *BeegoInput) Scheme() string {
if input.Request.URL.Scheme != "" { if input.Request.URL.Scheme != "" {
return input.Request.URL.Scheme return input.Request.URL.Scheme
} else if input.Request.TLS == nil {
return "http"
} else {
return "https"
} }
if input.Request.TLS == nil {
return "http"
}
return "https"
} }
// Domain returns host name. // Domain returns host name.

View File

@ -253,30 +253,20 @@ func (b *BeegoHttpRequest) Body(data interface{}) *BeegoHttpRequest {
return b return b
} }
func (b *BeegoHttpRequest) getResponse() (*http.Response, error) { func (b *BeegoHttpRequest) buildUrl(paramBody string) {
if b.resp.StatusCode != 0 { // build GET url with query string
return b.resp, nil
}
var paramBody string
if len(b.params) > 0 {
var buf bytes.Buffer
for k, v := range b.params {
buf.WriteString(url.QueryEscape(k))
buf.WriteByte('=')
buf.WriteString(url.QueryEscape(v))
buf.WriteByte('&')
}
paramBody = buf.String()
paramBody = paramBody[0 : len(paramBody)-1]
}
if b.req.Method == "GET" && len(paramBody) > 0 { if b.req.Method == "GET" && len(paramBody) > 0 {
if strings.Index(b.url, "?") != -1 { if strings.Index(b.url, "?") != -1 {
b.url += "&" + paramBody b.url += "&" + paramBody
} else { } else {
b.url = b.url + "?" + paramBody b.url = b.url + "?" + paramBody
} }
} else if b.req.Method == "POST" && b.req.Body == nil { return
}
// build POST url and body
if b.req.Method == "POST" && b.req.Body == nil {
// with files
if len(b.files) > 0 { if len(b.files) > 0 {
pr, pw := io.Pipe() pr, pw := io.Pipe()
bodyWriter := multipart.NewWriter(pw) bodyWriter := multipart.NewWriter(pw)
@ -305,12 +295,35 @@ func (b *BeegoHttpRequest) getResponse() (*http.Response, error) {
}() }()
b.Header("Content-Type", bodyWriter.FormDataContentType()) b.Header("Content-Type", bodyWriter.FormDataContentType())
b.req.Body = ioutil.NopCloser(pr) b.req.Body = ioutil.NopCloser(pr)
} else if len(paramBody) > 0 { return
}
// with params
if len(paramBody) > 0 {
b.Header("Content-Type", "application/x-www-form-urlencoded") b.Header("Content-Type", "application/x-www-form-urlencoded")
b.Body(paramBody) b.Body(paramBody)
} }
} }
}
func (b *BeegoHttpRequest) getResponse() (*http.Response, error) {
if b.resp.StatusCode != 0 {
return b.resp, nil
}
var paramBody string
if len(b.params) > 0 {
var buf bytes.Buffer
for k, v := range b.params {
buf.WriteString(url.QueryEscape(k))
buf.WriteByte('=')
buf.WriteString(url.QueryEscape(v))
buf.WriteByte('&')
}
paramBody = buf.String()
paramBody = paramBody[0 : len(paramBody)-1]
}
b.buildUrl(paramBody)
url, err := url.Parse(b.url) url, err := url.Parse(b.url)
if err != nil { if err != nil {
return nil, err return nil, err
@ -342,14 +355,12 @@ func (b *BeegoHttpRequest) getResponse() (*http.Response, error) {
} }
} }
var jar http.CookieJar var jar http.CookieJar = nil
if b.setting.EnableCookie { if b.setting.EnableCookie {
if defaultCookieJar == nil { if defaultCookieJar == nil {
createDefaultCookie() createDefaultCookie()
} }
jar = defaultCookieJar jar = defaultCookieJar
} else {
jar = nil
} }
client := &http.Client{ client := &http.Client{
@ -402,12 +413,11 @@ func (b *BeegoHttpRequest) Bytes() ([]byte, error) {
return nil, nil return nil, nil
} }
defer resp.Body.Close() defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body) b.body, err = ioutil.ReadAll(resp.Body)
if err != nil { if err != nil {
return nil, err return nil, err
} }
b.body = data return b.body, nil
return data, nil
} }
// ToFile saves the body data in response to one file. // ToFile saves the body data in response to one file.
@ -438,8 +448,7 @@ func (b *BeegoHttpRequest) ToJson(v interface{}) error {
if err != nil { if err != nil {
return err return err
} }
err = json.Unmarshal(data, v) return json.Unmarshal(data, v)
return err
} }
// ToXml returns the map that marshals from the body bytes as xml in response . // ToXml returns the map that marshals from the body bytes as xml in response .
@ -449,8 +458,7 @@ func (b *BeegoHttpRequest) ToXml(v interface{}) error {
if err != nil { if err != nil {
return err return err
} }
err = xml.Unmarshal(data, v) return xml.Unmarshal(data, v)
return err
} }
// Response executes request client gets response mannually. // Response executes request client gets response mannually.

View File

@ -43,11 +43,7 @@ func NewConn() LoggerInterface {
// init connection writer with json config. // init connection writer with json config.
// json config only need key "level". // json config only need key "level".
func (c *ConnWriter) Init(jsonconfig string) error { func (c *ConnWriter) Init(jsonconfig string) error {
err := json.Unmarshal([]byte(jsonconfig), c) return json.Unmarshal([]byte(jsonconfig), c)
if err != nil {
return err
}
return nil
} }
// write message in connection. // write message in connection.
@ -77,10 +73,9 @@ func (c *ConnWriter) Flush() {
// destroy connection writer and close tcp listener. // destroy connection writer and close tcp listener.
func (c *ConnWriter) Destroy() { func (c *ConnWriter) Destroy() {
if c.innerWriter == nil { if c.innerWriter != nil {
return c.innerWriter.Close()
} }
c.innerWriter.Close()
} }
func (c *ConnWriter) connect() error { func (c *ConnWriter) connect() error {

View File

@ -50,9 +50,10 @@ type ConsoleWriter struct {
// create ConsoleWriter returning as LoggerInterface. // create ConsoleWriter returning as LoggerInterface.
func NewConsole() LoggerInterface { func NewConsole() LoggerInterface {
cw := new(ConsoleWriter) cw := &ConsoleWriter{
cw.lg = log.New(os.Stdout, "", log.Ldate|log.Ltime) lg: log.New(os.Stdout, "", log.Ldate|log.Ltime),
cw.Level = LevelDebug Level: LevelDebug,
}
return cw return cw
} }
@ -62,11 +63,7 @@ func (c *ConsoleWriter) Init(jsonconfig string) error {
if len(jsonconfig) == 0 { if len(jsonconfig) == 0 {
return nil return nil
} }
err := json.Unmarshal([]byte(jsonconfig), c) return json.Unmarshal([]byte(jsonconfig), c)
if err != nil {
return err
}
return nil
} }
// write message in console. // write message in console.
@ -76,9 +73,10 @@ func (c *ConsoleWriter) WriteMsg(msg string, level int) error {
} }
if goos := runtime.GOOS; goos == "windows" { if goos := runtime.GOOS; goos == "windows" {
c.lg.Println(msg) c.lg.Println(msg)
} else { return nil
c.lg.Println(colors[level](msg))
} }
c.lg.Println(colors[level](msg))
return nil return nil
} }

View File

@ -123,11 +123,7 @@ func (w *FileLogWriter) startLogger() error {
return err return err
} }
w.mw.SetFd(fd) w.mw.SetFd(fd)
err = w.initFd() return w.initFd()
if err != nil {
return err
}
return nil
} }
func (w *FileLogWriter) docheck(size int) { func (w *FileLogWriter) docheck(size int) {
@ -170,14 +166,13 @@ func (w *FileLogWriter) initFd() error {
} }
w.maxsize_cursize = int(finfo.Size()) w.maxsize_cursize = int(finfo.Size())
w.daily_opendate = time.Now().Day() w.daily_opendate = time.Now().Day()
w.maxlines_curlines = 0
if finfo.Size() > 0 { if finfo.Size() > 0 {
count, err := w.lines() count, err := w.lines()
if err != nil { if err != nil {
return err return err
} }
w.maxlines_curlines = count w.maxlines_curlines = count
} else {
w.maxlines_curlines = 0
} }
return nil return nil
} }

View File

@ -292,9 +292,9 @@ func (bl *BeeLogger) Close() {
fmt.Println("ERROR, unable to WriteMsg (while closing logger):", err) fmt.Println("ERROR, unable to WriteMsg (while closing logger):", err)
} }
} }
} else { continue
break
} }
break
} }
for _, l := range bl.outputs { for _, l := range bl.outputs {
l.Flush() l.Flush()

View File

@ -25,7 +25,8 @@ import (
) )
const ( const (
subjectPhrase = "Diagnostic message from server" // no usage
// subjectPhrase = "Diagnostic message from server"
) )
// smtpWriter implements LoggerInterface and is used to send emails via given SMTP-server. // smtpWriter implements LoggerInterface and is used to send emails via given SMTP-server.
@ -146,9 +147,7 @@ func (s *SmtpWriter) WriteMsg(msg string, level int) error {
mailmsg := []byte("To: " + strings.Join(s.RecipientAddresses, ";") + "\r\nFrom: " + s.FromAddress + "<" + s.FromAddress + mailmsg := []byte("To: " + strings.Join(s.RecipientAddresses, ";") + "\r\nFrom: " + s.FromAddress + "<" + s.FromAddress +
">\r\nSubject: " + s.Subject + "\r\n" + content_type + "\r\n\r\n" + fmt.Sprintf(".%s", time.Now().Format("2006-01-02 15:04:05")) + msg) ">\r\nSubject: " + s.Subject + "\r\n" + content_type + "\r\n\r\n" + fmt.Sprintf(".%s", time.Now().Format("2006-01-02 15:04:05")) + msg)
err := s.sendMail(s.Host, auth, s.FromAddress, s.RecipientAddresses, mailmsg) return s.sendMail(s.Host, auth, s.FromAddress, s.RecipientAddresses, mailmsg)
return err
} }
// implementing method. empty. // implementing method. empty.

View File

@ -323,17 +323,15 @@ func Exception(errcode string, w http.ResponseWriter, r *http.Request, msg strin
w.WriteHeader(isint) w.WriteHeader(isint)
h(w, r) h(w, r)
return return
} else {
isint, err := strconv.Atoi(errcode)
if err != nil {
isint = 500
}
if isint == 404 {
msg = "404 page not found"
}
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(isint)
fmt.Fprintln(w, msg)
return
} }
isint, err := strconv.Atoi(errcode)
if err != nil {
isint = 500
}
if isint == 404 {
msg = "404 page not found"
}
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(isint)
fmt.Fprintln(w, msg)
} }

View File

@ -34,7 +34,6 @@ type Translation struct {
} }
func NewLocale(filepath string, defaultlocal string) *Translation { func NewLocale(filepath string, defaultlocal string) *Translation {
i18n := make(map[string]map[string]string)
file, err := os.Open(filepath) file, err := os.Open(filepath)
if err != nil { if err != nil {
panic("open " + filepath + " err :" + err.Error()) panic("open " + filepath + " err :" + err.Error())
@ -43,8 +42,9 @@ func NewLocale(filepath string, defaultlocal string) *Translation {
if err != nil { if err != nil {
panic("read " + filepath + " err :" + err.Error()) panic("read " + filepath + " err :" + err.Error())
} }
err = json.Unmarshal(data, &i18n)
if err != nil { i18n := make(map[string]map[string]string)
if err = json.Unmarshal(data, &i18n); err != nil {
panic("json.Unmarshal " + filepath + " err :" + err.Error()) panic("json.Unmarshal " + filepath + " err :" + err.Error())
} }
return &Translation{ return &Translation{