mirror of
https://github.com/astaxie/beego.git
synced 2025-07-11 09:31:01 +00:00
Compare commits
245 Commits
Author | SHA1 | Date | |
---|---|---|---|
f7f390dfec | |||
8f7246e17b | |||
c8f6e0f156 | |||
0207caab6f | |||
d629c1d3d0 | |||
817650aa33 | |||
ba1232dfaf | |||
64d4f6518b | |||
9f05db8475 | |||
b275d7c6f5 | |||
73770fbe22 | |||
fc11169ee3 | |||
b54589fa9d | |||
2af0c569a5 | |||
27b7a8f743 | |||
c143a6ec19 | |||
e619d83990 | |||
27b452cd95 | |||
b776e43962 | |||
cb89cd577d | |||
6b777f0c5e | |||
491238ce7d | |||
d9bb1a3592 | |||
9c6775c22c | |||
4d70b22f96 | |||
d943d16d52 | |||
bbb6f31f16 | |||
364cacf659 | |||
21586586ba | |||
e1d7bc8826 | |||
499ee09d4b | |||
970f0b460c | |||
9280683935 | |||
a58c8180e8 | |||
b9852df51c | |||
8e71d31dbe | |||
db06e954b5 | |||
3abd01799d | |||
ae37689314 | |||
40974365e6 | |||
edbaa080f1 | |||
d56491ab3a | |||
9fd7acf663 | |||
2dca48f26e | |||
4138fe0217 | |||
245762f7d9 | |||
18bdec951d | |||
9252301fa0 | |||
1053b63bbc | |||
3bd6caae0a | |||
d8734cf58d | |||
51161361db | |||
6da0cdb9e2 | |||
9f070c622b | |||
738e22e389 | |||
69fc22f0df | |||
4cd7177ece | |||
8e618192c2 | |||
3415a5b091 | |||
dfe055c47c | |||
74b22649c8 | |||
4255630564 | |||
7e3b5e5307 | |||
0222b8d693 | |||
23268b788a | |||
ee4fd60e4d | |||
4414659df4 | |||
68ccd8e5a4 | |||
6f802b0a05 | |||
743628a946 | |||
d90ce15707 | |||
23457ed2a0 | |||
d7791ba837 | |||
676595213f | |||
d446b5b011 | |||
2ba12ad1e1 | |||
8cc57e2fc8 | |||
322b208566 | |||
fd610d6777 | |||
1148359570 | |||
55b1d6a897 | |||
c4c9a50c42 | |||
a311d712a5 | |||
bb5351bb9f | |||
26130a5df6 | |||
2c9363d29b | |||
91886a4547 | |||
a7e60c93dc | |||
5b1705b2d6 | |||
34940d00c0 | |||
1a6ea693b5 | |||
2e51c124f1 | |||
1d8afdc9c9 | |||
1592e9c04d | |||
bf6b0d3e1f | |||
af71289c25 | |||
b1efae6ff8 | |||
92f3de4027 | |||
185089299c | |||
59c1e74e13 | |||
9bb9855153 | |||
519602a553 | |||
740a526105 | |||
98289cd8de | |||
56e2143630 | |||
c0cfb5277c | |||
b29700c3c3 | |||
47be2fadb5 | |||
1d72629334 | |||
b4880c5e1d | |||
c0bb5b9237 | |||
1e1068e81c | |||
6c3e274b6e | |||
f56bdb6284 | |||
d8fa118727 | |||
0afd04ec6f | |||
973306b28d | |||
da8c3c3910 | |||
0c1bb6409a | |||
cddb4fdb60 | |||
e1d20aea5d | |||
4498a02c15 | |||
5534258e22 | |||
73650e1f2b | |||
d0e7dd686b | |||
dc58ec8316 | |||
6d72fc63ab | |||
dd4afac5dc | |||
e229a4762f | |||
ecb27f34e6 | |||
d55997e520 | |||
44c8534477 | |||
44a39a6b3e | |||
cc5ca458ab | |||
6f6b412709 | |||
642a69de02 | |||
466f3c49c1 | |||
d1c9cb2281 | |||
9c9ffa202a | |||
56dfe418dd | |||
7caeb91f9b | |||
47848fa77b | |||
e0e8b98622 | |||
5c84ada389 | |||
ac6203b81b | |||
5e1e618d0f | |||
a5124a1d45 | |||
e675594e46 | |||
d02e32fa51 | |||
8a82e25e85 | |||
49c0f8906f | |||
9261c80509 | |||
217e24815b | |||
840fd3b64f | |||
eedaea2fea | |||
a002f78443 | |||
cdf9ff401f | |||
caa260f053 | |||
5fa55ca2d3 | |||
260b5b1951 | |||
54ae4bc25b | |||
162bee1b43 | |||
533b00ae56 | |||
d3cdebbee2 | |||
06b5c7f644 | |||
185ee872c4 | |||
74e0af4a9a | |||
8aa9455900 | |||
2d26f7df2f | |||
3d6408cfc2 | |||
223f57bb4c | |||
c4aa33fb1b | |||
20cc5b261e | |||
7ec2a077d9 | |||
9f70561f21 | |||
1c9898dee5 | |||
2cf7c6a58a | |||
2cee46ab2b | |||
020bfbcc9c | |||
3f8252bffd | |||
6d313aa15f | |||
2a4e2d4a71 | |||
f96a6285bf | |||
e938876c4a | |||
6e9d2dc965 | |||
3aceaf8838 | |||
71b9854f48 | |||
f59ccd3a35 | |||
181a7c35fe | |||
2ed272aeb2 | |||
77c1109134 | |||
29d4823866 | |||
24cf06d288 | |||
0c31c2d689 | |||
f988f035e5 | |||
1b4158c15b | |||
433e8f2ce3 | |||
22ba7fdce4 | |||
2a0f87e810 | |||
19db4b67f6 | |||
b1baf4503d | |||
d536f5b8dc | |||
1cc1d57f55 | |||
73370ade90 | |||
0d3b7dcd07 | |||
d7fe5ef435 | |||
8bd902814f | |||
378356a65e | |||
30871e2617 | |||
3731088b4a | |||
d46833c6d8 | |||
18659e16ba | |||
5d8187d005 | |||
d961ae4cd8 | |||
0e1a0049d1 | |||
0c933643e2 | |||
d2c5daa5ee | |||
d3ab157915 | |||
75d28d49c5 | |||
76bb4827d0 | |||
3caba06189 | |||
572508ddd8 | |||
e34f8479bb | |||
daf85f06f8 | |||
22671c524e | |||
ab99d5f1e2 | |||
c52f634d9c | |||
9c665afc04 | |||
77ed151243 | |||
29d98731c6 | |||
934dd2e8d2 | |||
e65d87974a | |||
db04c3cbb4 | |||
802aa16136 | |||
f2df07f630 | |||
dc89f844f3 | |||
b80cdef20f | |||
98dcee0643 | |||
0ad75cb5fa | |||
6a9d04c269 | |||
93ca11f83d | |||
d0b43ef4f5 | |||
c9bb9d6a09 | |||
f96245786a | |||
1a1b0c14b9 |
@ -3,7 +3,7 @@
|
||||
[](https://drone.io/github.com/astaxie/beego/latest)
|
||||
[](http://godoc.org/github.com/astaxie/beego)
|
||||
|
||||
beego is an open-source, high-performance, modularity, full-stack web framework.
|
||||
beego is an open-source, high-performance, modular, full-stack web framework.
|
||||
|
||||
More info [beego.me](http://beego.me)
|
||||
|
||||
@ -19,7 +19,7 @@ More info [beego.me](http://beego.me)
|
||||
* Auto API documents
|
||||
* Annotation router
|
||||
* Namespace
|
||||
* Powerful develop tools
|
||||
* Powerful development tools
|
||||
* Full stack for Web & API
|
||||
|
||||
## Documentation
|
||||
|
19
admin.go
19
admin.go
@ -19,9 +19,11 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"text/template"
|
||||
"time"
|
||||
|
||||
"github.com/astaxie/beego/grace"
|
||||
"github.com/astaxie/beego/toolbox"
|
||||
"github.com/astaxie/beego/utils"
|
||||
)
|
||||
@ -333,7 +335,6 @@ func profIndex(rw http.ResponseWriter, r *http.Request) {
|
||||
tmpl = template.Must(tmpl.Parse(defaultScriptsTpl))
|
||||
}
|
||||
tmpl.Execute(rw, data)
|
||||
} else {
|
||||
}
|
||||
}
|
||||
|
||||
@ -397,7 +398,7 @@ func taskStatus(rw http.ResponseWriter, req *http.Request) {
|
||||
if err != nil {
|
||||
data["Message"] = []string{"error", fmt.Sprintf("%s", err)}
|
||||
}
|
||||
data["Message"] = []string{"success", fmt.Sprintf("%s run success,Now the Status is %s", taskname, t.GetStatus())}
|
||||
data["Message"] = []string{"success", fmt.Sprintf("%s run success,Now the Status is <br>%s", taskname, t.GetStatus())}
|
||||
} else {
|
||||
data["Message"] = []string{"warning", fmt.Sprintf("there's no task which named: %s", taskname)}
|
||||
}
|
||||
@ -410,12 +411,14 @@ func taskStatus(rw http.ResponseWriter, req *http.Request) {
|
||||
var fields = []string{
|
||||
fmt.Sprintf("Task Name"),
|
||||
fmt.Sprintf("Task Spec"),
|
||||
fmt.Sprintf("Task Function"),
|
||||
fmt.Sprintf("Task Status"),
|
||||
fmt.Sprintf("Last Time"),
|
||||
fmt.Sprintf(""),
|
||||
}
|
||||
for tname, tk := range toolbox.AdminTaskList {
|
||||
result = []string{
|
||||
fmt.Sprintf("%s", tname),
|
||||
fmt.Sprintf("%s", tk.GetSpec()),
|
||||
fmt.Sprintf("%s", tk.GetStatus()),
|
||||
fmt.Sprintf("%s", tk.GetPrev().String()),
|
||||
}
|
||||
@ -457,8 +460,14 @@ func (admin *adminApp) Run() {
|
||||
http.Handle(p, f)
|
||||
}
|
||||
BeeLogger.Info("Admin server Running on %s", addr)
|
||||
err := http.ListenAndServe(addr, nil)
|
||||
|
||||
var err error
|
||||
if Graceful {
|
||||
err = grace.ListenAndServe(addr, nil)
|
||||
} else {
|
||||
err = http.ListenAndServe(addr, nil)
|
||||
}
|
||||
if err != nil {
|
||||
BeeLogger.Critical("Admin ListenAndServe: ", err)
|
||||
BeeLogger.Critical("Admin ListenAndServe: ", err, fmt.Sprintf("%d", os.Getpid()))
|
||||
}
|
||||
}
|
||||
|
@ -186,7 +186,7 @@ bg-warning
|
||||
</td>
|
||||
{{end}}
|
||||
<td>
|
||||
<a class="btn btn-primary btn-sm" href="/task?taskname={{index $slice 1}}">Run</a>
|
||||
<a class="btn btn-primary btn-sm" href="/task?taskname={{index $slice 0}}">Run</a>
|
||||
</td>
|
||||
</tr>
|
||||
{{end}}
|
||||
|
143
app.go
143
app.go
@ -19,7 +19,11 @@ import (
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/fcgi"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/astaxie/beego/grace"
|
||||
"github.com/astaxie/beego/utils"
|
||||
)
|
||||
|
||||
// App defines beego application with a new PatternServeMux.
|
||||
@ -59,6 +63,10 @@ func (app *App) Run() {
|
||||
}
|
||||
} else {
|
||||
if HttpPort == 0 {
|
||||
// remove the Socket file before start
|
||||
if utils.FileExists(addr) {
|
||||
os.Remove(addr)
|
||||
}
|
||||
l, err = net.Listen("unix", addr)
|
||||
} else {
|
||||
l, err = net.Listen("tcp", addr)
|
||||
@ -69,57 +77,96 @@ func (app *App) Run() {
|
||||
err = fcgi.Serve(l, app.Handlers)
|
||||
}
|
||||
} else {
|
||||
app.Server.Addr = addr
|
||||
app.Server.Handler = app.Handlers
|
||||
app.Server.ReadTimeout = time.Duration(HttpServerTimeOut) * time.Second
|
||||
app.Server.WriteTimeout = time.Duration(HttpServerTimeOut) * time.Second
|
||||
if Graceful {
|
||||
app.Server.Addr = addr
|
||||
app.Server.Handler = app.Handlers
|
||||
app.Server.ReadTimeout = time.Duration(HttpServerTimeOut) * time.Second
|
||||
app.Server.WriteTimeout = time.Duration(HttpServerTimeOut) * time.Second
|
||||
if EnableHttpTLS {
|
||||
go func() {
|
||||
time.Sleep(20 * time.Microsecond)
|
||||
if HttpsPort != 0 {
|
||||
addr = fmt.Sprintf("%s:%d", HttpAddr, HttpsPort)
|
||||
app.Server.Addr = addr
|
||||
}
|
||||
server := grace.NewServer(addr, app.Handlers)
|
||||
server.Server = app.Server
|
||||
err := server.ListenAndServeTLS(HttpCertFile, HttpKeyFile)
|
||||
if err != nil {
|
||||
BeeLogger.Critical("ListenAndServeTLS: ", err, fmt.Sprintf("%d", os.Getpid()))
|
||||
time.Sleep(100 * time.Microsecond)
|
||||
endRunning <- true
|
||||
}
|
||||
}()
|
||||
}
|
||||
if EnableHttpListen {
|
||||
go func() {
|
||||
server := grace.NewServer(addr, app.Handlers)
|
||||
server.Server = app.Server
|
||||
if ListenTCP4 && HttpAddr == "" {
|
||||
server.Network = "tcp4"
|
||||
}
|
||||
err := server.ListenAndServe()
|
||||
if err != nil {
|
||||
BeeLogger.Critical("ListenAndServe: ", err, fmt.Sprintf("%d", os.Getpid()))
|
||||
time.Sleep(100 * time.Microsecond)
|
||||
endRunning <- true
|
||||
}
|
||||
}()
|
||||
}
|
||||
} else {
|
||||
app.Server.Addr = addr
|
||||
app.Server.Handler = app.Handlers
|
||||
app.Server.ReadTimeout = time.Duration(HttpServerTimeOut) * time.Second
|
||||
app.Server.WriteTimeout = time.Duration(HttpServerTimeOut) * time.Second
|
||||
|
||||
if EnableHttpTLS {
|
||||
go func() {
|
||||
time.Sleep(20 * time.Microsecond)
|
||||
if HttpsPort != 0 {
|
||||
app.Server.Addr = fmt.Sprintf("%s:%d", HttpAddr, HttpsPort)
|
||||
}
|
||||
BeeLogger.Info("https server Running on %s", app.Server.Addr)
|
||||
err := app.Server.ListenAndServeTLS(HttpCertFile, HttpKeyFile)
|
||||
if err != nil {
|
||||
BeeLogger.Critical("ListenAndServeTLS: ", err)
|
||||
time.Sleep(100 * time.Microsecond)
|
||||
endRunning <- true
|
||||
}
|
||||
}()
|
||||
if EnableHttpTLS {
|
||||
go func() {
|
||||
time.Sleep(20 * time.Microsecond)
|
||||
if HttpsPort != 0 {
|
||||
app.Server.Addr = fmt.Sprintf("%s:%d", HttpAddr, HttpsPort)
|
||||
}
|
||||
BeeLogger.Info("https server Running on %s", app.Server.Addr)
|
||||
err := app.Server.ListenAndServeTLS(HttpCertFile, HttpKeyFile)
|
||||
if err != nil {
|
||||
BeeLogger.Critical("ListenAndServeTLS: ", err)
|
||||
time.Sleep(100 * time.Microsecond)
|
||||
endRunning <- true
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
if EnableHttpListen {
|
||||
go func() {
|
||||
app.Server.Addr = addr
|
||||
BeeLogger.Info("http server Running on %s", app.Server.Addr)
|
||||
if ListenTCP4 && HttpAddr == "" {
|
||||
ln, err := net.Listen("tcp4", app.Server.Addr)
|
||||
if err != nil {
|
||||
BeeLogger.Critical("ListenAndServe: ", err)
|
||||
time.Sleep(100 * time.Microsecond)
|
||||
endRunning <- true
|
||||
return
|
||||
}
|
||||
err = app.Server.Serve(ln)
|
||||
if err != nil {
|
||||
BeeLogger.Critical("ListenAndServe: ", err)
|
||||
time.Sleep(100 * time.Microsecond)
|
||||
endRunning <- true
|
||||
return
|
||||
}
|
||||
} else {
|
||||
err := app.Server.ListenAndServe()
|
||||
if err != nil {
|
||||
BeeLogger.Critical("ListenAndServe: ", err)
|
||||
time.Sleep(100 * time.Microsecond)
|
||||
endRunning <- true
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
if EnableHttpListen {
|
||||
go func() {
|
||||
app.Server.Addr = addr
|
||||
BeeLogger.Info("http server Running on %s", app.Server.Addr)
|
||||
if ListenTCP4 && HttpAddr == "" {
|
||||
ln, err := net.Listen("tcp4", app.Server.Addr)
|
||||
if err != nil {
|
||||
BeeLogger.Critical("ListenAndServe: ", err)
|
||||
time.Sleep(100 * time.Microsecond)
|
||||
endRunning <- true
|
||||
return
|
||||
}
|
||||
err = app.Server.Serve(ln)
|
||||
if err != nil {
|
||||
BeeLogger.Critical("ListenAndServe: ", err)
|
||||
time.Sleep(100 * time.Microsecond)
|
||||
endRunning <- true
|
||||
return
|
||||
}
|
||||
} else {
|
||||
err := app.Server.ListenAndServe()
|
||||
if err != nil {
|
||||
BeeLogger.Critical("ListenAndServe: ", err)
|
||||
time.Sleep(100 * time.Microsecond)
|
||||
endRunning <- true
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
<-endRunning
|
||||
}
|
||||
|
85
beego.go
85
beego.go
@ -33,83 +33,15 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/astaxie/beego/middleware"
|
||||
"github.com/astaxie/beego/session"
|
||||
)
|
||||
|
||||
// beego web framework version.
|
||||
const VERSION = "1.4.2"
|
||||
const VERSION = "1.5.0"
|
||||
|
||||
type hookfunc func() error //hook function to run
|
||||
var hooks []hookfunc //hook function slice to store the hookfunc
|
||||
|
||||
type groupRouter struct {
|
||||
pattern string
|
||||
controller ControllerInterface
|
||||
mappingMethods string
|
||||
}
|
||||
|
||||
// RouterGroups which will store routers
|
||||
type GroupRouters []groupRouter
|
||||
|
||||
// Get a new GroupRouters
|
||||
func NewGroupRouters() GroupRouters {
|
||||
return make(GroupRouters, 0)
|
||||
}
|
||||
|
||||
// Add Router in the GroupRouters
|
||||
// it is for plugin or module to register router
|
||||
func (gr *GroupRouters) AddRouter(pattern string, c ControllerInterface, mappingMethod ...string) {
|
||||
var newRG groupRouter
|
||||
if len(mappingMethod) > 0 {
|
||||
newRG = groupRouter{
|
||||
pattern,
|
||||
c,
|
||||
mappingMethod[0],
|
||||
}
|
||||
} else {
|
||||
newRG = groupRouter{
|
||||
pattern,
|
||||
c,
|
||||
"",
|
||||
}
|
||||
}
|
||||
*gr = append(*gr, newRG)
|
||||
}
|
||||
|
||||
func (gr *GroupRouters) AddAuto(c ControllerInterface) {
|
||||
newRG := groupRouter{
|
||||
"",
|
||||
c,
|
||||
"",
|
||||
}
|
||||
*gr = append(*gr, newRG)
|
||||
}
|
||||
|
||||
// AddGroupRouter with the prefix
|
||||
// it will register the router in BeeApp
|
||||
// the follow code is write in modules:
|
||||
// GR:=NewGroupRouters()
|
||||
// GR.AddRouter("/login",&UserController,"get:Login")
|
||||
// GR.AddRouter("/logout",&UserController,"get:Logout")
|
||||
// GR.AddRouter("/register",&UserController,"get:Reg")
|
||||
// the follow code is write in app:
|
||||
// import "github.com/beego/modules/auth"
|
||||
// AddRouterGroup("/admin", auth.GR)
|
||||
func AddGroupRouter(prefix string, groups GroupRouters) *App {
|
||||
for _, v := range groups {
|
||||
if v.pattern == "" {
|
||||
BeeApp.Handlers.AddAutoPrefix(prefix, v.controller)
|
||||
} else if v.mappingMethods != "" {
|
||||
BeeApp.Handlers.Add(prefix+v.pattern, v.controller, v.mappingMethods)
|
||||
} else {
|
||||
BeeApp.Handlers.Add(prefix+v.pattern, v.controller)
|
||||
}
|
||||
|
||||
}
|
||||
return BeeApp
|
||||
}
|
||||
|
||||
// Router adds a patterned controller handler to BeeApp.
|
||||
// it's an alias method of App.Router.
|
||||
// usage:
|
||||
@ -280,15 +212,6 @@ func Handler(rootpath string, h http.Handler, options ...interface{}) *App {
|
||||
return BeeApp
|
||||
}
|
||||
|
||||
// ErrorHandler registers http.HandlerFunc to each http err code string.
|
||||
// usage:
|
||||
// beego.ErrorHandler("404",NotFound)
|
||||
// beego.ErrorHandler("500",InternalServerError)
|
||||
func Errorhandler(err string, h http.HandlerFunc) *App {
|
||||
middleware.Errorhandler(err, h)
|
||||
return BeeApp
|
||||
}
|
||||
|
||||
// SetViewsPath sets view directory path in beego application.
|
||||
func SetViewsPath(path string) *App {
|
||||
ViewsPath = path
|
||||
@ -402,9 +325,7 @@ func initBeforeHttpRun() {
|
||||
}
|
||||
}
|
||||
|
||||
middleware.VERSION = VERSION
|
||||
middleware.AppName = AppName
|
||||
middleware.RegisterErrorHandler()
|
||||
registerDefaultErrorHandler()
|
||||
|
||||
if EnableDocs {
|
||||
Get("/docs", serverDocs)
|
||||
@ -415,7 +336,7 @@ func initBeforeHttpRun() {
|
||||
// this function is for test package init
|
||||
func TestBeegoInit(apppath string) {
|
||||
AppPath = apppath
|
||||
RunMode = "test"
|
||||
os.Setenv("BEEGO_RUNMODE", "test")
|
||||
AppConfigPath = filepath.Join(AppPath, "conf", "app.conf")
|
||||
err := ParseConfig()
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
|
2
cache/cache.go
vendored
2
cache/cache.go
vendored
@ -47,6 +47,8 @@ import (
|
||||
type Cache interface {
|
||||
// get cached value by key.
|
||||
Get(key string) interface{}
|
||||
// GetMulti is a batch version of Get.
|
||||
GetMulti(keys []string) []interface{}
|
||||
// set cached value with key and expire time.
|
||||
Put(key string, val interface{}, timeout int64) error
|
||||
// delete cached value by key.
|
||||
|
55
cache/cache_test.go
vendored
55
cache/cache_test.go
vendored
@ -15,6 +15,7 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
@ -64,10 +65,39 @@ func TestCache(t *testing.T) {
|
||||
if bm.IsExist("astaxie") {
|
||||
t.Error("delete err")
|
||||
}
|
||||
|
||||
//test GetMulti
|
||||
if err = bm.Put("astaxie", "author", 10); err != nil {
|
||||
t.Error("set Error", err)
|
||||
}
|
||||
if !bm.IsExist("astaxie") {
|
||||
t.Error("check err")
|
||||
}
|
||||
if v := bm.Get("astaxie"); v.(string) != "author" {
|
||||
t.Error("get err")
|
||||
}
|
||||
|
||||
if err = bm.Put("astaxie1", "author1", 10); err != nil {
|
||||
t.Error("set Error", err)
|
||||
}
|
||||
if !bm.IsExist("astaxie1") {
|
||||
t.Error("check err")
|
||||
}
|
||||
|
||||
vv := bm.GetMulti([]string{"astaxie", "astaxie1"})
|
||||
if len(vv) != 2 {
|
||||
t.Error("GetMulti ERROR")
|
||||
}
|
||||
if vv[0].(string) != "author" {
|
||||
t.Error("GetMulti ERROR")
|
||||
}
|
||||
if vv[1].(string) != "author1" {
|
||||
t.Error("GetMulti ERROR")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileCache(t *testing.T) {
|
||||
bm, err := NewCache("file", `{"CachePath":"/cache","FileSuffix":".bin","DirectoryLevel":2,"EmbedExpiry":0}`)
|
||||
bm, err := NewCache("file", `{"CachePath":"cache","FileSuffix":".bin","DirectoryLevel":2,"EmbedExpiry":0}`)
|
||||
if err != nil {
|
||||
t.Error("init err")
|
||||
}
|
||||
@ -101,6 +131,7 @@ func TestFileCache(t *testing.T) {
|
||||
if bm.IsExist("astaxie") {
|
||||
t.Error("delete err")
|
||||
}
|
||||
|
||||
//test string
|
||||
if err = bm.Put("astaxie", "author", 10); err != nil {
|
||||
t.Error("set Error", err)
|
||||
@ -108,8 +139,28 @@ func TestFileCache(t *testing.T) {
|
||||
if !bm.IsExist("astaxie") {
|
||||
t.Error("check err")
|
||||
}
|
||||
|
||||
if v := bm.Get("astaxie"); v.(string) != "author" {
|
||||
t.Error("get err")
|
||||
}
|
||||
|
||||
//test GetMulti
|
||||
if err = bm.Put("astaxie1", "author1", 10); err != nil {
|
||||
t.Error("set Error", err)
|
||||
}
|
||||
if !bm.IsExist("astaxie1") {
|
||||
t.Error("check err")
|
||||
}
|
||||
|
||||
vv := bm.GetMulti([]string{"astaxie", "astaxie1"})
|
||||
if len(vv) != 2 {
|
||||
t.Error("GetMulti ERROR")
|
||||
}
|
||||
if vv[0].(string) != "author" {
|
||||
t.Error("GetMulti ERROR")
|
||||
}
|
||||
if vv[1].(string) != "author1" {
|
||||
t.Error("GetMulti ERROR")
|
||||
}
|
||||
|
||||
os.RemoveAll("cache")
|
||||
}
|
||||
|
12
cache/file.go
vendored
12
cache/file.go
vendored
@ -92,8 +92,6 @@ func (fc *FileCache) StartAndGC(config string) error {
|
||||
|
||||
// Init will make new dir for file cache if not exist.
|
||||
func (fc *FileCache) Init() {
|
||||
app := filepath.Dir(os.Args[0])
|
||||
fc.CachePath = filepath.Join(app, fc.CachePath)
|
||||
if ok, _ := exists(fc.CachePath); !ok { // todo : error handle
|
||||
_ = os.MkdirAll(fc.CachePath, os.ModePerm) // todo : error handle
|
||||
}
|
||||
@ -134,6 +132,16 @@ func (fc *FileCache) Get(key string) interface{} {
|
||||
return to.Data
|
||||
}
|
||||
|
||||
// GetMulti gets values from file cache.
|
||||
// if non-exist or expired, return empty string.
|
||||
func (fc *FileCache) GetMulti(keys []string) []interface{} {
|
||||
var rc []interface{}
|
||||
for _, key := range keys {
|
||||
rc = append(rc, fc.Get(key))
|
||||
}
|
||||
return rc
|
||||
}
|
||||
|
||||
// Put value into file cache.
|
||||
// timeout means how long to keep this file, unit of ms.
|
||||
// if timeout equals FileCacheEmbedExpiry(default is 0), cache this item forever.
|
||||
|
26
cache/memcache/memcache.go
vendored
26
cache/memcache/memcache.go
vendored
@ -63,6 +63,32 @@ func (rc *MemcacheCache) Get(key string) interface{} {
|
||||
return nil
|
||||
}
|
||||
|
||||
// get value from memcache.
|
||||
func (rc *MemcacheCache) GetMulti(keys []string) []interface{} {
|
||||
size := len(keys)
|
||||
var rv []interface{}
|
||||
if rc.conn == nil {
|
||||
if err := rc.connectInit(); err != nil {
|
||||
for i := 0; i < size; i++ {
|
||||
rv = append(rv, err)
|
||||
}
|
||||
return rv
|
||||
}
|
||||
}
|
||||
mv, err := rc.conn.GetMulti(keys)
|
||||
if err == nil {
|
||||
for _, v := range mv {
|
||||
rv = append(rv, string(v.Value))
|
||||
}
|
||||
return rv
|
||||
} else {
|
||||
for i := 0; i < size; i++ {
|
||||
rv = append(rv, err)
|
||||
}
|
||||
return rv
|
||||
}
|
||||
}
|
||||
|
||||
// put value to memcache. only support string.
|
||||
func (rc *MemcacheCache) Put(key string, val interface{}, timeout int64) error {
|
||||
if rc.conn == nil {
|
||||
|
106
cache/memcache/memcache_test.go
vendored
Normal file
106
cache/memcache/memcache_test.go
vendored
Normal file
@ -0,0 +1,106 @@
|
||||
// Copyright 2014 beego Author. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package memcache
|
||||
|
||||
import (
|
||||
_ "github.com/bradfitz/gomemcache/memcache"
|
||||
|
||||
"github.com/astaxie/beego/cache"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRedisCache(t *testing.T) {
|
||||
bm, err := cache.NewCache("memcache", `{"conn": "127.0.0.1:11211"}`)
|
||||
if err != nil {
|
||||
t.Error("init err")
|
||||
}
|
||||
if err = bm.Put("astaxie", "1", 10); err != nil {
|
||||
t.Error("set Error", err)
|
||||
}
|
||||
if !bm.IsExist("astaxie") {
|
||||
t.Error("check err")
|
||||
}
|
||||
|
||||
time.Sleep(10 * time.Second)
|
||||
|
||||
if bm.IsExist("astaxie") {
|
||||
t.Error("check err")
|
||||
}
|
||||
if err = bm.Put("astaxie", "1", 10); err != nil {
|
||||
t.Error("set Error", err)
|
||||
}
|
||||
|
||||
if v, err := strconv.Atoi(bm.Get("astaxie").(string)); err != nil || v != 1 {
|
||||
t.Error("get err")
|
||||
}
|
||||
|
||||
if err = bm.Incr("astaxie"); err != nil {
|
||||
t.Error("Incr Error", err)
|
||||
}
|
||||
|
||||
if v, err := strconv.Atoi(bm.Get("astaxie").(string)); err != nil || v != 2 {
|
||||
t.Error("get err")
|
||||
}
|
||||
|
||||
if err = bm.Decr("astaxie"); err != nil {
|
||||
t.Error("Decr Error", err)
|
||||
}
|
||||
|
||||
if v, err := strconv.Atoi(bm.Get("astaxie").(string)); err != nil || v != 1 {
|
||||
t.Error("get err")
|
||||
}
|
||||
bm.Delete("astaxie")
|
||||
if bm.IsExist("astaxie") {
|
||||
t.Error("delete err")
|
||||
}
|
||||
|
||||
//test string
|
||||
if err = bm.Put("astaxie", "author", 10); err != nil {
|
||||
t.Error("set Error", err)
|
||||
}
|
||||
if !bm.IsExist("astaxie") {
|
||||
t.Error("check err")
|
||||
}
|
||||
|
||||
if v := bm.Get("astaxie").(string); v != "author" {
|
||||
t.Error("get err")
|
||||
}
|
||||
|
||||
//test GetMulti
|
||||
if err = bm.Put("astaxie1", "author1", 10); err != nil {
|
||||
t.Error("set Error", err)
|
||||
}
|
||||
if !bm.IsExist("astaxie1") {
|
||||
t.Error("check err")
|
||||
}
|
||||
|
||||
vv := bm.GetMulti([]string{"astaxie", "astaxie1"})
|
||||
if len(vv) != 2 {
|
||||
t.Error("GetMulti ERROR")
|
||||
}
|
||||
if vv[0].(string) != "author" {
|
||||
t.Error("GetMulti ERROR")
|
||||
}
|
||||
if vv[1].(string) != "author1" {
|
||||
t.Error("GetMulti ERROR")
|
||||
}
|
||||
|
||||
// test clear all
|
||||
if err = bm.ClearAll(); err != nil {
|
||||
t.Error("clear all err")
|
||||
}
|
||||
}
|
12
cache/memory.go
vendored
12
cache/memory.go
vendored
@ -64,6 +64,16 @@ func (bc *MemoryCache) Get(name string) interface{} {
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetMulti gets caches from memory.
|
||||
// if non-existed or expired, return nil.
|
||||
func (bc *MemoryCache) GetMulti(names []string) []interface{} {
|
||||
var rc []interface{}
|
||||
for _, name := range names {
|
||||
rc = append(rc, bc.Get(name))
|
||||
}
|
||||
return rc
|
||||
}
|
||||
|
||||
// Put cache to memory.
|
||||
// if expired is 0, it will be cleaned by next gc operation ( default gc clock is 1 minute).
|
||||
func (bc *MemoryCache) Put(name string, value interface{}, expired int64) error {
|
||||
@ -202,7 +212,7 @@ func (bc *MemoryCache) vaccuum() {
|
||||
if bc.items == nil {
|
||||
return
|
||||
}
|
||||
for name, _ := range bc.items {
|
||||
for name := range bc.items {
|
||||
bc.item_expired(name)
|
||||
}
|
||||
}
|
||||
|
65
cache/redis/redis.go
vendored
65
cache/redis/redis.go
vendored
@ -32,6 +32,7 @@ package redis
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/garyburd/redigo/redis"
|
||||
@ -48,7 +49,9 @@ var (
|
||||
type RedisCache struct {
|
||||
p *redis.Pool // redis connection pool
|
||||
conninfo string
|
||||
dbNum int
|
||||
key string
|
||||
password string
|
||||
}
|
||||
|
||||
// create new redis cache with default collection name.
|
||||
@ -72,6 +75,39 @@ func (rc *RedisCache) Get(key string) interface{} {
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetMulti get cache from redis.
|
||||
func (rc *RedisCache) GetMulti(keys []string) []interface{} {
|
||||
size := len(keys)
|
||||
var rv []interface{}
|
||||
c := rc.p.Get()
|
||||
defer c.Close()
|
||||
var err error
|
||||
for _, key := range keys {
|
||||
err = c.Send("GET", key)
|
||||
if err != nil {
|
||||
goto ERROR
|
||||
}
|
||||
}
|
||||
if err = c.Flush(); err != nil {
|
||||
goto ERROR
|
||||
}
|
||||
for i := 0; i < size; i++ {
|
||||
if v, err := c.Receive(); err == nil {
|
||||
rv = append(rv, v.([]byte))
|
||||
} else {
|
||||
rv = append(rv, err)
|
||||
}
|
||||
}
|
||||
return rv
|
||||
ERROR:
|
||||
rv = rv[0:0]
|
||||
for i := 0; i < size; i++ {
|
||||
rv = append(rv, nil)
|
||||
}
|
||||
|
||||
return rv
|
||||
}
|
||||
|
||||
// put cache to redis.
|
||||
func (rc *RedisCache) Put(key string, val interface{}, timeout int64) error {
|
||||
var err error
|
||||
@ -137,7 +173,7 @@ func (rc *RedisCache) ClearAll() error {
|
||||
}
|
||||
|
||||
// start redis cache adapter.
|
||||
// config is like {"key":"collection key","conn":"connection info"}
|
||||
// config is like {"key":"collection key","conn":"connection info","dbNum":"0"}
|
||||
// the cache item in redis are stored forever,
|
||||
// so no gc operation.
|
||||
func (rc *RedisCache) StartAndGC(config string) error {
|
||||
@ -147,13 +183,20 @@ func (rc *RedisCache) StartAndGC(config string) error {
|
||||
if _, ok := cf["key"]; !ok {
|
||||
cf["key"] = DefaultKey
|
||||
}
|
||||
|
||||
if _, ok := cf["conn"]; !ok {
|
||||
return errors.New("config has no conn key")
|
||||
}
|
||||
|
||||
if _, ok := cf["dbNum"]; !ok {
|
||||
cf["dbNum"] = "0"
|
||||
}
|
||||
if _, ok := cf["password"]; !ok {
|
||||
cf["password"] = ""
|
||||
}
|
||||
rc.key = cf["key"]
|
||||
rc.conninfo = cf["conn"]
|
||||
rc.dbNum, _ = strconv.Atoi(cf["dbNum"])
|
||||
rc.password = cf["password"]
|
||||
|
||||
rc.connectInit()
|
||||
|
||||
c := rc.p.Get()
|
||||
@ -166,6 +209,22 @@ func (rc *RedisCache) StartAndGC(config string) error {
|
||||
func (rc *RedisCache) connectInit() {
|
||||
dialFunc := func() (c redis.Conn, err error) {
|
||||
c, err = redis.Dial("tcp", rc.conninfo)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if rc.password != "" {
|
||||
if _, err := c.Do("AUTH", rc.password); err != nil {
|
||||
c.Close()
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
_, selecterr := c.Do("SELECT", rc.dbNum)
|
||||
if selecterr != nil {
|
||||
c.Close()
|
||||
return nil, selecterr
|
||||
}
|
||||
return
|
||||
}
|
||||
// initialize a new pool
|
||||
|
21
cache/redis/redis_test.go
vendored
21
cache/redis/redis_test.go
vendored
@ -67,6 +67,7 @@ func TestRedisCache(t *testing.T) {
|
||||
if bm.IsExist("astaxie") {
|
||||
t.Error("delete err")
|
||||
}
|
||||
|
||||
//test string
|
||||
if err = bm.Put("astaxie", "author", 10); err != nil {
|
||||
t.Error("set Error", err)
|
||||
@ -78,6 +79,26 @@ func TestRedisCache(t *testing.T) {
|
||||
if v, _ := redis.String(bm.Get("astaxie"), err); v != "author" {
|
||||
t.Error("get err")
|
||||
}
|
||||
|
||||
//test GetMulti
|
||||
if err = bm.Put("astaxie1", "author1", 10); err != nil {
|
||||
t.Error("set Error", err)
|
||||
}
|
||||
if !bm.IsExist("astaxie1") {
|
||||
t.Error("check err")
|
||||
}
|
||||
|
||||
vv := bm.GetMulti([]string{"astaxie", "astaxie1"})
|
||||
if len(vv) != 2 {
|
||||
t.Error("GetMulti ERROR")
|
||||
}
|
||||
if v, _ := redis.String(vv[0], nil); v != "author" {
|
||||
t.Error("GetMulti ERROR")
|
||||
}
|
||||
if v, _ := redis.String(vv[1], nil); v != "author1" {
|
||||
t.Error("GetMulti ERROR")
|
||||
}
|
||||
|
||||
// test clear all
|
||||
if err = bm.ClearAll(); err != nil {
|
||||
t.Error("clear all err")
|
||||
|
47
config.go
47
config.go
@ -81,6 +81,8 @@ var (
|
||||
AppConfigProvider string // config provider
|
||||
EnableDocs bool // enable generate docs & server docs API Swagger
|
||||
RouterCaseSensitive bool // router case sensitive default is true
|
||||
AccessLogs bool // print access logs, default is false
|
||||
Graceful bool // use graceful start the server
|
||||
)
|
||||
|
||||
type beegoAppConfig struct {
|
||||
@ -97,6 +99,10 @@ func newAppConfig(AppConfigProvider, AppConfigPath string) (*beegoAppConfig, err
|
||||
}
|
||||
|
||||
func (b *beegoAppConfig) Set(key, val string) error {
|
||||
err := b.innerConfig.Set(RunMode+"::"+key, val)
|
||||
if err == nil {
|
||||
return err
|
||||
}
|
||||
return b.innerConfig.Set(key, val)
|
||||
}
|
||||
|
||||
@ -110,7 +116,7 @@ func (b *beegoAppConfig) String(key string) string {
|
||||
|
||||
func (b *beegoAppConfig) Strings(key string) []string {
|
||||
v := b.innerConfig.Strings(RunMode + "::" + key)
|
||||
if len(v) == 0 {
|
||||
if v[0] == "" {
|
||||
return b.innerConfig.Strings(key)
|
||||
}
|
||||
return v
|
||||
@ -149,27 +155,51 @@ func (b *beegoAppConfig) Float(key string) (float64, error) {
|
||||
}
|
||||
|
||||
func (b *beegoAppConfig) DefaultString(key string, defaultval string) string {
|
||||
return b.innerConfig.DefaultString(key, defaultval)
|
||||
v := b.String(key)
|
||||
if v != "" {
|
||||
return v
|
||||
}
|
||||
return defaultval
|
||||
}
|
||||
|
||||
func (b *beegoAppConfig) DefaultStrings(key string, defaultval []string) []string {
|
||||
return b.innerConfig.DefaultStrings(key, defaultval)
|
||||
v := b.Strings(key)
|
||||
if len(v) != 0 {
|
||||
return v
|
||||
}
|
||||
return defaultval
|
||||
}
|
||||
|
||||
func (b *beegoAppConfig) DefaultInt(key string, defaultval int) int {
|
||||
return b.innerConfig.DefaultInt(key, defaultval)
|
||||
v, err := b.Int(key)
|
||||
if err == nil {
|
||||
return v
|
||||
}
|
||||
return defaultval
|
||||
}
|
||||
|
||||
func (b *beegoAppConfig) DefaultInt64(key string, defaultval int64) int64 {
|
||||
return b.innerConfig.DefaultInt64(key, defaultval)
|
||||
v, err := b.Int64(key)
|
||||
if err == nil {
|
||||
return v
|
||||
}
|
||||
return defaultval
|
||||
}
|
||||
|
||||
func (b *beegoAppConfig) DefaultBool(key string, defaultval bool) bool {
|
||||
return b.innerConfig.DefaultBool(key, defaultval)
|
||||
v, err := b.Bool(key)
|
||||
if err == nil {
|
||||
return v
|
||||
}
|
||||
return defaultval
|
||||
}
|
||||
|
||||
func (b *beegoAppConfig) DefaultFloat(key string, defaultval float64) float64 {
|
||||
return b.innerConfig.DefaultFloat(key, defaultval)
|
||||
v, err := b.Float(key)
|
||||
if err == nil {
|
||||
return v
|
||||
}
|
||||
return defaultval
|
||||
}
|
||||
|
||||
func (b *beegoAppConfig) DIY(key string) (interface{}, error) {
|
||||
@ -480,5 +510,8 @@ func ParseConfig() (err error) {
|
||||
if casesensitive, err := AppConfig.Bool("RouterCaseSensitive"); err == nil {
|
||||
RouterCaseSensitive = casesensitive
|
||||
}
|
||||
if graceful, err := AppConfig.Bool("Graceful"); err == nil {
|
||||
Graceful = graceful
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
@ -300,21 +300,8 @@ func (c *IniConfigContainer) SaveConfigFile(filename string) (err error) {
|
||||
defer f.Close()
|
||||
|
||||
buf := bytes.NewBuffer(nil)
|
||||
for section, dt := range c.data {
|
||||
// Write section comments.
|
||||
if v, ok := c.sectionComment[section]; ok {
|
||||
if _, err = buf.WriteString(string(bNumComment) + v + lineBreak); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if section != DEFAULT_SECTION {
|
||||
// Write section name.
|
||||
if _, err = buf.WriteString(string(sectionStart) + section + string(sectionEnd) + lineBreak); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Save default section at first place
|
||||
if dt, ok := c.data[DEFAULT_SECTION]; ok {
|
||||
for key, val := range dt {
|
||||
if key != " " {
|
||||
// Write key comments.
|
||||
@ -336,6 +323,43 @@ func (c *IniConfigContainer) SaveConfigFile(filename string) (err error) {
|
||||
return err
|
||||
}
|
||||
}
|
||||
// Save named sections
|
||||
for section, dt := range c.data {
|
||||
if section != DEFAULT_SECTION {
|
||||
// Write section comments.
|
||||
if v, ok := c.sectionComment[section]; ok {
|
||||
if _, err = buf.WriteString(string(bNumComment) + v + lineBreak); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Write section name.
|
||||
if _, err = buf.WriteString(string(sectionStart) + section + string(sectionEnd) + lineBreak); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for key, val := range dt {
|
||||
if key != " " {
|
||||
// Write key comments.
|
||||
if v, ok := c.keyComment[key]; ok {
|
||||
if _, err = buf.WriteString(string(bNumComment) + v + lineBreak); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Write key and value.
|
||||
if _, err = buf.WriteString(key + string(bEqual) + val + lineBreak); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Put a line between sections.
|
||||
if _, err = buf.WriteString(lineBreak); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if _, err = buf.WriteTo(f); err != nil {
|
||||
return err
|
||||
|
@ -17,13 +17,10 @@ package config
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// JsonConfig is a json config parser and implements Config interface.
|
||||
@ -41,13 +38,19 @@ func (js *JsonConfig) Parse(filename string) (ConfigContainer, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return js.ParseData(content)
|
||||
}
|
||||
|
||||
// ParseData returns a ConfigContainer with json string
|
||||
func (js *JsonConfig) ParseData(data []byte) (ConfigContainer, error) {
|
||||
x := &JsonConfigContainer{
|
||||
data: make(map[string]interface{}),
|
||||
}
|
||||
err = json.Unmarshal(content, &x.data)
|
||||
err := json.Unmarshal(data, &x.data)
|
||||
if err != nil {
|
||||
var wrappingArray []interface{}
|
||||
err2 := json.Unmarshal(content, &wrappingArray)
|
||||
err2 := json.Unmarshal(data, &wrappingArray)
|
||||
if err2 != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -56,16 +59,6 @@ func (js *JsonConfig) Parse(filename string) (ConfigContainer, error) {
|
||||
return x, nil
|
||||
}
|
||||
|
||||
func (js *JsonConfig) ParseData(data []byte) (ConfigContainer, error) {
|
||||
// Save memory data to temporary file
|
||||
tmpName := path.Join(os.TempDir(), "beego", fmt.Sprintf("%d", time.Now().Nanosecond()))
|
||||
os.MkdirAll(path.Dir(tmpName), os.ModePerm)
|
||||
if err := ioutil.WriteFile(tmpName, data, 0655); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return js.Parse(tmpName)
|
||||
}
|
||||
|
||||
// A Config represents the json configuration.
|
||||
// Only when get value, support key as section:name type.
|
||||
type JsonConfigContainer struct {
|
||||
@ -88,11 +81,10 @@ func (c *JsonConfigContainer) Bool(key string) (bool, error) {
|
||||
// DefaultBool return the bool value if has no error
|
||||
// otherwise return the defaultval
|
||||
func (c *JsonConfigContainer) DefaultBool(key string, defaultval bool) bool {
|
||||
if v, err := c.Bool(key); err != nil {
|
||||
return defaultval
|
||||
} else {
|
||||
if v, err := c.Bool(key); err == nil {
|
||||
return v
|
||||
}
|
||||
return defaultval
|
||||
}
|
||||
|
||||
// Int returns the integer value for a given key.
|
||||
@ -110,11 +102,10 @@ func (c *JsonConfigContainer) Int(key string) (int, error) {
|
||||
// DefaultInt returns the integer value for a given key.
|
||||
// if err != nil return defaltval
|
||||
func (c *JsonConfigContainer) DefaultInt(key string, defaultval int) int {
|
||||
if v, err := c.Int(key); err != nil {
|
||||
return defaultval
|
||||
} else {
|
||||
if v, err := c.Int(key); err == nil {
|
||||
return v
|
||||
}
|
||||
return defaultval
|
||||
}
|
||||
|
||||
// Int64 returns the int64 value for a given key.
|
||||
@ -132,11 +123,10 @@ func (c *JsonConfigContainer) Int64(key string) (int64, error) {
|
||||
// DefaultInt64 returns the int64 value for a given key.
|
||||
// if err != nil return defaltval
|
||||
func (c *JsonConfigContainer) DefaultInt64(key string, defaultval int64) int64 {
|
||||
if v, err := c.Int64(key); err != nil {
|
||||
return defaultval
|
||||
} else {
|
||||
if v, err := c.Int64(key); err == nil {
|
||||
return v
|
||||
}
|
||||
return defaultval
|
||||
}
|
||||
|
||||
// Float returns the float value for a given key.
|
||||
@ -154,11 +144,10 @@ func (c *JsonConfigContainer) Float(key string) (float64, error) {
|
||||
// DefaultFloat returns the float64 value for a given key.
|
||||
// if err != nil return defaltval
|
||||
func (c *JsonConfigContainer) DefaultFloat(key string, defaultval float64) float64 {
|
||||
if v, err := c.Float(key); err != nil {
|
||||
return defaultval
|
||||
} else {
|
||||
if v, err := c.Float(key); err == nil {
|
||||
return v
|
||||
}
|
||||
return defaultval
|
||||
}
|
||||
|
||||
// String returns the string value for a given key.
|
||||
@ -175,35 +164,37 @@ func (c *JsonConfigContainer) String(key string) string {
|
||||
// DefaultString returns the string value for a given key.
|
||||
// if err != nil return defaltval
|
||||
func (c *JsonConfigContainer) DefaultString(key string, defaultval string) string {
|
||||
if v := c.String(key); v == "" {
|
||||
return defaultval
|
||||
} else {
|
||||
// TODO FIXME should not use "" to replace non existance
|
||||
if v := c.String(key); v != "" {
|
||||
return v
|
||||
}
|
||||
return defaultval
|
||||
}
|
||||
|
||||
// Strings returns the []string value for a given key.
|
||||
func (c *JsonConfigContainer) Strings(key string) []string {
|
||||
stringVal := c.String(key)
|
||||
if stringVal == "" {
|
||||
return []string{}
|
||||
}
|
||||
return strings.Split(c.String(key), ";")
|
||||
}
|
||||
|
||||
// DefaultStrings returns the []string value for a given key.
|
||||
// if err != nil return defaltval
|
||||
func (c *JsonConfigContainer) DefaultStrings(key string, defaultval []string) []string {
|
||||
if v := c.Strings(key); len(v) == 0 {
|
||||
return defaultval
|
||||
} else {
|
||||
if v := c.Strings(key); len(v) > 0 {
|
||||
return v
|
||||
}
|
||||
return defaultval
|
||||
}
|
||||
|
||||
// GetSection returns map for the given section
|
||||
func (c *JsonConfigContainer) GetSection(section string) (map[string]string, error) {
|
||||
if v, ok := c.data[section]; ok {
|
||||
return v.(map[string]string), nil
|
||||
} else {
|
||||
return nil, errors.New("not exist setction")
|
||||
}
|
||||
return nil, errors.New("nonexist section " + section)
|
||||
}
|
||||
|
||||
// SaveConfigFile save the config into file
|
||||
@ -222,7 +213,7 @@ func (c *JsonConfigContainer) SaveConfigFile(filename string) (err error) {
|
||||
return err
|
||||
}
|
||||
|
||||
// WriteValue writes a new value for key.
|
||||
// Set writes a new value for key.
|
||||
func (c *JsonConfigContainer) Set(key, val string) error {
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
@ -241,18 +232,20 @@ func (c *JsonConfigContainer) DIY(key string) (v interface{}, err error) {
|
||||
|
||||
// section.key or key
|
||||
func (c *JsonConfigContainer) getData(key string) interface{} {
|
||||
c.RLock()
|
||||
defer c.RUnlock()
|
||||
if len(key) == 0 {
|
||||
return nil
|
||||
}
|
||||
sectionKey := strings.Split(key, "::")
|
||||
if len(sectionKey) >= 2 {
|
||||
curValue, ok := c.data[sectionKey[0]]
|
||||
|
||||
c.RLock()
|
||||
defer c.RUnlock()
|
||||
|
||||
sectionKeys := strings.Split(key, "::")
|
||||
if len(sectionKeys) >= 2 {
|
||||
curValue, ok := c.data[sectionKeys[0]]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
for _, key := range sectionKey[1:] {
|
||||
for _, key := range sectionKeys[1:] {
|
||||
if v, ok := curValue.(map[string]interface{}); ok {
|
||||
if curValue, ok = v[key]; !ok {
|
||||
return nil
|
||||
|
@ -21,6 +21,7 @@ import (
|
||||
|
||||
var jsoncontext = `{
|
||||
"appname": "beeapi",
|
||||
"testnames": "foo;bar",
|
||||
"httpport": 8080,
|
||||
"mysqlport": 3600,
|
||||
"PI": 3.1415976,
|
||||
@ -28,8 +29,8 @@ var jsoncontext = `{
|
||||
"autorender": false,
|
||||
"copyrequestbody": true,
|
||||
"database": {
|
||||
"host": "host",
|
||||
"port": "port",
|
||||
"host": "host",
|
||||
"port": "port",
|
||||
"database": "database",
|
||||
"username": "username",
|
||||
"password": "password",
|
||||
@ -122,6 +123,12 @@ func TestJson(t *testing.T) {
|
||||
if jsonconf.String("runmode") != "dev" {
|
||||
t.Fatal("runmode not equal to dev")
|
||||
}
|
||||
if v := jsonconf.Strings("unknown"); len(v) > 0 {
|
||||
t.Fatal("unknown strings, the length should be 0")
|
||||
}
|
||||
if v := jsonconf.Strings("testnames"); len(v) != 2 {
|
||||
t.Fatal("testnames length should be 2")
|
||||
}
|
||||
if v, err := jsonconf.Bool("autorender"); err != nil || v != false {
|
||||
t.Error(v)
|
||||
t.Fatal(err)
|
||||
@ -179,4 +186,8 @@ func TestJson(t *testing.T) {
|
||||
if _, err := jsonconf.Bool("unknown"); err == nil {
|
||||
t.Error("unknown keys should return an error when expecting a Bool")
|
||||
}
|
||||
|
||||
if !jsonconf.DefaultBool("unknow", true) {
|
||||
t.Error("unknown keys with default value wrong")
|
||||
}
|
||||
}
|
||||
|
@ -31,7 +31,6 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/astaxie/beego/middleware"
|
||||
"github.com/astaxie/beego/utils"
|
||||
)
|
||||
|
||||
@ -53,24 +52,10 @@ func (ctx *Context) Redirect(status int, localurl string) {
|
||||
}
|
||||
|
||||
// Abort stops this request.
|
||||
// if middleware.ErrorMaps exists, panic body.
|
||||
// if middleware.HTTPExceptionMaps exists, panic HTTPException struct with status and body string.
|
||||
// if beego.ErrorMaps exists, panic body.
|
||||
func (ctx *Context) Abort(status int, body string) {
|
||||
ctx.ResponseWriter.WriteHeader(status)
|
||||
// first panic from ErrorMaps, is is user defined error functions.
|
||||
if _, ok := middleware.ErrorMaps[body]; ok {
|
||||
panic(body)
|
||||
}
|
||||
// second panic from HTTPExceptionMaps, it is system defined functions.
|
||||
if e, ok := middleware.HTTPExceptionMaps[status]; ok {
|
||||
if len(body) >= 1 {
|
||||
e.Description = body
|
||||
}
|
||||
panic(e)
|
||||
}
|
||||
// last panic user string
|
||||
ctx.ResponseWriter.Write([]byte(body))
|
||||
panic("User stop run")
|
||||
panic(body)
|
||||
}
|
||||
|
||||
// Write string to response body.
|
||||
@ -155,8 +140,11 @@ func (ctx *Context) CheckXsrfCookie() bool {
|
||||
}
|
||||
if token == "" {
|
||||
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")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
@ -21,13 +21,22 @@ import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/astaxie/beego/session"
|
||||
)
|
||||
|
||||
// BeegoInput operates the http request header ,data ,cookie and body.
|
||||
// Regexes for checking the accept headers
|
||||
// TODO make sure these are correct
|
||||
var (
|
||||
acceptsHtmlRegex = regexp.MustCompile(`(text/html|application/xhtml\+xml)(?:,|$)`)
|
||||
acceptsXmlRegex = regexp.MustCompile(`(application/xml|text/xml)(?:,|$)`)
|
||||
acceptsJsonRegex = regexp.MustCompile(`(application/json)(?:,|$)`)
|
||||
)
|
||||
|
||||
// BeegoInput operates the http request header, data, cookie and body.
|
||||
// it also contains router params and current session.
|
||||
type BeegoInput struct {
|
||||
CruSession session.SessionStore
|
||||
@ -72,11 +81,11 @@ func (input *BeegoInput) Site() string {
|
||||
func (input *BeegoInput) Scheme() string {
|
||||
if 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.
|
||||
@ -153,16 +162,31 @@ func (input *BeegoInput) IsSecure() bool {
|
||||
return input.Scheme() == "https"
|
||||
}
|
||||
|
||||
// IsSecure returns boolean of this request is in webSocket.
|
||||
// IsWebsocket returns boolean of this request is in webSocket.
|
||||
func (input *BeegoInput) IsWebsocket() bool {
|
||||
return input.Header("Upgrade") == "websocket"
|
||||
}
|
||||
|
||||
// IsSecure returns boolean of whether file uploads in this request or not..
|
||||
// IsUpload returns boolean of whether file uploads in this request or not..
|
||||
func (input *BeegoInput) IsUpload() bool {
|
||||
return strings.Contains(input.Header("Content-Type"), "multipart/form-data")
|
||||
}
|
||||
|
||||
// Checks if request accepts html response
|
||||
func (input *BeegoInput) AcceptsHtml() bool {
|
||||
return acceptsHtmlRegex.MatchString(input.Header("Accept"))
|
||||
}
|
||||
|
||||
// Checks if request accepts xml response
|
||||
func (input *BeegoInput) AcceptsXml() bool {
|
||||
return acceptsXmlRegex.MatchString(input.Header("Accept"))
|
||||
}
|
||||
|
||||
// Checks if request accepts json response
|
||||
func (input *BeegoInput) AcceptsJson() bool {
|
||||
return acceptsJsonRegex.MatchString(input.Header("Accept"))
|
||||
}
|
||||
|
||||
// IP returns request client ip.
|
||||
// if in proxy, return first proxy id.
|
||||
// if error, return 127.0.0.1.
|
||||
@ -189,16 +213,24 @@ func (input *BeegoInput) Proxy() []string {
|
||||
return []string{}
|
||||
}
|
||||
|
||||
// Referer returns http referer header.
|
||||
func (input *BeegoInput) Referer() string {
|
||||
return input.Header("Referer")
|
||||
}
|
||||
|
||||
// Refer returns http referer header.
|
||||
func (input *BeegoInput) Refer() string {
|
||||
return input.Header("Referer")
|
||||
return input.Referer()
|
||||
}
|
||||
|
||||
// SubDomains returns sub domain string.
|
||||
// if aa.bb.domain.com, returns aa.bb .
|
||||
func (input *BeegoInput) SubDomains() string {
|
||||
parts := strings.Split(input.Host(), ".")
|
||||
return strings.Join(parts[len(parts)-2:], ".")
|
||||
if len(parts) >= 3 {
|
||||
return strings.Join(parts[:len(parts)-2], ".")
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Port returns request client port.
|
||||
@ -237,6 +269,7 @@ func (input *BeegoInput) Query(key string) string {
|
||||
}
|
||||
|
||||
// Header returns request header item string by a given string.
|
||||
// if non-existed, return empty string.
|
||||
func (input *BeegoInput) Header(key string) string {
|
||||
return input.Request.Header.Get(key)
|
||||
}
|
||||
@ -252,11 +285,12 @@ func (input *BeegoInput) Cookie(key string) string {
|
||||
}
|
||||
|
||||
// Session returns current session item value by a given key.
|
||||
// if non-existed, return empty string.
|
||||
func (input *BeegoInput) Session(key interface{}) interface{} {
|
||||
return input.CruSession.Get(key)
|
||||
}
|
||||
|
||||
// Body returns the raw request body data as bytes.
|
||||
// CopyBody returns the raw request body data as bytes.
|
||||
func (input *BeegoInput) CopyBody() []byte {
|
||||
requestbody, _ := ioutil.ReadAll(input.Request.Body)
|
||||
input.Request.Body.Close()
|
||||
@ -296,7 +330,7 @@ func (input *BeegoInput) ParseFormOrMulitForm(maxMemory int64) error {
|
||||
// Bind data from request.Form[key] to dest
|
||||
// like /?id=123&isok=true&ft=1.2&ol[0]=1&ol[1]=2&ul[]=str&ul[]=array&user.Name=astaxie
|
||||
// var id int beegoInput.Bind(&id, "id") id ==123
|
||||
// var isok bool beegoInput.Bind(&isok, "isok") id ==true
|
||||
// var isok bool beegoInput.Bind(&isok, "isok") isok ==true
|
||||
// var ft float64 beegoInput.Bind(&ft, "ft") ft ==1.2
|
||||
// ol := make([]int, 0, 2) beegoInput.Bind(&ol, "ol") ol ==[1 2]
|
||||
// ul := make([]string, 0, 2) beegoInput.Bind(&ul, "ul") ul ==[str array]
|
||||
|
@ -70,3 +70,45 @@ func TestParse(t *testing.T) {
|
||||
}
|
||||
fmt.Println(user)
|
||||
}
|
||||
|
||||
func TestSubDomain(t *testing.T) {
|
||||
r, _ := http.NewRequest("GET", "http://www.example.com/?id=123&isok=true&ft=1.2&ol[0]=1&ol[1]=2&ul[]=str&ul[]=array&user.Name=astaxie", nil)
|
||||
beegoInput := NewInput(r)
|
||||
|
||||
subdomain := beegoInput.SubDomains()
|
||||
if subdomain != "www" {
|
||||
t.Fatal("Subdomain parse error, got" + subdomain)
|
||||
}
|
||||
|
||||
r, _ = http.NewRequest("GET", "http://localhost/", nil)
|
||||
beegoInput.Request = r
|
||||
if beegoInput.SubDomains() != "" {
|
||||
t.Fatal("Subdomain parse error, should be empty, got " + beegoInput.SubDomains())
|
||||
}
|
||||
|
||||
r, _ = http.NewRequest("GET", "http://aa.bb.example.com/", nil)
|
||||
beegoInput.Request = r
|
||||
if beegoInput.SubDomains() != "aa.bb" {
|
||||
t.Fatal("Subdomain parse error, got " + beegoInput.SubDomains())
|
||||
}
|
||||
|
||||
/* TODO Fix this
|
||||
r, _ = http.NewRequest("GET", "http://127.0.0.1/", nil)
|
||||
beegoInput.Request = r
|
||||
if beegoInput.SubDomains() != "" {
|
||||
t.Fatal("Subdomain parse error, got " + beegoInput.SubDomains())
|
||||
}
|
||||
*/
|
||||
|
||||
r, _ = http.NewRequest("GET", "http://example.com/", nil)
|
||||
beegoInput.Request = r
|
||||
if beegoInput.SubDomains() != "" {
|
||||
t.Fatal("Subdomain parse error, got " + beegoInput.SubDomains())
|
||||
}
|
||||
|
||||
r, _ = http.NewRequest("GET", "http://aa.bb.cc.dd.example.com/", nil)
|
||||
beegoInput.Request = r
|
||||
if beegoInput.SubDomains() != "aa.bb.cc.dd" {
|
||||
t.Fatal("Subdomain parse error, got " + beegoInput.SubDomains())
|
||||
}
|
||||
}
|
||||
|
@ -29,6 +29,7 @@ import (
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// BeegoOutput does work for sending response header.
|
||||
@ -98,28 +99,30 @@ func (output *BeegoOutput) Body(content []byte) {
|
||||
func (output *BeegoOutput) Cookie(name string, value string, others ...interface{}) {
|
||||
var b bytes.Buffer
|
||||
fmt.Fprintf(&b, "%s=%s", sanitizeName(name), sanitizeValue(value))
|
||||
if len(others) > 0 {
|
||||
switch v := others[0].(type) {
|
||||
case int:
|
||||
if v > 0 {
|
||||
fmt.Fprintf(&b, "; Max-Age=%d", v)
|
||||
} else if v < 0 {
|
||||
fmt.Fprintf(&b, "; Max-Age=0")
|
||||
}
|
||||
case int64:
|
||||
if v > 0 {
|
||||
fmt.Fprintf(&b, "; Max-Age=%d", v)
|
||||
} else if v < 0 {
|
||||
fmt.Fprintf(&b, "; Max-Age=0")
|
||||
}
|
||||
case int32:
|
||||
if v > 0 {
|
||||
fmt.Fprintf(&b, "; Max-Age=%d", v)
|
||||
} else if v < 0 {
|
||||
fmt.Fprintf(&b, "; Max-Age=0")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//fix cookie not work in IE
|
||||
if len(others) > 0 {
|
||||
switch v := others[0].(type) {
|
||||
case int:
|
||||
if v > 0 {
|
||||
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 {
|
||||
fmt.Fprintf(&b, "; Max-Age=0")
|
||||
}
|
||||
case int64:
|
||||
if v > 0 {
|
||||
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 {
|
||||
fmt.Fprintf(&b, "; Max-Age=0")
|
||||
}
|
||||
case int32:
|
||||
if v > 0 {
|
||||
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 {
|
||||
fmt.Fprintf(&b, "; Max-Age=0")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// the settings below
|
||||
// Path, Domain, Secure, HttpOnly
|
||||
@ -188,7 +191,7 @@ func sanitizeValue(v string) string {
|
||||
// Json writes json to response body.
|
||||
// if coding is true, it converts utf-8 to \u0000 type.
|
||||
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 err error
|
||||
if hasIndent {
|
||||
@ -209,7 +212,7 @@ func (output *BeegoOutput) Json(data interface{}, hasIndent bool, coding bool) e
|
||||
|
||||
// Jsonp writes jsonp to response body.
|
||||
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 err error
|
||||
if hasIndent {
|
||||
@ -235,7 +238,7 @@ func (output *BeegoOutput) Jsonp(data interface{}, hasIndent bool) error {
|
||||
|
||||
// Xml writes xml string to response body.
|
||||
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 err error
|
||||
if hasIndent {
|
||||
|
188
controller.go
188
controller.go
@ -270,16 +270,22 @@ func (c *Controller) Redirect(url string, code int) {
|
||||
// Aborts stops controller handler and show the error data if code is defined in ErrorMap or code string.
|
||||
func (c *Controller) Abort(code string) {
|
||||
status, err := strconv.Atoi(code)
|
||||
if err == nil {
|
||||
c.Ctx.Abort(status, code)
|
||||
} else {
|
||||
c.Ctx.Abort(200, code)
|
||||
if err != nil {
|
||||
status = 200
|
||||
}
|
||||
c.CustomAbort(status, code)
|
||||
}
|
||||
|
||||
// CustomAbort stops controller handler and show the error data, it's similar Aborts, but support status code and body.
|
||||
func (c *Controller) CustomAbort(status int, body string) {
|
||||
c.Ctx.Abort(status, body)
|
||||
c.Ctx.ResponseWriter.WriteHeader(status)
|
||||
// first panic from ErrorMaps, is is user defined error functions.
|
||||
if _, ok := ErrorMaps[body]; ok {
|
||||
panic(body)
|
||||
}
|
||||
// last panic user string
|
||||
c.Ctx.ResponseWriter.Write([]byte(body))
|
||||
panic(USERSTOPRUN)
|
||||
}
|
||||
|
||||
// StopRun makes panic of USERSTOPRUN error and go to recover function if defined.
|
||||
@ -289,7 +295,7 @@ func (c *Controller) StopRun() {
|
||||
|
||||
// UrlFor does another controller handler in this request function.
|
||||
// it goes to this controller method if endpoint is not clear.
|
||||
func (c *Controller) UrlFor(endpoint string, values ...string) string {
|
||||
func (c *Controller) UrlFor(endpoint string, values ...interface{}) string {
|
||||
if len(endpoint) <= 0 {
|
||||
return ""
|
||||
}
|
||||
@ -363,67 +369,128 @@ func (c *Controller) ParseForm(obj interface{}) error {
|
||||
return ParseForm(c.Input(), obj)
|
||||
}
|
||||
|
||||
// GetString returns the input value by key string.
|
||||
func (c *Controller) GetString(key string) string {
|
||||
return c.Ctx.Input.Query(key)
|
||||
// GetString returns the input value by key string or the default value while it's present and input is blank
|
||||
func (c *Controller) GetString(key string, def ...string) string {
|
||||
var defv string
|
||||
if len(def) > 0 {
|
||||
defv = def[0]
|
||||
}
|
||||
|
||||
if v := c.Ctx.Input.Query(key); v != "" {
|
||||
return v
|
||||
} else {
|
||||
return defv
|
||||
}
|
||||
}
|
||||
|
||||
// GetStrings returns the input string slice by key string.
|
||||
// GetStrings returns the input string slice by key string or the default value while it's present and input is blank
|
||||
// it's designed for multi-value input field such as checkbox(input[type=checkbox]), multi-selection.
|
||||
func (c *Controller) GetStrings(key string) []string {
|
||||
func (c *Controller) GetStrings(key string, def ...[]string) []string {
|
||||
var defv []string
|
||||
if len(def) > 0 {
|
||||
defv = def[0]
|
||||
}
|
||||
|
||||
f := c.Input()
|
||||
if f == nil {
|
||||
return []string{}
|
||||
return defv
|
||||
}
|
||||
|
||||
vs := f[key]
|
||||
if len(vs) > 0 {
|
||||
return vs
|
||||
} else {
|
||||
return defv
|
||||
}
|
||||
return []string{}
|
||||
}
|
||||
|
||||
// GetInt returns input as an int
|
||||
func (c *Controller) GetInt(key string) (int, error) {
|
||||
return strconv.Atoi(c.Ctx.Input.Query(key))
|
||||
// GetInt returns input as an int or the default value while it's present and input is blank
|
||||
func (c *Controller) GetInt(key string, def ...int) (int, error) {
|
||||
if strv := c.Ctx.Input.Query(key); strv != "" {
|
||||
return strconv.Atoi(strv)
|
||||
} else if len(def) > 0 {
|
||||
return def[0], nil
|
||||
} else {
|
||||
return strconv.Atoi(strv)
|
||||
}
|
||||
}
|
||||
|
||||
// GetInt8 return input as an int8
|
||||
func (c *Controller) GetInt8(key string) (int8, error) {
|
||||
i64, err := strconv.ParseInt(c.Ctx.Input.Query(key), 10, 8)
|
||||
i8 := int8(i64)
|
||||
|
||||
return i8, err
|
||||
// GetInt8 return input as an int8 or the default value while it's present and input is blank
|
||||
func (c *Controller) GetInt8(key string, def ...int8) (int8, error) {
|
||||
if strv := c.Ctx.Input.Query(key); strv != "" {
|
||||
i64, err := strconv.ParseInt(strv, 10, 8)
|
||||
i8 := int8(i64)
|
||||
return i8, err
|
||||
} else if len(def) > 0 {
|
||||
return def[0], nil
|
||||
} else {
|
||||
i64, err := strconv.ParseInt(strv, 10, 8)
|
||||
i8 := int8(i64)
|
||||
return i8, err
|
||||
}
|
||||
}
|
||||
|
||||
// GetInt16 returns input as an int16
|
||||
func (c *Controller) GetInt16(key string) (int16, error) {
|
||||
i64, err := strconv.ParseInt(c.Ctx.Input.Query(key), 10, 16)
|
||||
i16 := int16(i64)
|
||||
|
||||
return i16, err
|
||||
// GetInt16 returns input as an int16 or the default value while it's present and input is blank
|
||||
func (c *Controller) GetInt16(key string, def ...int16) (int16, error) {
|
||||
if strv := c.Ctx.Input.Query(key); strv != "" {
|
||||
i64, err := strconv.ParseInt(strv, 10, 16)
|
||||
i16 := int16(i64)
|
||||
return i16, err
|
||||
} else if len(def) > 0 {
|
||||
return def[0], nil
|
||||
} else {
|
||||
i64, err := strconv.ParseInt(strv, 10, 16)
|
||||
i16 := int16(i64)
|
||||
return i16, err
|
||||
}
|
||||
}
|
||||
|
||||
// GetInt32 returns input as an int32
|
||||
func (c *Controller) GetInt32(key string) (int32, error) {
|
||||
i64, err := strconv.ParseInt(c.Ctx.Input.Query(key), 10, 32)
|
||||
i32 := int32(i64)
|
||||
|
||||
return i32, err
|
||||
// GetInt32 returns input as an int32 or the default value while it's present and input is blank
|
||||
func (c *Controller) GetInt32(key string, def ...int32) (int32, error) {
|
||||
if strv := c.Ctx.Input.Query(key); strv != "" {
|
||||
i64, err := strconv.ParseInt(c.Ctx.Input.Query(key), 10, 32)
|
||||
i32 := int32(i64)
|
||||
return i32, err
|
||||
} else if len(def) > 0 {
|
||||
return def[0], nil
|
||||
} else {
|
||||
i64, err := strconv.ParseInt(c.Ctx.Input.Query(key), 10, 32)
|
||||
i32 := int32(i64)
|
||||
return i32, err
|
||||
}
|
||||
}
|
||||
|
||||
// GetInt64 returns input value as int64.
|
||||
func (c *Controller) GetInt64(key string) (int64, error) {
|
||||
return strconv.ParseInt(c.Ctx.Input.Query(key), 10, 64)
|
||||
// GetInt64 returns input value as int64 or the default value while it's present and input is blank.
|
||||
func (c *Controller) GetInt64(key string, def ...int64) (int64, error) {
|
||||
if strv := c.Ctx.Input.Query(key); strv != "" {
|
||||
return strconv.ParseInt(strv, 10, 64)
|
||||
} else if len(def) > 0 {
|
||||
return def[0], nil
|
||||
} else {
|
||||
return strconv.ParseInt(strv, 10, 64)
|
||||
}
|
||||
}
|
||||
|
||||
// GetBool returns input value as bool.
|
||||
func (c *Controller) GetBool(key string) (bool, error) {
|
||||
return strconv.ParseBool(c.Ctx.Input.Query(key))
|
||||
// GetBool returns input value as bool or the default value while it's present and input is blank.
|
||||
func (c *Controller) GetBool(key string, def ...bool) (bool, error) {
|
||||
if strv := c.Ctx.Input.Query(key); strv != "" {
|
||||
return strconv.ParseBool(strv)
|
||||
} else if len(def) > 0 {
|
||||
return def[0], nil
|
||||
} else {
|
||||
return strconv.ParseBool(strv)
|
||||
}
|
||||
}
|
||||
|
||||
// GetFloat returns input value as float64.
|
||||
func (c *Controller) GetFloat(key string) (float64, error) {
|
||||
return strconv.ParseFloat(c.Ctx.Input.Query(key), 64)
|
||||
// GetFloat returns input value as float64 or the default value while it's present and input is blank.
|
||||
func (c *Controller) GetFloat(key string, def ...float64) (float64, error) {
|
||||
if strv := c.Ctx.Input.Query(key); strv != "" {
|
||||
return strconv.ParseFloat(strv, 64)
|
||||
} else if len(def) > 0 {
|
||||
return def[0], nil
|
||||
} else {
|
||||
return strconv.ParseFloat(strv, 64)
|
||||
}
|
||||
}
|
||||
|
||||
// GetFile returns the file data in file upload field named as key.
|
||||
@ -432,6 +499,41 @@ func (c *Controller) GetFile(key string) (multipart.File, *multipart.FileHeader,
|
||||
return c.Ctx.Request.FormFile(key)
|
||||
}
|
||||
|
||||
// GetFiles return multi-upload files
|
||||
// files, err:=c.Getfiles("myfiles")
|
||||
// if err != nil {
|
||||
// http.Error(w, err.Error(), http.StatusNoContent)
|
||||
// return
|
||||
// }
|
||||
// for i, _ := range files {
|
||||
// //for each fileheader, get a handle to the actual file
|
||||
// file, err := files[i].Open()
|
||||
// defer file.Close()
|
||||
// if err != nil {
|
||||
// http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
// return
|
||||
// }
|
||||
// //create destination file making sure the path is writeable.
|
||||
// dst, err := os.Create("upload/" + files[i].Filename)
|
||||
// defer dst.Close()
|
||||
// if err != nil {
|
||||
// http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
// return
|
||||
// }
|
||||
// //copy the uploaded file to the destination file
|
||||
// if _, err := io.Copy(dst, file); err != nil {
|
||||
// http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
// return
|
||||
// }
|
||||
// }
|
||||
func (c *Controller) GetFiles(key string) ([]*multipart.FileHeader, error) {
|
||||
files, ok := c.Ctx.Request.MultipartForm.File[key]
|
||||
if ok {
|
||||
return files, nil
|
||||
}
|
||||
return nil, http.ErrMissingFile
|
||||
}
|
||||
|
||||
// SaveToFile saves uploaded file to new path.
|
||||
// it only operates the first one of mutil-upload form file field.
|
||||
func (c *Controller) SaveToFile(fromfile, tofile string) error {
|
||||
|
@ -12,20 +12,26 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package middleware
|
||||
package beego
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"html/template"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/astaxie/beego/context"
|
||||
"github.com/astaxie/beego/utils"
|
||||
)
|
||||
|
||||
var (
|
||||
AppName string
|
||||
VERSION string
|
||||
const (
|
||||
errorTypeHandler = iota
|
||||
errorTypeController
|
||||
)
|
||||
|
||||
var tpl = `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
@ -76,18 +82,18 @@ var tpl = `
|
||||
`
|
||||
|
||||
// render default application error page with error and stack string.
|
||||
func ShowErr(err interface{}, rw http.ResponseWriter, r *http.Request, Stack string) {
|
||||
func showErr(err interface{}, ctx *context.Context, Stack string) {
|
||||
t, _ := template.New("beegoerrortemp").Parse(tpl)
|
||||
data := make(map[string]string)
|
||||
data["AppError"] = AppName + ":" + fmt.Sprint(err)
|
||||
data["RequestMethod"] = r.Method
|
||||
data["RequestURL"] = r.RequestURI
|
||||
data["RemoteAddr"] = r.RemoteAddr
|
||||
data["RequestMethod"] = ctx.Input.Method()
|
||||
data["RequestURL"] = ctx.Input.Uri()
|
||||
data["RemoteAddr"] = ctx.Input.IP()
|
||||
data["Stack"] = Stack
|
||||
data["BeegoVersion"] = VERSION
|
||||
data["GoVersion"] = runtime.Version()
|
||||
rw.WriteHeader(500)
|
||||
t.Execute(rw, data)
|
||||
ctx.ResponseWriter.WriteHeader(500)
|
||||
t.Execute(ctx.ResponseWriter, data)
|
||||
}
|
||||
|
||||
var errtpl = `
|
||||
@ -190,15 +196,68 @@ var errtpl = `
|
||||
</html>
|
||||
`
|
||||
|
||||
type errorInfo struct {
|
||||
controllerType reflect.Type
|
||||
handler http.HandlerFunc
|
||||
method string
|
||||
errorType int
|
||||
}
|
||||
|
||||
// map of http handlers for each error string.
|
||||
var ErrorMaps map[string]http.HandlerFunc
|
||||
var ErrorMaps map[string]*errorInfo
|
||||
|
||||
func init() {
|
||||
ErrorMaps = make(map[string]http.HandlerFunc)
|
||||
ErrorMaps = make(map[string]*errorInfo)
|
||||
}
|
||||
|
||||
// show 401 unauthorized error.
|
||||
func unauthorized(rw http.ResponseWriter, r *http.Request) {
|
||||
t, _ := template.New("beegoerrortemp").Parse(errtpl)
|
||||
data := make(map[string]interface{})
|
||||
data["Title"] = "Unauthorized"
|
||||
data["Content"] = template.HTML("<br>The page you have requested can't be authorized." +
|
||||
"<br>Perhaps you are here because:" +
|
||||
"<br><br><ul>" +
|
||||
"<br>The credentials you supplied are incorrect" +
|
||||
"<br>There are errors in the website address" +
|
||||
"</ul>")
|
||||
data["BeegoVersion"] = VERSION
|
||||
t.Execute(rw, data)
|
||||
}
|
||||
|
||||
// show 402 Payment Required
|
||||
func paymentRequired(rw http.ResponseWriter, r *http.Request) {
|
||||
t, _ := template.New("beegoerrortemp").Parse(errtpl)
|
||||
data := make(map[string]interface{})
|
||||
data["Title"] = "Payment Required"
|
||||
data["Content"] = template.HTML("<br>The page you have requested Payment Required." +
|
||||
"<br>Perhaps you are here because:" +
|
||||
"<br><br><ul>" +
|
||||
"<br>The credentials you supplied are incorrect" +
|
||||
"<br>There are errors in the website address" +
|
||||
"</ul>")
|
||||
data["BeegoVersion"] = VERSION
|
||||
t.Execute(rw, data)
|
||||
}
|
||||
|
||||
// show 403 forbidden error.
|
||||
func forbidden(rw http.ResponseWriter, r *http.Request) {
|
||||
t, _ := template.New("beegoerrortemp").Parse(errtpl)
|
||||
data := make(map[string]interface{})
|
||||
data["Title"] = "Forbidden"
|
||||
data["Content"] = template.HTML("<br>The page you have requested is forbidden." +
|
||||
"<br>Perhaps you are here because:" +
|
||||
"<br><br><ul>" +
|
||||
"<br>Your address may be blocked" +
|
||||
"<br>The site may be disabled" +
|
||||
"<br>You need to log in" +
|
||||
"</ul>")
|
||||
data["BeegoVersion"] = VERSION
|
||||
t.Execute(rw, data)
|
||||
}
|
||||
|
||||
// show 404 notfound error.
|
||||
func NotFound(rw http.ResponseWriter, r *http.Request) {
|
||||
func notFound(rw http.ResponseWriter, r *http.Request) {
|
||||
t, _ := template.New("beegoerrortemp").Parse(errtpl)
|
||||
data := make(map[string]interface{})
|
||||
data["Title"] = "Page Not Found"
|
||||
@ -211,45 +270,66 @@ func NotFound(rw http.ResponseWriter, r *http.Request) {
|
||||
"<br>You like 404 pages" +
|
||||
"</ul>")
|
||||
data["BeegoVersion"] = VERSION
|
||||
//rw.WriteHeader(http.StatusNotFound)
|
||||
t.Execute(rw, data)
|
||||
}
|
||||
|
||||
// show 401 unauthorized error.
|
||||
func Unauthorized(rw http.ResponseWriter, r *http.Request) {
|
||||
// show 405 Method Not Allowed
|
||||
func methodNotAllowed(rw http.ResponseWriter, r *http.Request) {
|
||||
t, _ := template.New("beegoerrortemp").Parse(errtpl)
|
||||
data := make(map[string]interface{})
|
||||
data["Title"] = "Unauthorized"
|
||||
data["Content"] = template.HTML("<br>The page you have requested can't be authorized." +
|
||||
data["Title"] = "Method Not Allowed"
|
||||
data["Content"] = template.HTML("<br>The method you have requested Not Allowed." +
|
||||
"<br>Perhaps you are here because:" +
|
||||
"<br><br><ul>" +
|
||||
"<br>The credentials you supplied are incorrect" +
|
||||
"<br>There are errors in the website address" +
|
||||
"<br>The method specified in the Request-Line is not allowed for the resource identified by the Request-URI" +
|
||||
"<br>The response MUST include an Allow header containing a list of valid methods for the requested resource." +
|
||||
"</ul>")
|
||||
data["BeegoVersion"] = VERSION
|
||||
//rw.WriteHeader(http.StatusUnauthorized)
|
||||
t.Execute(rw, data)
|
||||
}
|
||||
|
||||
// show 403 forbidden error.
|
||||
func Forbidden(rw http.ResponseWriter, r *http.Request) {
|
||||
// show 500 internal server error.
|
||||
func internalServerError(rw http.ResponseWriter, r *http.Request) {
|
||||
t, _ := template.New("beegoerrortemp").Parse(errtpl)
|
||||
data := make(map[string]interface{})
|
||||
data["Title"] = "Forbidden"
|
||||
data["Content"] = template.HTML("<br>The page you have requested is forbidden." +
|
||||
"<br>Perhaps you are here because:" +
|
||||
data["Title"] = "Internal Server Error"
|
||||
data["Content"] = template.HTML("<br>The page you have requested is down right now." +
|
||||
"<br><br><ul>" +
|
||||
"<br>Your address may be blocked" +
|
||||
"<br>The site may be disabled" +
|
||||
"<br>You need to log in" +
|
||||
"</ul>")
|
||||
"<br>Please try again later and report the error to the website administrator" +
|
||||
"<br></ul>")
|
||||
data["BeegoVersion"] = VERSION
|
||||
t.Execute(rw, data)
|
||||
}
|
||||
|
||||
// show 501 Not Implemented.
|
||||
func notImplemented(rw http.ResponseWriter, r *http.Request) {
|
||||
t, _ := template.New("beegoerrortemp").Parse(errtpl)
|
||||
data := make(map[string]interface{})
|
||||
data["Title"] = "Not Implemented"
|
||||
data["Content"] = template.HTML("<br>The page you have requested is Not Implemented." +
|
||||
"<br><br><ul>" +
|
||||
"<br>Please try again later and report the error to the website administrator" +
|
||||
"<br></ul>")
|
||||
data["BeegoVersion"] = VERSION
|
||||
t.Execute(rw, data)
|
||||
}
|
||||
|
||||
// show 502 Bad Gateway.
|
||||
func badGateway(rw http.ResponseWriter, r *http.Request) {
|
||||
t, _ := template.New("beegoerrortemp").Parse(errtpl)
|
||||
data := make(map[string]interface{})
|
||||
data["Title"] = "Bad Gateway"
|
||||
data["Content"] = template.HTML("<br>The page you have requested is down right now." +
|
||||
"<br><br><ul>" +
|
||||
"<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." +
|
||||
"<br>Please try again later and report the error to the website administrator" +
|
||||
"<br></ul>")
|
||||
data["BeegoVersion"] = VERSION
|
||||
//rw.WriteHeader(http.StatusForbidden)
|
||||
t.Execute(rw, data)
|
||||
}
|
||||
|
||||
// show 503 service unavailable error.
|
||||
func ServiceUnavailable(rw http.ResponseWriter, r *http.Request) {
|
||||
func serviceUnavailable(rw http.ResponseWriter, r *http.Request) {
|
||||
t, _ := template.New("beegoerrortemp").Parse(errtpl)
|
||||
data := make(map[string]interface{})
|
||||
data["Title"] = "Service Unavailable"
|
||||
@ -260,80 +340,151 @@ func ServiceUnavailable(rw http.ResponseWriter, r *http.Request) {
|
||||
"<br>Please try again later." +
|
||||
"</ul>")
|
||||
data["BeegoVersion"] = VERSION
|
||||
//rw.WriteHeader(http.StatusServiceUnavailable)
|
||||
t.Execute(rw, data)
|
||||
}
|
||||
|
||||
// show 500 internal server error.
|
||||
func InternalServerError(rw http.ResponseWriter, r *http.Request) {
|
||||
// show 504 Gateway Timeout.
|
||||
func gatewayTimeout(rw http.ResponseWriter, r *http.Request) {
|
||||
t, _ := template.New("beegoerrortemp").Parse(errtpl)
|
||||
data := make(map[string]interface{})
|
||||
data["Title"] = "Internal Server Error"
|
||||
data["Content"] = template.HTML("<br>The page you have requested is down right now." +
|
||||
data["Title"] = "Gateway Timeout"
|
||||
data["Content"] = template.HTML("<br>The page you have requested is unavailable." +
|
||||
"<br>Perhaps you are here because:" +
|
||||
"<br><br><ul>" +
|
||||
"<br>Please try again later and report the error to the website administrator" +
|
||||
"<br></ul>")
|
||||
"<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." +
|
||||
"<br>Please try again later." +
|
||||
"</ul>")
|
||||
data["BeegoVersion"] = VERSION
|
||||
//rw.WriteHeader(http.StatusInternalServerError)
|
||||
t.Execute(rw, data)
|
||||
}
|
||||
|
||||
// show 500 internal error with simple text string.
|
||||
func SimpleServerError(rw http.ResponseWriter, r *http.Request) {
|
||||
http.Error(rw, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
// add http handler for given error string.
|
||||
func Errorhandler(err string, h http.HandlerFunc) {
|
||||
ErrorMaps[err] = h
|
||||
}
|
||||
|
||||
// register default error http handlers, 404,401,403,500 and 503.
|
||||
func RegisterErrorHandler() {
|
||||
if _, ok := ErrorMaps["404"]; !ok {
|
||||
ErrorMaps["404"] = NotFound
|
||||
func registerDefaultErrorHandler() {
|
||||
if _, ok := ErrorMaps["401"]; !ok {
|
||||
Errorhandler("401", unauthorized)
|
||||
}
|
||||
|
||||
if _, ok := ErrorMaps["401"]; !ok {
|
||||
ErrorMaps["401"] = Unauthorized
|
||||
if _, ok := ErrorMaps["402"]; !ok {
|
||||
Errorhandler("402", paymentRequired)
|
||||
}
|
||||
|
||||
if _, ok := ErrorMaps["403"]; !ok {
|
||||
ErrorMaps["403"] = Forbidden
|
||||
Errorhandler("403", forbidden)
|
||||
}
|
||||
|
||||
if _, ok := ErrorMaps["503"]; !ok {
|
||||
ErrorMaps["503"] = ServiceUnavailable
|
||||
if _, ok := ErrorMaps["404"]; !ok {
|
||||
Errorhandler("404", notFound)
|
||||
}
|
||||
|
||||
if _, ok := ErrorMaps["405"]; !ok {
|
||||
Errorhandler("405", methodNotAllowed)
|
||||
}
|
||||
|
||||
if _, ok := ErrorMaps["500"]; !ok {
|
||||
ErrorMaps["500"] = InternalServerError
|
||||
Errorhandler("500", internalServerError)
|
||||
}
|
||||
if _, ok := ErrorMaps["501"]; !ok {
|
||||
Errorhandler("501", notImplemented)
|
||||
}
|
||||
if _, ok := ErrorMaps["502"]; !ok {
|
||||
Errorhandler("502", badGateway)
|
||||
}
|
||||
|
||||
if _, ok := ErrorMaps["503"]; !ok {
|
||||
Errorhandler("503", serviceUnavailable)
|
||||
}
|
||||
|
||||
if _, ok := ErrorMaps["504"]; !ok {
|
||||
Errorhandler("504", gatewayTimeout)
|
||||
}
|
||||
}
|
||||
|
||||
// ErrorHandler registers http.HandlerFunc to each http err code string.
|
||||
// usage:
|
||||
// beego.ErrorHandler("404",NotFound)
|
||||
// beego.ErrorHandler("500",InternalServerError)
|
||||
func Errorhandler(code string, h http.HandlerFunc) *App {
|
||||
errinfo := &errorInfo{}
|
||||
errinfo.errorType = errorTypeHandler
|
||||
errinfo.handler = h
|
||||
errinfo.method = code
|
||||
ErrorMaps[code] = errinfo
|
||||
return BeeApp
|
||||
}
|
||||
|
||||
// ErrorController registers ControllerInterface to each http err code string.
|
||||
// usage:
|
||||
// beego.ErrorHandler(&controllers.ErrorController{})
|
||||
func ErrorController(c ControllerInterface) *App {
|
||||
reflectVal := reflect.ValueOf(c)
|
||||
rt := reflectVal.Type()
|
||||
ct := reflect.Indirect(reflectVal).Type()
|
||||
for i := 0; i < rt.NumMethod(); i++ {
|
||||
if !utils.InSlice(rt.Method(i).Name, exceptMethod) && strings.HasPrefix(rt.Method(i).Name, "Error") {
|
||||
errinfo := &errorInfo{}
|
||||
errinfo.errorType = errorTypeController
|
||||
errinfo.controllerType = ct
|
||||
errinfo.method = rt.Method(i).Name
|
||||
errname := strings.TrimPrefix(rt.Method(i).Name, "Error")
|
||||
ErrorMaps[errname] = errinfo
|
||||
}
|
||||
}
|
||||
return BeeApp
|
||||
}
|
||||
|
||||
// show error string as simple text message.
|
||||
// if error string is empty, show 500 error as default.
|
||||
func Exception(errcode string, w http.ResponseWriter, r *http.Request, msg string) {
|
||||
func exception(errcode string, ctx *context.Context) {
|
||||
code, err := strconv.Atoi(errcode)
|
||||
if err != nil {
|
||||
code = 503
|
||||
}
|
||||
if h, ok := ErrorMaps[errcode]; ok {
|
||||
isint, err := strconv.Atoi(errcode)
|
||||
if err != nil {
|
||||
isint = 500
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.WriteHeader(isint)
|
||||
h(w, r)
|
||||
executeError(h, ctx, code)
|
||||
return
|
||||
} else if h, ok := ErrorMaps["503"]; ok {
|
||||
executeError(h, ctx, code)
|
||||
return
|
||||
} else {
|
||||
isint, err := strconv.Atoi(errcode)
|
||||
if err != nil {
|
||||
isint = 500
|
||||
}
|
||||
if isint == 400 {
|
||||
msg = "404 page not found"
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||
w.WriteHeader(isint)
|
||||
fmt.Fprintln(w, msg)
|
||||
return
|
||||
ctx.ResponseWriter.WriteHeader(code)
|
||||
ctx.WriteString(errcode)
|
||||
}
|
||||
}
|
||||
|
||||
func executeError(err *errorInfo, ctx *context.Context, code int) {
|
||||
if err.errorType == errorTypeHandler {
|
||||
ctx.ResponseWriter.WriteHeader(code)
|
||||
err.handler(ctx.ResponseWriter, ctx.Request)
|
||||
return
|
||||
}
|
||||
if err.errorType == errorTypeController {
|
||||
ctx.Output.SetStatus(code)
|
||||
//Invoke the request handler
|
||||
vc := reflect.New(err.controllerType)
|
||||
execController, ok := vc.Interface().(ControllerInterface)
|
||||
if !ok {
|
||||
panic("controller is not ControllerInterface")
|
||||
}
|
||||
//call the controller init function
|
||||
execController.Init(ctx, err.controllerType.Name(), err.method, vc.Interface())
|
||||
|
||||
//call prepare function
|
||||
execController.Prepare()
|
||||
|
||||
execController.URLMapping()
|
||||
|
||||
in := make([]reflect.Value, 0)
|
||||
method := vc.MethodByName(err.method)
|
||||
method.Call(in)
|
||||
|
||||
//render template
|
||||
if AutoRender {
|
||||
if err := execController.Render(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// finish all runrouter. release resource
|
||||
execController.Finish()
|
||||
}
|
||||
}
|
@ -2,7 +2,7 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>Chat Example</title>
|
||||
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
|
||||
<script src="//code.jquery.com/jquery-2.1.3.min.js"></script>
|
||||
<script type="text/javascript">
|
||||
$(function() {
|
||||
|
||||
|
16
filter.go
16
filter.go
@ -16,11 +16,12 @@ package beego
|
||||
|
||||
import "github.com/astaxie/beego/context"
|
||||
|
||||
// FilterFunc defines filter function type.
|
||||
// FilterFunc defines a filter function which is invoked before the controller handler is executed.
|
||||
type FilterFunc func(*context.Context)
|
||||
|
||||
// FilterRouter defines filter operation before controller handler execution.
|
||||
// it can match patterned url and do filter function when action arrives.
|
||||
// FilterRouter defines a filter operation which is invoked before the controller handler is executed.
|
||||
// It can match the URL against a pattern, and execute a filter function
|
||||
// when a request with a matching URL arrives.
|
||||
type FilterRouter struct {
|
||||
filterFunc FilterFunc
|
||||
tree *Tree
|
||||
@ -28,10 +29,11 @@ type FilterRouter struct {
|
||||
returnOnOutput bool
|
||||
}
|
||||
|
||||
// ValidRouter check current request is valid for this filter.
|
||||
// if matched, returns parsed params in this request by defined filter router pattern.
|
||||
func (f *FilterRouter) ValidRouter(router string) (bool, map[string]string) {
|
||||
isok, params := f.tree.Match(router)
|
||||
// ValidRouter checks if the current request is matched by this filter.
|
||||
// If the request is matched, the values of the URL parameters defined
|
||||
// by the filter pattern are also returned.
|
||||
func (f *FilterRouter) ValidRouter(url string) (bool, map[string]string) {
|
||||
isok, params := f.tree.Match(url)
|
||||
if isok == nil {
|
||||
return false, nil
|
||||
}
|
||||
|
13
grace/conn.go
Normal file
13
grace/conn.go
Normal file
@ -0,0 +1,13 @@
|
||||
package grace
|
||||
|
||||
import "net"
|
||||
|
||||
type graceConn struct {
|
||||
net.Conn
|
||||
server *graceServer
|
||||
}
|
||||
|
||||
func (c graceConn) Close() error {
|
||||
c.server.wg.Done()
|
||||
return c.Conn.Close()
|
||||
}
|
150
grace/grace.go
Normal file
150
grace/grace.go
Normal file
@ -0,0 +1,150 @@
|
||||
// Copyright 2014 beego Author. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
// Description: http://grisha.org/blog/2014/06/03/graceful-restart-in-golang/
|
||||
//
|
||||
// Usage:
|
||||
//
|
||||
// import(
|
||||
// "log"
|
||||
// "net/http"
|
||||
// "os"
|
||||
//
|
||||
// "github.com/astaxie/beego/grace"
|
||||
// )
|
||||
//
|
||||
// func handler(w http.ResponseWriter, r *http.Request) {
|
||||
// w.Write([]byte("WORLD!"))
|
||||
// }
|
||||
//
|
||||
// func main() {
|
||||
// mux := http.NewServeMux()
|
||||
// mux.HandleFunc("/hello", handler)
|
||||
//
|
||||
// err := grace.ListenAndServe("localhost:8080", mux1)
|
||||
// if err != nil {
|
||||
// log.Println(err)
|
||||
// }
|
||||
// log.Println("Server on 8080 stopped")
|
||||
// os.Exit(0)
|
||||
// }
|
||||
package grace
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
PRE_SIGNAL = iota
|
||||
POST_SIGNAL
|
||||
|
||||
STATE_INIT
|
||||
STATE_RUNNING
|
||||
STATE_SHUTTING_DOWN
|
||||
STATE_TERMINATE
|
||||
)
|
||||
|
||||
var (
|
||||
regLock *sync.Mutex
|
||||
runningServers map[string]*graceServer
|
||||
runningServersOrder []string
|
||||
socketPtrOffsetMap map[string]uint
|
||||
runningServersForked bool
|
||||
|
||||
DefaultReadTimeOut time.Duration
|
||||
DefaultWriteTimeOut time.Duration
|
||||
DefaultMaxHeaderBytes int
|
||||
DefaultTimeout time.Duration
|
||||
|
||||
isChild bool
|
||||
socketOrder string
|
||||
)
|
||||
|
||||
func init() {
|
||||
regLock = &sync.Mutex{}
|
||||
flag.BoolVar(&isChild, "graceful", false, "listen on open fd (after forking)")
|
||||
flag.StringVar(&socketOrder, "socketorder", "", "previous initialization order - used when more than one listener was started")
|
||||
runningServers = make(map[string]*graceServer)
|
||||
runningServersOrder = []string{}
|
||||
socketPtrOffsetMap = make(map[string]uint)
|
||||
|
||||
DefaultMaxHeaderBytes = 0
|
||||
|
||||
DefaultTimeout = 60 * time.Second
|
||||
}
|
||||
|
||||
// NewServer returns a new graceServer.
|
||||
func NewServer(addr string, handler http.Handler) (srv *graceServer) {
|
||||
regLock.Lock()
|
||||
defer regLock.Unlock()
|
||||
if !flag.Parsed() {
|
||||
flag.Parse()
|
||||
}
|
||||
if len(socketOrder) > 0 {
|
||||
for i, addr := range strings.Split(socketOrder, ",") {
|
||||
socketPtrOffsetMap[addr] = uint(i)
|
||||
}
|
||||
} else {
|
||||
socketPtrOffsetMap[addr] = uint(len(runningServersOrder))
|
||||
}
|
||||
|
||||
srv = &graceServer{
|
||||
wg: sync.WaitGroup{},
|
||||
sigChan: make(chan os.Signal),
|
||||
isChild: isChild,
|
||||
SignalHooks: map[int]map[os.Signal][]func(){
|
||||
PRE_SIGNAL: map[os.Signal][]func(){
|
||||
syscall.SIGHUP: []func(){},
|
||||
syscall.SIGINT: []func(){},
|
||||
syscall.SIGTERM: []func(){},
|
||||
},
|
||||
POST_SIGNAL: map[os.Signal][]func(){
|
||||
syscall.SIGHUP: []func(){},
|
||||
syscall.SIGINT: []func(){},
|
||||
syscall.SIGTERM: []func(){},
|
||||
},
|
||||
},
|
||||
state: STATE_INIT,
|
||||
Network: "tcp",
|
||||
}
|
||||
srv.Server = &http.Server{}
|
||||
srv.Server.Addr = addr
|
||||
srv.Server.ReadTimeout = DefaultReadTimeOut
|
||||
srv.Server.WriteTimeout = DefaultWriteTimeOut
|
||||
srv.Server.MaxHeaderBytes = DefaultMaxHeaderBytes
|
||||
srv.Server.Handler = handler
|
||||
|
||||
runningServersOrder = append(runningServersOrder, addr)
|
||||
runningServers[addr] = srv
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// refer http.ListenAndServe
|
||||
func ListenAndServe(addr string, handler http.Handler) error {
|
||||
server := NewServer(addr, handler)
|
||||
return server.ListenAndServe()
|
||||
}
|
||||
|
||||
// refer http.ListenAndServeTLS
|
||||
func ListenAndServeTLS(addr string, certFile string, keyFile string, handler http.Handler) error {
|
||||
server := NewServer(addr, handler)
|
||||
return server.ListenAndServeTLS(certFile, keyFile)
|
||||
}
|
62
grace/listener.go
Normal file
62
grace/listener.go
Normal file
@ -0,0 +1,62 @@
|
||||
package grace
|
||||
|
||||
import (
|
||||
"net"
|
||||
"os"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
type graceListener struct {
|
||||
net.Listener
|
||||
stop chan error
|
||||
stopped bool
|
||||
server *graceServer
|
||||
}
|
||||
|
||||
func newGraceListener(l net.Listener, srv *graceServer) (el *graceListener) {
|
||||
el = &graceListener{
|
||||
Listener: l,
|
||||
stop: make(chan error),
|
||||
server: srv,
|
||||
}
|
||||
go func() {
|
||||
_ = <-el.stop
|
||||
el.stopped = true
|
||||
el.stop <- el.Listener.Close()
|
||||
}()
|
||||
return
|
||||
}
|
||||
|
||||
func (gl *graceListener) Accept() (c net.Conn, err error) {
|
||||
tc, err := gl.Listener.(*net.TCPListener).AcceptTCP()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
tc.SetKeepAlive(true)
|
||||
tc.SetKeepAlivePeriod(3 * time.Minute)
|
||||
|
||||
c = graceConn{
|
||||
Conn: tc,
|
||||
server: gl.server,
|
||||
}
|
||||
|
||||
gl.server.wg.Add(1)
|
||||
return
|
||||
}
|
||||
|
||||
func (el *graceListener) Close() error {
|
||||
if el.stopped {
|
||||
return syscall.EINVAL
|
||||
}
|
||||
el.stop <- nil
|
||||
return <-el.stop
|
||||
}
|
||||
|
||||
func (el *graceListener) File() *os.File {
|
||||
// returns a dup(2) - FD_CLOEXEC flag *not* set
|
||||
tl := el.Listener.(*net.TCPListener)
|
||||
fl, _ := tl.File()
|
||||
return fl
|
||||
}
|
292
grace/server.go
Normal file
292
grace/server.go
Normal file
@ -0,0 +1,292 @@
|
||||
package grace
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/signal"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
type graceServer struct {
|
||||
*http.Server
|
||||
GraceListener net.Listener
|
||||
SignalHooks map[int]map[os.Signal][]func()
|
||||
tlsInnerListener *graceListener
|
||||
wg sync.WaitGroup
|
||||
sigChan chan os.Signal
|
||||
isChild bool
|
||||
state uint8
|
||||
Network string
|
||||
}
|
||||
|
||||
// Serve accepts incoming connections on the Listener l,
|
||||
// creating a new service goroutine for each.
|
||||
// The service goroutines read requests and then call srv.Handler to reply to them.
|
||||
func (srv *graceServer) Serve() (err error) {
|
||||
srv.state = STATE_RUNNING
|
||||
err = srv.Server.Serve(srv.GraceListener)
|
||||
log.Println(syscall.Getpid(), "Waiting for connections to finish...")
|
||||
srv.wg.Wait()
|
||||
srv.state = STATE_TERMINATE
|
||||
return
|
||||
}
|
||||
|
||||
// ListenAndServe listens on the TCP network address srv.Addr and then calls Serve
|
||||
// to handle requests on incoming connections. If srv.Addr is blank, ":http" is
|
||||
// used.
|
||||
func (srv *graceServer) ListenAndServe() (err error) {
|
||||
addr := srv.Addr
|
||||
if addr == "" {
|
||||
addr = ":http"
|
||||
}
|
||||
|
||||
go srv.handleSignals()
|
||||
|
||||
l, err := srv.getListener(addr)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
return err
|
||||
}
|
||||
|
||||
srv.GraceListener = newGraceListener(l, srv)
|
||||
|
||||
if srv.isChild {
|
||||
process, err := os.FindProcess(os.Getppid())
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
return err
|
||||
}
|
||||
err = process.Kill()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
log.Println(os.Getpid(), srv.Addr)
|
||||
return srv.Serve()
|
||||
}
|
||||
|
||||
// ListenAndServeTLS listens on the TCP network address srv.Addr and then calls
|
||||
// Serve to handle requests on incoming TLS connections.
|
||||
//
|
||||
// Filenames containing a certificate and matching private key for the server must
|
||||
// be provided. If the certificate is signed by a certificate authority, the
|
||||
// certFile should be the concatenation of the server's certificate followed by the
|
||||
// CA's certificate.
|
||||
//
|
||||
// If srv.Addr is blank, ":https" is used.
|
||||
func (srv *graceServer) ListenAndServeTLS(certFile, keyFile string) (err error) {
|
||||
addr := srv.Addr
|
||||
if addr == "" {
|
||||
addr = ":https"
|
||||
}
|
||||
|
||||
config := &tls.Config{}
|
||||
if srv.TLSConfig != nil {
|
||||
*config = *srv.TLSConfig
|
||||
}
|
||||
if config.NextProtos == nil {
|
||||
config.NextProtos = []string{"http/1.1"}
|
||||
}
|
||||
|
||||
config.Certificates = make([]tls.Certificate, 1)
|
||||
config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
go srv.handleSignals()
|
||||
|
||||
l, err := srv.getListener(addr)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
return err
|
||||
}
|
||||
|
||||
srv.tlsInnerListener = newGraceListener(l, srv)
|
||||
srv.GraceListener = tls.NewListener(srv.tlsInnerListener, config)
|
||||
|
||||
if srv.isChild {
|
||||
process, err := os.FindProcess(os.Getppid())
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
return err
|
||||
}
|
||||
err = process.Kill()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
log.Println(os.Getpid(), srv.Addr)
|
||||
return srv.Serve()
|
||||
}
|
||||
|
||||
// getListener either opens a new socket to listen on, or takes the acceptor socket
|
||||
// it got passed when restarted.
|
||||
func (srv *graceServer) getListener(laddr string) (l net.Listener, err error) {
|
||||
if srv.isChild {
|
||||
var ptrOffset uint = 0
|
||||
if len(socketPtrOffsetMap) > 0 {
|
||||
ptrOffset = socketPtrOffsetMap[laddr]
|
||||
log.Println("laddr", laddr, "ptr offset", socketPtrOffsetMap[laddr])
|
||||
}
|
||||
|
||||
f := os.NewFile(uintptr(3+ptrOffset), "")
|
||||
l, err = net.FileListener(f)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("net.FileListener error: %v", err)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
l, err = net.Listen(srv.Network, laddr)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("net.Listen error: %v", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// handleSignals listens for os Signals and calls any hooked in function that the
|
||||
// user had registered with the signal.
|
||||
func (srv *graceServer) handleSignals() {
|
||||
var sig os.Signal
|
||||
|
||||
signal.Notify(
|
||||
srv.sigChan,
|
||||
syscall.SIGHUP,
|
||||
syscall.SIGINT,
|
||||
syscall.SIGTERM,
|
||||
)
|
||||
|
||||
pid := syscall.Getpid()
|
||||
for {
|
||||
sig = <-srv.sigChan
|
||||
srv.signalHooks(PRE_SIGNAL, sig)
|
||||
switch sig {
|
||||
case syscall.SIGHUP:
|
||||
log.Println(pid, "Received SIGHUP. forking.")
|
||||
err := srv.fork()
|
||||
if err != nil {
|
||||
log.Println("Fork err:", err)
|
||||
}
|
||||
case syscall.SIGINT:
|
||||
log.Println(pid, "Received SIGINT.")
|
||||
srv.shutdown()
|
||||
case syscall.SIGTERM:
|
||||
log.Println(pid, "Received SIGTERM.")
|
||||
srv.shutdown()
|
||||
default:
|
||||
log.Printf("Received %v: nothing i care about...\n", sig)
|
||||
}
|
||||
srv.signalHooks(POST_SIGNAL, sig)
|
||||
}
|
||||
}
|
||||
|
||||
func (srv *graceServer) signalHooks(ppFlag int, sig os.Signal) {
|
||||
if _, notSet := srv.SignalHooks[ppFlag][sig]; !notSet {
|
||||
return
|
||||
}
|
||||
for _, f := range srv.SignalHooks[ppFlag][sig] {
|
||||
f()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// shutdown closes the listener so that no new connections are accepted. it also
|
||||
// starts a goroutine that will serverTimeout (stop all running requests) the server
|
||||
// after DefaultTimeout.
|
||||
func (srv *graceServer) shutdown() {
|
||||
if srv.state != STATE_RUNNING {
|
||||
return
|
||||
}
|
||||
|
||||
srv.state = STATE_SHUTTING_DOWN
|
||||
if DefaultTimeout >= 0 {
|
||||
go srv.serverTimeout(DefaultTimeout)
|
||||
}
|
||||
err := srv.GraceListener.Close()
|
||||
if err != nil {
|
||||
log.Println(syscall.Getpid(), "Listener.Close() error:", err)
|
||||
} else {
|
||||
log.Println(syscall.Getpid(), srv.GraceListener.Addr(), "Listener closed.")
|
||||
}
|
||||
}
|
||||
|
||||
// serverTimeout forces the server to shutdown in a given timeout - whether it
|
||||
// finished outstanding requests or not. if Read/WriteTimeout are not set or the
|
||||
// max header size is very big a connection could hang
|
||||
func (srv *graceServer) serverTimeout(d time.Duration) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
log.Println("WaitGroup at 0", r)
|
||||
}
|
||||
}()
|
||||
if srv.state != STATE_SHUTTING_DOWN {
|
||||
return
|
||||
}
|
||||
time.Sleep(d)
|
||||
log.Println("[STOP - Hammer Time] Forcefully shutting down parent")
|
||||
for {
|
||||
if srv.state == STATE_TERMINATE {
|
||||
break
|
||||
}
|
||||
srv.wg.Done()
|
||||
}
|
||||
}
|
||||
|
||||
func (srv *graceServer) fork() (err error) {
|
||||
regLock.Lock()
|
||||
defer regLock.Unlock()
|
||||
if runningServersForked {
|
||||
return
|
||||
}
|
||||
runningServersForked = true
|
||||
|
||||
var files = make([]*os.File, len(runningServers))
|
||||
var orderArgs = make([]string, len(runningServers))
|
||||
for _, srvPtr := range runningServers {
|
||||
switch srvPtr.GraceListener.(type) {
|
||||
case *graceListener:
|
||||
files[socketPtrOffsetMap[srvPtr.Server.Addr]] = srvPtr.GraceListener.(*graceListener).File()
|
||||
default:
|
||||
files[socketPtrOffsetMap[srvPtr.Server.Addr]] = srvPtr.tlsInnerListener.File()
|
||||
}
|
||||
orderArgs[socketPtrOffsetMap[srvPtr.Server.Addr]] = srvPtr.Server.Addr
|
||||
}
|
||||
|
||||
log.Println(files)
|
||||
path := os.Args[0]
|
||||
var args []string
|
||||
if len(os.Args) > 1 {
|
||||
for _, arg := range os.Args[1:] {
|
||||
if arg == "-graceful" {
|
||||
break
|
||||
}
|
||||
args = append(args, arg)
|
||||
}
|
||||
}
|
||||
args = append(args, "-graceful")
|
||||
if len(runningServers) > 1 {
|
||||
args = append(args, fmt.Sprintf(`-socketorder=%s`, strings.Join(orderArgs, ",")))
|
||||
log.Println(args)
|
||||
}
|
||||
cmd := exec.Command(path, args...)
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
cmd.ExtraFiles = files
|
||||
err = cmd.Start()
|
||||
if err != nil {
|
||||
log.Fatalf("Restart: Failed to launch, error: %v", err)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
@ -32,6 +32,7 @@ package httplib
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
@ -50,7 +51,14 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
var defaultSetting = BeegoHttpSettings{false, "beegoServer", 60 * time.Second, 60 * time.Second, nil, nil, nil, false}
|
||||
var defaultSetting = BeegoHttpSettings{
|
||||
UserAgent: "beegoServer",
|
||||
ConnectTimeout: 60 * time.Second,
|
||||
ReadWriteTimeout: 60 * time.Second,
|
||||
Gzip: true,
|
||||
DumpBody: true,
|
||||
}
|
||||
|
||||
var defaultCookieJar http.CookieJar
|
||||
var settingMutex sync.Mutex
|
||||
|
||||
@ -75,41 +83,53 @@ func SetDefaultSetting(setting BeegoHttpSettings) {
|
||||
}
|
||||
|
||||
// return *BeegoHttpRequest with specific method
|
||||
func newBeegoRequest(url, method string) *BeegoHttpRequest {
|
||||
func NewBeegoRequest(rawurl, method string) *BeegoHttpRequest {
|
||||
var resp http.Response
|
||||
u, err := url.Parse(rawurl)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
req := http.Request{
|
||||
URL: u,
|
||||
Method: method,
|
||||
Header: make(http.Header),
|
||||
Proto: "HTTP/1.1",
|
||||
ProtoMajor: 1,
|
||||
ProtoMinor: 1,
|
||||
}
|
||||
return &BeegoHttpRequest{url, &req, map[string]string{}, map[string]string{}, defaultSetting, &resp, nil}
|
||||
return &BeegoHttpRequest{
|
||||
url: rawurl,
|
||||
req: &req,
|
||||
params: map[string]string{},
|
||||
files: map[string]string{},
|
||||
setting: defaultSetting,
|
||||
resp: &resp,
|
||||
}
|
||||
}
|
||||
|
||||
// Get returns *BeegoHttpRequest with GET method.
|
||||
func Get(url string) *BeegoHttpRequest {
|
||||
return newBeegoRequest(url, "GET")
|
||||
return NewBeegoRequest(url, "GET")
|
||||
}
|
||||
|
||||
// Post returns *BeegoHttpRequest with POST method.
|
||||
func Post(url string) *BeegoHttpRequest {
|
||||
return newBeegoRequest(url, "POST")
|
||||
return NewBeegoRequest(url, "POST")
|
||||
}
|
||||
|
||||
// Put returns *BeegoHttpRequest with PUT method.
|
||||
func Put(url string) *BeegoHttpRequest {
|
||||
return newBeegoRequest(url, "PUT")
|
||||
return NewBeegoRequest(url, "PUT")
|
||||
}
|
||||
|
||||
// Delete returns *BeegoHttpRequest DELETE method.
|
||||
func Delete(url string) *BeegoHttpRequest {
|
||||
return newBeegoRequest(url, "DELETE")
|
||||
return NewBeegoRequest(url, "DELETE")
|
||||
}
|
||||
|
||||
// Head returns *BeegoHttpRequest with HEAD method.
|
||||
func Head(url string) *BeegoHttpRequest {
|
||||
return newBeegoRequest(url, "HEAD")
|
||||
return NewBeegoRequest(url, "HEAD")
|
||||
}
|
||||
|
||||
// BeegoHttpSettings
|
||||
@ -122,6 +142,8 @@ type BeegoHttpSettings struct {
|
||||
Proxy func(*http.Request) (*url.URL, error)
|
||||
Transport http.RoundTripper
|
||||
EnableCookie bool
|
||||
Gzip bool
|
||||
DumpBody bool
|
||||
}
|
||||
|
||||
// BeegoHttpRequest provides more useful methods for requesting one url than http.Request.
|
||||
@ -133,6 +155,12 @@ type BeegoHttpRequest struct {
|
||||
setting BeegoHttpSettings
|
||||
resp *http.Response
|
||||
body []byte
|
||||
dump []byte
|
||||
}
|
||||
|
||||
// get request
|
||||
func (b *BeegoHttpRequest) GetRequest() *http.Request {
|
||||
return b.req
|
||||
}
|
||||
|
||||
// Change request settings
|
||||
@ -165,6 +193,17 @@ func (b *BeegoHttpRequest) Debug(isdebug bool) *BeegoHttpRequest {
|
||||
return b
|
||||
}
|
||||
|
||||
// Dump Body.
|
||||
func (b *BeegoHttpRequest) DumpBody(isdump bool) *BeegoHttpRequest {
|
||||
b.setting.DumpBody = isdump
|
||||
return b
|
||||
}
|
||||
|
||||
// return the DumpRequest
|
||||
func (b *BeegoHttpRequest) DumpRequest() []byte {
|
||||
return b.dump
|
||||
}
|
||||
|
||||
// SetTimeout sets connect time out and read-write time out for BeegoRequest.
|
||||
func (b *BeegoHttpRequest) SetTimeout(connectTimeout, readWriteTimeout time.Duration) *BeegoHttpRequest {
|
||||
b.setting.ConnectTimeout = connectTimeout
|
||||
@ -184,6 +223,12 @@ func (b *BeegoHttpRequest) Header(key, value string) *BeegoHttpRequest {
|
||||
return b
|
||||
}
|
||||
|
||||
// Set HOST
|
||||
func (b *BeegoHttpRequest) SetHost(host string) *BeegoHttpRequest {
|
||||
b.req.Host = host
|
||||
return b
|
||||
}
|
||||
|
||||
// Set the protocol version for incoming requests.
|
||||
// Client requests always use HTTP/1.1.
|
||||
func (b *BeegoHttpRequest) SetProtocolVersion(vers string) *BeegoHttpRequest {
|
||||
@ -253,30 +298,35 @@ func (b *BeegoHttpRequest) Body(data interface{}) *BeegoHttpRequest {
|
||||
return b
|
||||
}
|
||||
|
||||
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('&')
|
||||
// JsonBody adds request raw body encoding by JSON.
|
||||
func (b *BeegoHttpRequest) JsonBody(obj interface{}) (*BeegoHttpRequest, error) {
|
||||
if b.req.Body == nil && obj != nil {
|
||||
buf := bytes.NewBuffer(nil)
|
||||
enc := json.NewEncoder(buf)
|
||||
if err := enc.Encode(obj); err != nil {
|
||||
return b, err
|
||||
}
|
||||
paramBody = buf.String()
|
||||
paramBody = paramBody[0 : len(paramBody)-1]
|
||||
b.req.Body = ioutil.NopCloser(buf)
|
||||
b.req.ContentLength = int64(buf.Len())
|
||||
b.req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func (b *BeegoHttpRequest) buildUrl(paramBody string) {
|
||||
// build GET url with query string
|
||||
if b.req.Method == "GET" && len(paramBody) > 0 {
|
||||
if strings.Index(b.url, "?") != -1 {
|
||||
b.url += "&" + paramBody
|
||||
} else {
|
||||
b.url = b.url + "?" + paramBody
|
||||
}
|
||||
} else if b.req.Method == "POST" && b.req.Body == nil {
|
||||
return
|
||||
}
|
||||
|
||||
// build POST/PUT/PATCH url and body
|
||||
if (b.req.Method == "POST" || b.req.Method == "PUT" || b.req.Method == "PATCH") && b.req.Body == nil {
|
||||
// with files
|
||||
if len(b.files) > 0 {
|
||||
pr, pw := io.Pipe()
|
||||
bodyWriter := multipart.NewWriter(pw)
|
||||
@ -305,12 +355,44 @@ func (b *BeegoHttpRequest) getResponse() (*http.Response, error) {
|
||||
}()
|
||||
b.Header("Content-Type", bodyWriter.FormDataContentType())
|
||||
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.Body(paramBody)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (b *BeegoHttpRequest) getResponse() (*http.Response, error) {
|
||||
if b.resp.StatusCode != 0 {
|
||||
return b.resp, nil
|
||||
}
|
||||
resp, err := b.SendOut()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b.resp = resp
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (b *BeegoHttpRequest) SendOut() (*http.Response, error) {
|
||||
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)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@ -342,14 +424,12 @@ func (b *BeegoHttpRequest) getResponse() (*http.Response, error) {
|
||||
}
|
||||
}
|
||||
|
||||
var jar http.CookieJar
|
||||
var jar http.CookieJar = nil
|
||||
if b.setting.EnableCookie {
|
||||
if defaultCookieJar == nil {
|
||||
createDefaultCookie()
|
||||
}
|
||||
jar = defaultCookieJar
|
||||
} else {
|
||||
jar = nil
|
||||
}
|
||||
|
||||
client := &http.Client{
|
||||
@ -362,19 +442,13 @@ func (b *BeegoHttpRequest) getResponse() (*http.Response, error) {
|
||||
}
|
||||
|
||||
if b.setting.ShowDebug {
|
||||
dump, err := httputil.DumpRequest(b.req, true)
|
||||
dump, err := httputil.DumpRequest(b.req, b.setting.DumpBody)
|
||||
if err != nil {
|
||||
println(err.Error())
|
||||
log.Println(err.Error())
|
||||
}
|
||||
println(string(dump))
|
||||
b.dump = dump
|
||||
}
|
||||
|
||||
resp, err := client.Do(b.req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b.resp = resp
|
||||
return resp, nil
|
||||
return client.Do(b.req)
|
||||
}
|
||||
|
||||
// String returns the body string in response.
|
||||
@ -402,12 +476,16 @@ func (b *BeegoHttpRequest) Bytes() ([]byte, error) {
|
||||
return nil, nil
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
data, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
if b.setting.Gzip && resp.Header.Get("Content-Encoding") == "gzip" {
|
||||
reader, err := gzip.NewReader(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b.body, err = ioutil.ReadAll(reader)
|
||||
} else {
|
||||
b.body, err = ioutil.ReadAll(resp.Body)
|
||||
}
|
||||
b.body = data
|
||||
return data, nil
|
||||
return b.body, err
|
||||
}
|
||||
|
||||
// ToFile saves the body data in response to one file.
|
||||
@ -438,8 +516,7 @@ func (b *BeegoHttpRequest) ToJson(v interface{}) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = json.Unmarshal(data, v)
|
||||
return err
|
||||
return json.Unmarshal(data, v)
|
||||
}
|
||||
|
||||
// ToXml returns the map that marshals from the body bytes as xml in response .
|
||||
@ -449,8 +526,7 @@ func (b *BeegoHttpRequest) ToXml(v interface{}) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = xml.Unmarshal(data, v)
|
||||
return err
|
||||
return xml.Unmarshal(data, v)
|
||||
}
|
||||
|
||||
// Response executes request client gets response mannually.
|
||||
@ -465,7 +541,7 @@ func TimeoutDialer(cTimeout time.Duration, rwTimeout time.Duration) func(net, ad
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
conn.SetDeadline(time.Now().Add(rwTimeout))
|
||||
return conn, nil
|
||||
err = conn.SetDeadline(time.Now().Add(rwTimeout))
|
||||
return conn, err
|
||||
}
|
||||
}
|
||||
|
10
log.go
10
log.go
@ -78,9 +78,9 @@ func Warning(v ...interface{}) {
|
||||
BeeLogger.Warning(generateFmtStr(len(v)), v...)
|
||||
}
|
||||
|
||||
// Deprecated: compatibility alias for Warning(), Will be removed in 1.5.0.
|
||||
// compatibility alias for Warning()
|
||||
func Warn(v ...interface{}) {
|
||||
Warning(v...)
|
||||
BeeLogger.Warn(generateFmtStr(len(v)), v...)
|
||||
}
|
||||
|
||||
func Notice(v ...interface{}) {
|
||||
@ -92,9 +92,9 @@ func Informational(v ...interface{}) {
|
||||
BeeLogger.Informational(generateFmtStr(len(v)), v...)
|
||||
}
|
||||
|
||||
// Deprecated: compatibility alias for Warning(), Will be removed in 1.5.0.
|
||||
// compatibility alias for Warning()
|
||||
func Info(v ...interface{}) {
|
||||
Informational(v...)
|
||||
BeeLogger.Info(generateFmtStr(len(v)), v...)
|
||||
}
|
||||
|
||||
// Debug logs a message at debug level.
|
||||
@ -103,7 +103,7 @@ func Debug(v ...interface{}) {
|
||||
}
|
||||
|
||||
// Trace logs a message at trace level.
|
||||
// Deprecated: compatibility alias for Warning(), Will be removed in 1.5.0.
|
||||
// compatibility alias for Warning()
|
||||
func Trace(v ...interface{}) {
|
||||
BeeLogger.Trace(generateFmtStr(len(v)), v...)
|
||||
}
|
||||
|
11
logs/conn.go
11
logs/conn.go
@ -43,11 +43,7 @@ func NewConn() LoggerInterface {
|
||||
// init connection writer with json config.
|
||||
// json config only need key "level".
|
||||
func (c *ConnWriter) Init(jsonconfig string) error {
|
||||
err := json.Unmarshal([]byte(jsonconfig), c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
return json.Unmarshal([]byte(jsonconfig), c)
|
||||
}
|
||||
|
||||
// write message in connection.
|
||||
@ -77,10 +73,9 @@ func (c *ConnWriter) Flush() {
|
||||
|
||||
// destroy connection writer and close tcp listener.
|
||||
func (c *ConnWriter) Destroy() {
|
||||
if c.innerWriter == nil {
|
||||
return
|
||||
if c.innerWriter != nil {
|
||||
c.innerWriter.Close()
|
||||
}
|
||||
c.innerWriter.Close()
|
||||
}
|
||||
|
||||
func (c *ConnWriter) connect() error {
|
||||
|
@ -50,9 +50,10 @@ type ConsoleWriter struct {
|
||||
|
||||
// create ConsoleWriter returning as LoggerInterface.
|
||||
func NewConsole() LoggerInterface {
|
||||
cw := new(ConsoleWriter)
|
||||
cw.lg = log.New(os.Stdout, "", log.Ldate|log.Ltime)
|
||||
cw.Level = LevelDebug
|
||||
cw := &ConsoleWriter{
|
||||
lg: log.New(os.Stdout, "", log.Ldate|log.Ltime),
|
||||
Level: LevelDebug,
|
||||
}
|
||||
return cw
|
||||
}
|
||||
|
||||
@ -62,11 +63,7 @@ func (c *ConsoleWriter) Init(jsonconfig string) error {
|
||||
if len(jsonconfig) == 0 {
|
||||
return nil
|
||||
}
|
||||
err := json.Unmarshal([]byte(jsonconfig), c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
return json.Unmarshal([]byte(jsonconfig), c)
|
||||
}
|
||||
|
||||
// write message in console.
|
||||
@ -76,9 +73,10 @@ func (c *ConsoleWriter) WriteMsg(msg string, level int) error {
|
||||
}
|
||||
if goos := runtime.GOOS; goos == "windows" {
|
||||
c.lg.Println(msg)
|
||||
} else {
|
||||
c.lg.Println(colors[level](msg))
|
||||
return nil
|
||||
}
|
||||
c.lg.Println(colors[level](msg))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
76
logs/es/es.go
Normal file
76
logs/es/es.go
Normal file
@ -0,0 +1,76 @@
|
||||
package es
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/astaxie/beego/logs"
|
||||
"github.com/belogik/goes"
|
||||
)
|
||||
|
||||
func NewES() logs.LoggerInterface {
|
||||
cw := &esLogger{
|
||||
Level: logs.LevelDebug,
|
||||
}
|
||||
return cw
|
||||
}
|
||||
|
||||
type esLogger struct {
|
||||
*goes.Connection
|
||||
DSN string `json:"dsn"`
|
||||
Level int `json:"level"`
|
||||
}
|
||||
|
||||
// {"dsn":"http://localhost:9200/","level":1}
|
||||
func (el *esLogger) Init(jsonconfig string) error {
|
||||
err := json.Unmarshal([]byte(jsonconfig), el)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if el.DSN == "" {
|
||||
return errors.New("empty dsn")
|
||||
} else if u, err := url.Parse(el.DSN); err != nil {
|
||||
return err
|
||||
} else if u.Path == "" {
|
||||
return errors.New("missing prefix")
|
||||
} else if host, port, err := net.SplitHostPort(u.Host); err != nil {
|
||||
return err
|
||||
} else {
|
||||
conn := goes.NewConnection(host, port)
|
||||
el.Connection = conn
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (el *esLogger) WriteMsg(msg string, level int) error {
|
||||
if level > el.Level {
|
||||
return nil
|
||||
}
|
||||
t := time.Now()
|
||||
vals := make(map[string]interface{})
|
||||
vals["@timestamp"] = t.Format(time.RFC3339)
|
||||
vals["@msg"] = msg
|
||||
d := goes.Document{
|
||||
Index: fmt.Sprintf("%04d.%02d.%02d", t.Year(), t.Month(), t.Day()),
|
||||
Type: "logs",
|
||||
Fields: vals,
|
||||
}
|
||||
_, err := el.Index(d, nil)
|
||||
return err
|
||||
}
|
||||
|
||||
func (el *esLogger) Destroy() {
|
||||
|
||||
}
|
||||
|
||||
func (el *esLogger) Flush() {
|
||||
|
||||
}
|
||||
|
||||
func init() {
|
||||
logs.Register("es", NewES)
|
||||
}
|
43
logs/file.go
43
logs/file.go
@ -15,10 +15,11 @@
|
||||
package logs
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@ -122,11 +123,7 @@ func (w *FileLogWriter) startLogger() error {
|
||||
return err
|
||||
}
|
||||
w.mw.SetFd(fd)
|
||||
err = w.initFd()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
return w.initFd()
|
||||
}
|
||||
|
||||
func (w *FileLogWriter) docheck(size int) {
|
||||
@ -169,18 +166,44 @@ func (w *FileLogWriter) initFd() error {
|
||||
}
|
||||
w.maxsize_cursize = int(finfo.Size())
|
||||
w.daily_opendate = time.Now().Day()
|
||||
w.maxlines_curlines = 0
|
||||
if finfo.Size() > 0 {
|
||||
content, err := ioutil.ReadFile(w.Filename)
|
||||
count, err := w.lines()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
w.maxlines_curlines = len(strings.Split(string(content), "\n"))
|
||||
} else {
|
||||
w.maxlines_curlines = 0
|
||||
w.maxlines_curlines = count
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *FileLogWriter) lines() (int, error) {
|
||||
fd, err := os.Open(w.Filename)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer fd.Close()
|
||||
|
||||
buf := make([]byte, 32768) // 32k
|
||||
count := 0
|
||||
lineSep := []byte{'\n'}
|
||||
|
||||
for {
|
||||
c, err := fd.Read(buf)
|
||||
if err != nil && err != io.EOF {
|
||||
return count, err
|
||||
}
|
||||
|
||||
count += bytes.Count(buf[:c], lineSep)
|
||||
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return count, nil
|
||||
}
|
||||
|
||||
// DoRotate means it need to write file in new file.
|
||||
// new file name like xx.log.2013-01-01.2
|
||||
func (w *FileLogWriter) DoRotate() error {
|
||||
|
95
logs/log.go
95
logs/log.go
@ -92,6 +92,7 @@ type BeeLogger struct {
|
||||
level int
|
||||
enableFuncCallDepth bool
|
||||
loggerFuncCallDepth int
|
||||
asynchronous bool
|
||||
msg chan *logMsg
|
||||
outputs map[string]LoggerInterface
|
||||
}
|
||||
@ -110,7 +111,11 @@ func NewLogger(channellen int64) *BeeLogger {
|
||||
bl.loggerFuncCallDepth = 2
|
||||
bl.msg = make(chan *logMsg, channellen)
|
||||
bl.outputs = make(map[string]LoggerInterface)
|
||||
//bl.SetLogger("console", "") // default output to console
|
||||
return bl
|
||||
}
|
||||
|
||||
func (bl *BeeLogger) Async() *BeeLogger {
|
||||
bl.asynchronous = true
|
||||
go bl.startLogger()
|
||||
return bl
|
||||
}
|
||||
@ -148,26 +153,30 @@ func (bl *BeeLogger) DelLogger(adaptername string) error {
|
||||
}
|
||||
|
||||
func (bl *BeeLogger) writerMsg(loglevel int, msg string) error {
|
||||
if loglevel > bl.level {
|
||||
return nil
|
||||
}
|
||||
lm := new(logMsg)
|
||||
lm.level = loglevel
|
||||
if bl.enableFuncCallDepth {
|
||||
_, file, line, ok := runtime.Caller(bl.loggerFuncCallDepth)
|
||||
if _, filename := path.Split(file); filename == "log.go" && (line == 97 || line == 83) {
|
||||
_, file, line, ok = runtime.Caller(bl.loggerFuncCallDepth + 1)
|
||||
}
|
||||
if ok {
|
||||
_, filename := path.Split(file)
|
||||
lm.msg = fmt.Sprintf("[%s:%d] %s", filename, line, msg)
|
||||
} else {
|
||||
lm.msg = msg
|
||||
if !ok {
|
||||
file = "???"
|
||||
line = 0
|
||||
}
|
||||
_, filename := path.Split(file)
|
||||
lm.msg = fmt.Sprintf("[%s:%d] %s", filename, line, msg)
|
||||
} else {
|
||||
lm.msg = msg
|
||||
}
|
||||
bl.msg <- lm
|
||||
if bl.asynchronous {
|
||||
bl.msg <- lm
|
||||
} else {
|
||||
for name, l := range bl.outputs {
|
||||
err := l.WriteMsg(lm.msg, lm.level)
|
||||
if err != nil {
|
||||
fmt.Println("unable to WriteMsg to adapter:", name, err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@ -184,6 +193,11 @@ func (bl *BeeLogger) SetLogFuncCallDepth(d int) {
|
||||
bl.loggerFuncCallDepth = d
|
||||
}
|
||||
|
||||
// get log funcCallDepth for wrapper
|
||||
func (bl *BeeLogger) GetLogFuncCallDepth() int {
|
||||
return bl.loggerFuncCallDepth
|
||||
}
|
||||
|
||||
// enable log funcCallDepth
|
||||
func (bl *BeeLogger) EnableFuncCallDepth(b bool) {
|
||||
bl.enableFuncCallDepth = b
|
||||
@ -207,71 +221,104 @@ func (bl *BeeLogger) startLogger() {
|
||||
|
||||
// Log EMERGENCY level message.
|
||||
func (bl *BeeLogger) Emergency(format string, v ...interface{}) {
|
||||
if LevelEmergency > bl.level {
|
||||
return
|
||||
}
|
||||
msg := fmt.Sprintf("[M] "+format, v...)
|
||||
bl.writerMsg(LevelEmergency, msg)
|
||||
}
|
||||
|
||||
// Log ALERT level message.
|
||||
func (bl *BeeLogger) Alert(format string, v ...interface{}) {
|
||||
if LevelAlert > bl.level {
|
||||
return
|
||||
}
|
||||
msg := fmt.Sprintf("[A] "+format, v...)
|
||||
bl.writerMsg(LevelAlert, msg)
|
||||
}
|
||||
|
||||
// Log CRITICAL level message.
|
||||
func (bl *BeeLogger) Critical(format string, v ...interface{}) {
|
||||
if LevelCritical > bl.level {
|
||||
return
|
||||
}
|
||||
msg := fmt.Sprintf("[C] "+format, v...)
|
||||
bl.writerMsg(LevelCritical, msg)
|
||||
}
|
||||
|
||||
// Log ERROR level message.
|
||||
func (bl *BeeLogger) Error(format string, v ...interface{}) {
|
||||
if LevelError > bl.level {
|
||||
return
|
||||
}
|
||||
msg := fmt.Sprintf("[E] "+format, v...)
|
||||
bl.writerMsg(LevelError, msg)
|
||||
}
|
||||
|
||||
// Log WARNING level message.
|
||||
func (bl *BeeLogger) Warning(format string, v ...interface{}) {
|
||||
if LevelWarning > bl.level {
|
||||
return
|
||||
}
|
||||
msg := fmt.Sprintf("[W] "+format, v...)
|
||||
bl.writerMsg(LevelWarning, msg)
|
||||
}
|
||||
|
||||
// Log NOTICE level message.
|
||||
func (bl *BeeLogger) Notice(format string, v ...interface{}) {
|
||||
if LevelNotice > bl.level {
|
||||
return
|
||||
}
|
||||
msg := fmt.Sprintf("[N] "+format, v...)
|
||||
bl.writerMsg(LevelNotice, msg)
|
||||
}
|
||||
|
||||
// Log INFORMATIONAL level message.
|
||||
func (bl *BeeLogger) Informational(format string, v ...interface{}) {
|
||||
if LevelInformational > bl.level {
|
||||
return
|
||||
}
|
||||
msg := fmt.Sprintf("[I] "+format, v...)
|
||||
bl.writerMsg(LevelInformational, msg)
|
||||
}
|
||||
|
||||
// Log DEBUG level message.
|
||||
func (bl *BeeLogger) Debug(format string, v ...interface{}) {
|
||||
if LevelDebug > bl.level {
|
||||
return
|
||||
}
|
||||
msg := fmt.Sprintf("[D] "+format, v...)
|
||||
bl.writerMsg(LevelDebug, msg)
|
||||
}
|
||||
|
||||
// Log WARN level message.
|
||||
//
|
||||
// Deprecated: compatibility alias for Warning(), Will be removed in 1.5.0.
|
||||
// compatibility alias for Warning()
|
||||
func (bl *BeeLogger) Warn(format string, v ...interface{}) {
|
||||
bl.Warning(format, v...)
|
||||
if LevelWarning > bl.level {
|
||||
return
|
||||
}
|
||||
msg := fmt.Sprintf("[W] "+format, v...)
|
||||
bl.writerMsg(LevelWarning, msg)
|
||||
}
|
||||
|
||||
// Log INFO level message.
|
||||
//
|
||||
// Deprecated: compatibility alias for Informational(), Will be removed in 1.5.0.
|
||||
// compatibility alias for Informational()
|
||||
func (bl *BeeLogger) Info(format string, v ...interface{}) {
|
||||
bl.Informational(format, v...)
|
||||
if LevelInformational > bl.level {
|
||||
return
|
||||
}
|
||||
msg := fmt.Sprintf("[I] "+format, v...)
|
||||
bl.writerMsg(LevelInformational, msg)
|
||||
}
|
||||
|
||||
// Log TRACE level message.
|
||||
//
|
||||
// Deprecated: compatibility alias for Debug(), Will be removed in 1.5.0.
|
||||
// compatibility alias for Debug()
|
||||
func (bl *BeeLogger) Trace(format string, v ...interface{}) {
|
||||
bl.Debug(format, v...)
|
||||
if LevelDebug > bl.level {
|
||||
return
|
||||
}
|
||||
msg := fmt.Sprintf("[D] "+format, v...)
|
||||
bl.writerMsg(LevelDebug, msg)
|
||||
}
|
||||
|
||||
// flush all chan data.
|
||||
@ -292,9 +339,9 @@ func (bl *BeeLogger) Close() {
|
||||
fmt.Println("ERROR, unable to WriteMsg (while closing logger):", err)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
break
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
for _, l := range bl.outputs {
|
||||
l.Flush()
|
||||
|
@ -25,7 +25,8 @@ import (
|
||||
)
|
||||
|
||||
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.
|
||||
@ -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 +
|
||||
">\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 err
|
||||
return s.sendMail(s.Host, auth, s.FromAddress, s.RecipientAddresses, mailmsg)
|
||||
}
|
||||
|
||||
// implementing method. empty.
|
||||
|
@ -1,49 +0,0 @@
|
||||
// Copyright 2014 beego Author. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package middleware
|
||||
|
||||
import "fmt"
|
||||
|
||||
// http exceptions
|
||||
type HTTPException struct {
|
||||
StatusCode int // http status code 4xx, 5xx
|
||||
Description string
|
||||
}
|
||||
|
||||
// return http exception error string, e.g. "400 Bad Request".
|
||||
func (e *HTTPException) Error() string {
|
||||
return fmt.Sprintf("%d %s", e.StatusCode, e.Description)
|
||||
}
|
||||
|
||||
// map of http exceptions for each http status code int.
|
||||
// defined 400,401,403,404,405,500,502,503 and 504 default.
|
||||
var HTTPExceptionMaps map[int]HTTPException
|
||||
|
||||
func init() {
|
||||
HTTPExceptionMaps = make(map[int]HTTPException)
|
||||
|
||||
// Normal 4XX HTTP Status
|
||||
HTTPExceptionMaps[400] = HTTPException{400, "Bad Request"}
|
||||
HTTPExceptionMaps[401] = HTTPException{401, "Unauthorized"}
|
||||
HTTPExceptionMaps[403] = HTTPException{403, "Forbidden"}
|
||||
HTTPExceptionMaps[404] = HTTPException{404, "Not Found"}
|
||||
HTTPExceptionMaps[405] = HTTPException{405, "Method Not Allowed"}
|
||||
|
||||
// Normal 5XX HTTP Status
|
||||
HTTPExceptionMaps[500] = HTTPException{500, "Internal Server Error"}
|
||||
HTTPExceptionMaps[502] = HTTPException{502, "Bad Gateway"}
|
||||
HTTPExceptionMaps[503] = HTTPException{503, "Service Unavailable"}
|
||||
HTTPExceptionMaps[504] = HTTPException{504, "Gateway Timeout"}
|
||||
}
|
@ -34,7 +34,6 @@ type Translation struct {
|
||||
}
|
||||
|
||||
func NewLocale(filepath string, defaultlocal string) *Translation {
|
||||
i18n := make(map[string]map[string]string)
|
||||
file, err := os.Open(filepath)
|
||||
if err != nil {
|
||||
panic("open " + filepath + " err :" + err.Error())
|
||||
@ -43,8 +42,9 @@ func NewLocale(filepath string, defaultlocal string) *Translation {
|
||||
if err != nil {
|
||||
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())
|
||||
}
|
||||
return &Translation{
|
||||
|
1
mime.go
1
mime.go
@ -40,6 +40,7 @@ var mimemaps map[string]string = map[string]string{
|
||||
".ani": "application/x-navi-animation",
|
||||
".aos": "application/x-nokia-9000-communicator-add-on-software",
|
||||
".aps": "application/mime",
|
||||
".apk": "application/vnd.android.package-archive",
|
||||
".arc": "application/x-arc-compressed",
|
||||
".arj": "application/arj",
|
||||
".art": "image/x-jg",
|
||||
|
@ -19,7 +19,6 @@ import (
|
||||
"strings"
|
||||
|
||||
beecontext "github.com/astaxie/beego/context"
|
||||
"github.com/astaxie/beego/middleware"
|
||||
)
|
||||
|
||||
type namespaceCond func(*beecontext.Context) bool
|
||||
@ -57,7 +56,7 @@ func NewNamespace(prefix string, params ...innnerNamespace) *Namespace {
|
||||
func (n *Namespace) Cond(cond namespaceCond) *Namespace {
|
||||
fn := func(ctx *beecontext.Context) {
|
||||
if !cond(ctx) {
|
||||
middleware.Exception("405", ctx.ResponseWriter, ctx.Request, "Method not allowed")
|
||||
exception("405", ctx)
|
||||
}
|
||||
}
|
||||
if v, ok := n.handlers.filters[BeforeRouter]; ok {
|
||||
|
@ -117,7 +117,7 @@ o.Begin()
|
||||
...
|
||||
user := User{Name: "slene"}
|
||||
id, err := o.Insert(&user)
|
||||
if err != nil {
|
||||
if err == nil {
|
||||
o.Commit()
|
||||
} else {
|
||||
o.Rollback()
|
||||
|
@ -104,7 +104,11 @@ func getColumnAddQuery(al *alias, fi *fieldInfo) string {
|
||||
typ += " " + "NOT NULL"
|
||||
}
|
||||
|
||||
return fmt.Sprintf("ALTER TABLE %s%s%s ADD COLUMN %s%s%s %s", Q, fi.mi.table, Q, Q, fi.column, Q, typ)
|
||||
return fmt.Sprintf("ALTER TABLE %s%s%s ADD COLUMN %s%s%s %s %s",
|
||||
Q, fi.mi.table, Q,
|
||||
Q, fi.column, Q,
|
||||
typ, getColumnDefault(fi),
|
||||
)
|
||||
}
|
||||
|
||||
// create database creation string.
|
||||
@ -155,6 +159,9 @@ func getDbCreateSql(al *alias) (sqls []string, tableIndexes map[string][]dbIndex
|
||||
//if fi.initial.String() != "" {
|
||||
// column += " DEFAULT " + fi.initial.String()
|
||||
//}
|
||||
|
||||
// Append attribute DEFAULT
|
||||
column += getColumnDefault(fi)
|
||||
|
||||
if fi.unique {
|
||||
column += " " + "UNIQUE"
|
||||
@ -239,3 +246,44 @@ func getDbCreateSql(al *alias) (sqls []string, tableIndexes map[string][]dbIndex
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
// Get string value for the attribute "DEFAULT" for the CREATE, ALTER commands
|
||||
func getColumnDefault(fi *fieldInfo) string {
|
||||
var (
|
||||
v, t, d string
|
||||
)
|
||||
|
||||
// Skip default attribute if field is in relations
|
||||
if fi.rel || fi.reverse {
|
||||
return v
|
||||
}
|
||||
|
||||
t = " DEFAULT '%s' "
|
||||
|
||||
// These defaults will be useful if there no config value orm:"default" and NOT NULL is on
|
||||
switch fi.fieldType {
|
||||
case TypeDateField, TypeDateTimeField:
|
||||
return v;
|
||||
|
||||
case TypeBooleanField, TypeBitField, TypeSmallIntegerField, TypeIntegerField,
|
||||
TypeBigIntegerField, TypePositiveBitField, TypePositiveSmallIntegerField,
|
||||
TypePositiveIntegerField, TypePositiveBigIntegerField, TypeFloatField,
|
||||
TypeDecimalField:
|
||||
d = "0"
|
||||
}
|
||||
|
||||
if fi.colDefault {
|
||||
if !fi.initial.Exist() {
|
||||
v = fmt.Sprintf(t, "")
|
||||
} else {
|
||||
v = fmt.Sprintf(t, fi.initial.String())
|
||||
}
|
||||
} else {
|
||||
if !fi.null {
|
||||
v = fmt.Sprintf(t, d)
|
||||
}
|
||||
}
|
||||
|
||||
return v
|
||||
}
|
||||
|
14
orm/db.go
14
orm/db.go
@ -44,6 +44,8 @@ var (
|
||||
"gte": true,
|
||||
"lt": true,
|
||||
"lte": true,
|
||||
"eq": true,
|
||||
"nq": true,
|
||||
"startswith": true,
|
||||
"endswith": true,
|
||||
"istartswith": true,
|
||||
@ -324,7 +326,7 @@ func (d *dbBase) Read(q dbQuerier, mi *modelInfo, ind reflect.Value, tz *time.Lo
|
||||
query := fmt.Sprintf("SELECT %s%s%s FROM %s%s%s WHERE %s%s%s = ?", Q, sels, Q, Q, mi.table, Q, Q, wheres, Q)
|
||||
|
||||
refs := make([]interface{}, colsNum)
|
||||
for i, _ := range refs {
|
||||
for i := range refs {
|
||||
var ref interface{}
|
||||
refs[i] = &ref
|
||||
}
|
||||
@ -423,7 +425,7 @@ func (d *dbBase) InsertValue(q dbQuerier, mi *modelInfo, isMulti bool, names []s
|
||||
Q := d.ins.TableQuote()
|
||||
|
||||
marks := make([]string, len(names))
|
||||
for i, _ := range marks {
|
||||
for i := range marks {
|
||||
marks[i] = "?"
|
||||
}
|
||||
|
||||
@ -693,7 +695,7 @@ func (d *dbBase) DeleteBatch(q dbQuerier, qs *querySet, mi *modelInfo, cond *Con
|
||||
}
|
||||
|
||||
marks := make([]string, len(args))
|
||||
for i, _ := range marks {
|
||||
for i := range marks {
|
||||
marks[i] = "?"
|
||||
}
|
||||
sql := fmt.Sprintf("IN (%s)", strings.Join(marks, ", "))
|
||||
@ -824,7 +826,7 @@ func (d *dbBase) ReadBatch(q dbQuerier, qs *querySet, mi *modelInfo, cond *Condi
|
||||
}
|
||||
|
||||
refs := make([]interface{}, colsNum)
|
||||
for i, _ := range refs {
|
||||
for i := range refs {
|
||||
var ref interface{}
|
||||
refs[i] = &ref
|
||||
}
|
||||
@ -964,7 +966,7 @@ func (d *dbBase) GenerateOperatorSql(mi *modelInfo, fi *fieldInfo, operator stri
|
||||
switch operator {
|
||||
case "in":
|
||||
marks := make([]string, len(params))
|
||||
for i, _ := range marks {
|
||||
for i := range marks {
|
||||
marks[i] = "?"
|
||||
}
|
||||
sql = fmt.Sprintf("IN (%s)", strings.Join(marks, ", "))
|
||||
@ -1460,7 +1462,7 @@ func (d *dbBase) ReadValues(q dbQuerier, qs *querySet, mi *modelInfo, cond *Cond
|
||||
}
|
||||
|
||||
refs := make([]interface{}, len(cols))
|
||||
for i, _ := range refs {
|
||||
for i := range refs {
|
||||
var ref interface{}
|
||||
refs[i] = &ref
|
||||
}
|
||||
|
@ -30,6 +30,8 @@ var mysqlOperators = map[string]string{
|
||||
"gte": ">= ?",
|
||||
"lt": "< ?",
|
||||
"lte": "<= ?",
|
||||
"eq": "= ?",
|
||||
"ne": "!= ?",
|
||||
"startswith": "LIKE BINARY ?",
|
||||
"endswith": "LIKE BINARY ?",
|
||||
"istartswith": "LIKE ?",
|
||||
|
@ -29,6 +29,8 @@ var postgresOperators = map[string]string{
|
||||
"gte": ">= ?",
|
||||
"lt": "< ?",
|
||||
"lte": "<= ?",
|
||||
"eq": "= ?",
|
||||
"ne": "!= ?",
|
||||
"startswith": "LIKE ?",
|
||||
"endswith": "LIKE ?",
|
||||
"istartswith": "LIKE UPPER(?)",
|
||||
|
@ -29,6 +29,8 @@ var sqliteOperators = map[string]string{
|
||||
"gte": ">= ?",
|
||||
"lt": "< ?",
|
||||
"lte": "<= ?",
|
||||
"eq": "= ?",
|
||||
"ne": "!= ?",
|
||||
"startswith": "LIKE ? ESCAPE '\\'",
|
||||
"endswith": "LIKE ? ESCAPE '\\'",
|
||||
"istartswith": "LIKE ? ESCAPE '\\'",
|
||||
|
@ -116,6 +116,7 @@ type fieldInfo struct {
|
||||
null bool
|
||||
index bool
|
||||
unique bool
|
||||
colDefault bool
|
||||
initial StrTo
|
||||
size int
|
||||
auto_now bool
|
||||
@ -280,6 +281,11 @@ checkType:
|
||||
fi.pk = attrs["pk"]
|
||||
fi.unique = attrs["unique"]
|
||||
|
||||
// Mark object property if there is attribute "default" in the orm configuration
|
||||
if _, ok := tags["default"]; ok {
|
||||
fi.colDefault = true
|
||||
}
|
||||
|
||||
switch fieldType {
|
||||
case RelManyToMany, RelReverseMany, RelReverseOne:
|
||||
fi.null = false
|
||||
|
@ -242,14 +242,14 @@ type User struct {
|
||||
|
||||
func (u *User) TableIndex() [][]string {
|
||||
return [][]string{
|
||||
[]string{"Id", "UserName"},
|
||||
[]string{"Id", "Created"},
|
||||
{"Id", "UserName"},
|
||||
{"Id", "Created"},
|
||||
}
|
||||
}
|
||||
|
||||
func (u *User) TableUnique() [][]string {
|
||||
return [][]string{
|
||||
[]string{"UserName", "Email"},
|
||||
{"UserName", "Email"},
|
||||
}
|
||||
}
|
||||
|
||||
@ -287,7 +287,7 @@ type Post struct {
|
||||
|
||||
func (u *Post) TableIndex() [][]string {
|
||||
return [][]string{
|
||||
[]string{"Id", "Created"},
|
||||
{"Id", "Created"},
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -489,10 +489,6 @@ func (o *orm) Driver() Driver {
|
||||
return driver(o.alias.Name)
|
||||
}
|
||||
|
||||
func (o *orm) GetDB() dbQuerier {
|
||||
panic(ErrNotImplement)
|
||||
}
|
||||
|
||||
// create new orm
|
||||
func NewOrm() Ormer {
|
||||
BootStrap() // execute only once
|
||||
|
@ -115,23 +115,21 @@ func (o querySet) OrderBy(exprs ...string) QuerySeter {
|
||||
// set relation model to query together.
|
||||
// it will query relation models and assign to parent model.
|
||||
func (o querySet) RelatedSel(params ...interface{}) QuerySeter {
|
||||
var related []string
|
||||
if len(params) == 0 {
|
||||
o.relDepth = DefaultRelsDepth
|
||||
} else {
|
||||
for _, p := range params {
|
||||
switch val := p.(type) {
|
||||
case string:
|
||||
related = append(o.related, val)
|
||||
case int:
|
||||
o.relDepth = val
|
||||
default:
|
||||
panic(fmt.Errorf("<QuerySeter.RelatedSel> wrong param kind: %v", val))
|
||||
}
|
||||
}
|
||||
}
|
||||
o.related = related
|
||||
return &o
|
||||
if len(params) == 0 {
|
||||
o.relDepth = DefaultRelsDepth
|
||||
} else {
|
||||
for _, p := range params {
|
||||
switch val := p.(type) {
|
||||
case string:
|
||||
o.related = append(o.related, val)
|
||||
case int:
|
||||
o.relDepth = val
|
||||
default:
|
||||
panic(fmt.Errorf("<QuerySeter.RelatedSel> wrong param kind: %v", val))
|
||||
}
|
||||
}
|
||||
}
|
||||
return &o
|
||||
}
|
||||
|
||||
// set condition to QuerySeter.
|
||||
|
@ -585,7 +585,7 @@ func (o *rawSet) readValues(container interface{}, needCols []string) (int64, er
|
||||
|
||||
cols = columns
|
||||
refs = make([]interface{}, len(cols))
|
||||
for i, _ := range refs {
|
||||
for i := range refs {
|
||||
var ref sql.NullString
|
||||
refs[i] = &ref
|
||||
|
||||
@ -711,7 +711,7 @@ func (o *rawSet) queryRowsTo(container interface{}, keyCol, valueCol string) (in
|
||||
} else {
|
||||
cols = columns
|
||||
refs = make([]interface{}, len(cols))
|
||||
for i, _ := range refs {
|
||||
for i := range refs {
|
||||
if keyCol == cols[i] {
|
||||
keyIndex = i
|
||||
}
|
||||
|
@ -586,29 +586,29 @@ func TestInsertTestData(t *testing.T) {
|
||||
throwFail(t, AssertIs(id, 4))
|
||||
|
||||
tags := []*Tag{
|
||||
&Tag{Name: "golang", BestPost: &Post{Id: 2}},
|
||||
&Tag{Name: "example"},
|
||||
&Tag{Name: "format"},
|
||||
&Tag{Name: "c++"},
|
||||
{Name: "golang", BestPost: &Post{Id: 2}},
|
||||
{Name: "example"},
|
||||
{Name: "format"},
|
||||
{Name: "c++"},
|
||||
}
|
||||
|
||||
posts := []*Post{
|
||||
&Post{User: users[0], Tags: []*Tag{tags[0]}, Title: "Introduction", Content: `Go is a new language. Although it borrows ideas from existing languages, it has unusual properties that make effective Go programs different in character from programs written in its relatives. A straightforward translation of a C++ or Java program into Go is unlikely to produce a satisfactory result—Java programs are written in Java, not Go. On the other hand, thinking about the problem from a Go perspective could produce a successful but quite different program. In other words, to write Go well, it's important to understand its properties and idioms. It's also important to know the established conventions for programming in Go, such as naming, formatting, program construction, and so on, so that programs you write will be easy for other Go programmers to understand.
|
||||
{User: users[0], Tags: []*Tag{tags[0]}, Title: "Introduction", Content: `Go is a new language. Although it borrows ideas from existing languages, it has unusual properties that make effective Go programs different in character from programs written in its relatives. A straightforward translation of a C++ or Java program into Go is unlikely to produce a satisfactory result—Java programs are written in Java, not Go. On the other hand, thinking about the problem from a Go perspective could produce a successful but quite different program. In other words, to write Go well, it's important to understand its properties and idioms. It's also important to know the established conventions for programming in Go, such as naming, formatting, program construction, and so on, so that programs you write will be easy for other Go programmers to understand.
|
||||
This document gives tips for writing clear, idiomatic Go code. It augments the language specification, the Tour of Go, and How to Write Go Code, all of which you should read first.`},
|
||||
&Post{User: users[1], Tags: []*Tag{tags[0], tags[1]}, Title: "Examples", Content: `The Go package sources are intended to serve not only as the core library but also as examples of how to use the language. Moreover, many of the packages contain working, self-contained executable examples you can run directly from the golang.org web site, such as this one (click on the word "Example" to open it up). If you have a question about how to approach a problem or how something might be implemented, the documentation, code and examples in the library can provide answers, ideas and background.`},
|
||||
&Post{User: users[1], Tags: []*Tag{tags[0], tags[2]}, Title: "Formatting", Content: `Formatting issues are the most contentious but the least consequential. People can adapt to different formatting styles but it's better if they don't have to, and less time is devoted to the topic if everyone adheres to the same style. The problem is how to approach this Utopia without a long prescriptive style guide.
|
||||
{User: users[1], Tags: []*Tag{tags[0], tags[1]}, Title: "Examples", Content: `The Go package sources are intended to serve not only as the core library but also as examples of how to use the language. Moreover, many of the packages contain working, self-contained executable examples you can run directly from the golang.org web site, such as this one (click on the word "Example" to open it up). If you have a question about how to approach a problem or how something might be implemented, the documentation, code and examples in the library can provide answers, ideas and background.`},
|
||||
{User: users[1], Tags: []*Tag{tags[0], tags[2]}, Title: "Formatting", Content: `Formatting issues are the most contentious but the least consequential. People can adapt to different formatting styles but it's better if they don't have to, and less time is devoted to the topic if everyone adheres to the same style. The problem is how to approach this Utopia without a long prescriptive style guide.
|
||||
With Go we take an unusual approach and let the machine take care of most formatting issues. The gofmt program (also available as go fmt, which operates at the package level rather than source file level) reads a Go program and emits the source in a standard style of indentation and vertical alignment, retaining and if necessary reformatting comments. If you want to know how to handle some new layout situation, run gofmt; if the answer doesn't seem right, rearrange your program (or file a bug about gofmt), don't work around it.`},
|
||||
&Post{User: users[2], Tags: []*Tag{tags[3]}, Title: "Commentary", Content: `Go provides C-style /* */ block comments and C++-style // line comments. Line comments are the norm; block comments appear mostly as package comments, but are useful within an expression or to disable large swaths of code.
|
||||
{User: users[2], Tags: []*Tag{tags[3]}, Title: "Commentary", Content: `Go provides C-style /* */ block comments and C++-style // line comments. Line comments are the norm; block comments appear mostly as package comments, but are useful within an expression or to disable large swaths of code.
|
||||
The program—and web server—godoc processes Go source files to extract documentation about the contents of the package. Comments that appear before top-level declarations, with no intervening newlines, are extracted along with the declaration to serve as explanatory text for the item. The nature and style of these comments determines the quality of the documentation godoc produces.`},
|
||||
}
|
||||
|
||||
comments := []*Comment{
|
||||
&Comment{Post: posts[0], Content: "a comment"},
|
||||
&Comment{Post: posts[1], Content: "yes"},
|
||||
&Comment{Post: posts[1]},
|
||||
&Comment{Post: posts[1]},
|
||||
&Comment{Post: posts[2]},
|
||||
&Comment{Post: posts[2]},
|
||||
{Post: posts[0], Content: "a comment"},
|
||||
{Post: posts[1], Content: "yes"},
|
||||
{Post: posts[1]},
|
||||
{Post: posts[1]},
|
||||
{Post: posts[2]},
|
||||
{Post: posts[2]},
|
||||
}
|
||||
|
||||
for _, tag := range tags {
|
||||
@ -1248,7 +1248,7 @@ func TestQueryM2M(t *testing.T) {
|
||||
post := Post{Id: 4}
|
||||
m2m := dORM.QueryM2M(&post, "Tags")
|
||||
|
||||
tag1 := []*Tag{&Tag{Name: "TestTag1"}, &Tag{Name: "TestTag2"}}
|
||||
tag1 := []*Tag{{Name: "TestTag1"}, {Name: "TestTag2"}}
|
||||
tag2 := &Tag{Name: "TestTag3"}
|
||||
tag3 := []interface{}{&Tag{Name: "TestTag4"}}
|
||||
|
||||
@ -1311,7 +1311,7 @@ func TestQueryM2M(t *testing.T) {
|
||||
|
||||
m2m = dORM.QueryM2M(&tag, "Posts")
|
||||
|
||||
post1 := []*Post{&Post{Title: "TestPost1"}, &Post{Title: "TestPost2"}}
|
||||
post1 := []*Post{{Title: "TestPost1"}, {Title: "TestPost2"}}
|
||||
post2 := &Post{Title: "TestPost3"}
|
||||
post3 := []interface{}{&Post{Title: "TestPost4"}}
|
||||
|
||||
|
@ -51,7 +51,6 @@ type Ormer interface {
|
||||
Rollback() error
|
||||
Raw(string, ...interface{}) RawSeter
|
||||
Driver() Driver
|
||||
GetDB() dbQuerier
|
||||
}
|
||||
|
||||
// insert prepared statement
|
||||
|
@ -195,7 +195,7 @@ func snakeString(s string) string {
|
||||
}
|
||||
data = append(data, d)
|
||||
}
|
||||
return strings.ToLower(string(data[:len(data)]))
|
||||
return strings.ToLower(string(data[:]))
|
||||
}
|
||||
|
||||
// camel string, xx_yy to XxYy
|
||||
@ -220,7 +220,7 @@ func camelString(s string) string {
|
||||
}
|
||||
data = append(data, d)
|
||||
}
|
||||
return string(data[:len(data)])
|
||||
return string(data[:])
|
||||
}
|
||||
|
||||
type argString []string
|
||||
|
13
parser.go
13
parser.go
@ -24,6 +24,7 @@ import (
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/astaxie/beego/utils"
|
||||
@ -36,7 +37,7 @@ import (
|
||||
)
|
||||
|
||||
func init() {
|
||||
{{.globalinfo}}
|
||||
{{.globalinfo}}
|
||||
}
|
||||
`
|
||||
|
||||
@ -57,7 +58,7 @@ func parserPkg(pkgRealpath, pkgpath string) error {
|
||||
rep := strings.NewReplacer("/", "_", ".", "_")
|
||||
commentFilename = COMMENTFL + rep.Replace(pkgpath) + ".go"
|
||||
if !compareFile(pkgRealpath) {
|
||||
Info(pkgRealpath + " don't has updated")
|
||||
Info(pkgRealpath + " has not changed, not reloading")
|
||||
return nil
|
||||
}
|
||||
genInfoList = make(map[string][]ControllerComments)
|
||||
@ -129,7 +130,13 @@ func genRouterCode() {
|
||||
os.Mkdir(path.Join(workPath, "routers"), 0755)
|
||||
Info("generate router from comments")
|
||||
var globalinfo string
|
||||
for k, cList := range genInfoList {
|
||||
sortKey := make([]string, 0)
|
||||
for k, _ := range genInfoList {
|
||||
sortKey = append(sortKey, k)
|
||||
}
|
||||
sort.Strings(sortKey)
|
||||
for _, k := range sortKey {
|
||||
cList := genInfoList[k]
|
||||
for _, c := range cList {
|
||||
allmethod := "nil"
|
||||
if len(c.AllowHTTPMethods) > 0 {
|
||||
|
@ -217,6 +217,7 @@ func Allow(opts *Options) beego.FilterFunc {
|
||||
ctx.Output.Header(key, value)
|
||||
}
|
||||
ctx.Output.SetStatus(http.StatusOK)
|
||||
ctx.WriteString("")
|
||||
return
|
||||
}
|
||||
headers = opts.Header(origin)
|
||||
|
118
router.go
118
router.go
@ -30,7 +30,6 @@ import (
|
||||
"time"
|
||||
|
||||
beecontext "github.com/astaxie/beego/context"
|
||||
"github.com/astaxie/beego/middleware"
|
||||
"github.com/astaxie/beego/toolbox"
|
||||
"github.com/astaxie/beego/utils"
|
||||
)
|
||||
@ -89,7 +88,7 @@ func (l *logFilter) Filter(ctx *beecontext.Context) bool {
|
||||
if requestPath == "/favicon.ico" || requestPath == "/robots.txt" {
|
||||
return true
|
||||
}
|
||||
for prefix, _ := range StaticDir {
|
||||
for prefix := range StaticDir {
|
||||
if strings.HasPrefix(requestPath, prefix) {
|
||||
return true
|
||||
}
|
||||
@ -153,7 +152,7 @@ func (p *ControllerRegistor) Add(pattern string, c ControllerInterface, mappingM
|
||||
if val := reflectVal.MethodByName(colon[1]); val.IsValid() {
|
||||
methods[strings.ToUpper(m)] = colon[1]
|
||||
} else {
|
||||
panic(colon[1] + " method doesn't exist in the controller " + t.Name())
|
||||
panic("'" + colon[1] + "' method doesn't exist in the controller " + t.Name())
|
||||
}
|
||||
} else {
|
||||
panic(v + " is an invalid method mapping. Method doesn't exist " + m)
|
||||
@ -172,7 +171,7 @@ func (p *ControllerRegistor) Add(pattern string, c ControllerInterface, mappingM
|
||||
p.addToRouter(m, pattern, route)
|
||||
}
|
||||
} else {
|
||||
for k, _ := range methods {
|
||||
for k := range methods {
|
||||
if k == "*" {
|
||||
for _, m := range HTTPMETHOD {
|
||||
p.addToRouter(m, pattern, route)
|
||||
@ -333,7 +332,7 @@ func (p *ControllerRegistor) AddMethod(method, pattern string, f FilterFunc) {
|
||||
methods[strings.ToUpper(method)] = strings.ToUpper(method)
|
||||
}
|
||||
route.methods = methods
|
||||
for k, _ := range methods {
|
||||
for k := range methods {
|
||||
if k == "*" {
|
||||
for _, m := range HTTPMETHOD {
|
||||
p.addToRouter(m, pattern, route)
|
||||
@ -429,7 +428,7 @@ func (p *ControllerRegistor) insertFilterRouter(pos int, mr *FilterRouter) error
|
||||
|
||||
// UrlFor does another controller handler in this request function.
|
||||
// it can access any controller method.
|
||||
func (p *ControllerRegistor) UrlFor(endpoint string, values ...string) string {
|
||||
func (p *ControllerRegistor) UrlFor(endpoint string, values ...interface{}) string {
|
||||
paths := strings.Split(endpoint, ".")
|
||||
if len(paths) <= 1 {
|
||||
Warn("urlfor endpoint must like path.controller.method")
|
||||
@ -444,9 +443,9 @@ func (p *ControllerRegistor) UrlFor(endpoint string, values ...string) string {
|
||||
key := ""
|
||||
for k, v := range values {
|
||||
if k%2 == 0 {
|
||||
key = v
|
||||
key = fmt.Sprint(v)
|
||||
} else {
|
||||
params[key] = v
|
||||
params[key] = fmt.Sprint(v)
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -577,7 +576,6 @@ func (p *ControllerRegistor) geturl(t *Tree, url, controllName, methodName strin
|
||||
|
||||
// Implement http.Handler interface.
|
||||
func (p *ControllerRegistor) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
|
||||
defer p.recoverPanic(rw, r)
|
||||
starttime := time.Now()
|
||||
var runrouter reflect.Type
|
||||
var findrouter bool
|
||||
@ -600,6 +598,8 @@ func (p *ControllerRegistor) ServeHTTP(rw http.ResponseWriter, r *http.Request)
|
||||
context.Output.Context = context
|
||||
context.Output.EnableGzip = EnableGzip
|
||||
|
||||
defer p.recoverPanic(context)
|
||||
|
||||
var urlPath string
|
||||
if !RouterCaseSensitive {
|
||||
urlPath = strings.ToLower(r.URL.Path)
|
||||
@ -611,17 +611,21 @@ func (p *ControllerRegistor) ServeHTTP(rw http.ResponseWriter, r *http.Request)
|
||||
if p.enableFilter {
|
||||
if l, ok := p.filters[pos]; ok {
|
||||
for _, filterR := range l {
|
||||
if ok, p := filterR.ValidRouter(urlPath); ok {
|
||||
context.Input.Params = p
|
||||
filterR.filterFunc(context)
|
||||
if filterR.returnOnOutput && w.started {
|
||||
return true
|
||||
if filterR.returnOnOutput && w.started {
|
||||
return true
|
||||
}
|
||||
if ok, params := filterR.ValidRouter(urlPath); ok {
|
||||
for k, v := range params {
|
||||
context.Input.Params[k] = v
|
||||
}
|
||||
filterR.filterFunc(context)
|
||||
}
|
||||
if filterR.returnOnOutput && w.started {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
@ -648,7 +652,7 @@ func (p *ControllerRegistor) ServeHTTP(rw http.ResponseWriter, r *http.Request)
|
||||
context.Input.CruSession, err = GlobalSessions.SessionStart(w, r)
|
||||
if err != nil {
|
||||
Error(err)
|
||||
middleware.Exception("503", rw, r, "")
|
||||
exception("503", context)
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
@ -703,7 +707,7 @@ func (p *ControllerRegistor) ServeHTTP(rw http.ResponseWriter, r *http.Request)
|
||||
|
||||
//if no matches to url, throw a not found exception
|
||||
if !findrouter {
|
||||
middleware.Exception("404", rw, r, "")
|
||||
exception("404", context)
|
||||
goto Admin
|
||||
}
|
||||
|
||||
@ -719,7 +723,7 @@ func (p *ControllerRegistor) ServeHTTP(rw http.ResponseWriter, r *http.Request)
|
||||
isRunable = true
|
||||
routerInfo.runfunction(context)
|
||||
} else {
|
||||
middleware.Exception("405", rw, r, "Method Not Allowed")
|
||||
exception("405", context)
|
||||
goto Admin
|
||||
}
|
||||
} else if routerInfo.routerType == routerTypeHandler {
|
||||
@ -830,7 +834,7 @@ Admin:
|
||||
}
|
||||
}
|
||||
|
||||
if RunMode == "dev" {
|
||||
if RunMode == "dev" || AccessLogs {
|
||||
var devinfo string
|
||||
if findrouter {
|
||||
if routerInfo != nil {
|
||||
@ -852,68 +856,34 @@ Admin:
|
||||
}
|
||||
}
|
||||
|
||||
func (p *ControllerRegistor) recoverPanic(rw http.ResponseWriter, r *http.Request) {
|
||||
func (p *ControllerRegistor) recoverPanic(context *beecontext.Context) {
|
||||
if err := recover(); err != nil {
|
||||
if err == USERSTOPRUN {
|
||||
return
|
||||
}
|
||||
if he, ok := err.(middleware.HTTPException); ok {
|
||||
rw.WriteHeader(he.StatusCode)
|
||||
rw.Write([]byte(he.Description))
|
||||
// catch intented errors, only for HTTP 4XX and 5XX
|
||||
if !RecoverPanic {
|
||||
panic(err)
|
||||
} else {
|
||||
if RunMode == "dev" {
|
||||
if !RecoverPanic {
|
||||
panic(err)
|
||||
} else {
|
||||
if ErrorsShow {
|
||||
if handler, ok := middleware.ErrorMaps[fmt.Sprint(err)]; ok {
|
||||
handler(rw, r)
|
||||
return
|
||||
}
|
||||
}
|
||||
var stack string
|
||||
Critical("the request url is ", r.URL.Path)
|
||||
Critical("Handler crashed with error", err)
|
||||
for i := 1; ; i++ {
|
||||
_, file, line, ok := runtime.Caller(i)
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
Critical(fmt.Sprintf("%s:%d", file, line))
|
||||
stack = stack + fmt.Sprintln(fmt.Sprintf("%s:%d", file, line))
|
||||
}
|
||||
middleware.ShowErr(err, rw, r, stack)
|
||||
}
|
||||
} else {
|
||||
if !RecoverPanic {
|
||||
panic(err)
|
||||
} else {
|
||||
// in production model show all infomation
|
||||
if ErrorsShow {
|
||||
if handler, ok := middleware.ErrorMaps[fmt.Sprint(err)]; ok {
|
||||
handler(rw, r)
|
||||
return
|
||||
} else if handler, ok := middleware.ErrorMaps["503"]; ok {
|
||||
handler(rw, r)
|
||||
return
|
||||
} else {
|
||||
rw.Write([]byte(fmt.Sprint(err)))
|
||||
}
|
||||
} else {
|
||||
Critical("the request url is ", r.URL.Path)
|
||||
Critical("Handler crashed with error", err)
|
||||
for i := 1; ; i++ {
|
||||
_, file, line, ok := runtime.Caller(i)
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
Critical(fmt.Sprintf("%s:%d", file, line))
|
||||
}
|
||||
}
|
||||
if ErrorsShow {
|
||||
if _, ok := ErrorMaps[fmt.Sprint(err)]; ok {
|
||||
exception(fmt.Sprint(err), context)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var stack string
|
||||
Critical("the request url is ", context.Input.Url())
|
||||
Critical("Handler crashed with error", err)
|
||||
for i := 1; ; i++ {
|
||||
_, file, line, ok := runtime.Caller(i)
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
Critical(fmt.Sprintf("%s:%d", file, line))
|
||||
stack = stack + fmt.Sprintln(fmt.Sprintf("%s:%d", file, line))
|
||||
}
|
||||
if RunMode == "dev" {
|
||||
showErr(err, context, stack)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -444,7 +444,7 @@ func TestFilterAfterExec(t *testing.T) {
|
||||
mux := NewControllerRegister()
|
||||
mux.InsertFilter(url, BeforeRouter, beegoFilterNoOutput)
|
||||
mux.InsertFilter(url, BeforeExec, beegoFilterNoOutput)
|
||||
mux.InsertFilter(url, AfterExec, beegoAfterExec1)
|
||||
mux.InsertFilter(url, AfterExec, beegoAfterExec1, false)
|
||||
|
||||
mux.Get(url, beegoFilterFunc)
|
||||
|
||||
@ -506,7 +506,7 @@ func TestFilterFinishRouterMultiFirstOnly(t *testing.T) {
|
||||
url := "/finishRouterMultiFirstOnly"
|
||||
|
||||
mux := NewControllerRegister()
|
||||
mux.InsertFilter(url, FinishRouter, beegoFinishRouter1)
|
||||
mux.InsertFilter(url, FinishRouter, beegoFinishRouter1, false)
|
||||
mux.InsertFilter(url, FinishRouter, beegoFinishRouter2)
|
||||
|
||||
mux.Get(url, beegoFilterFunc)
|
||||
@ -534,7 +534,7 @@ func TestFilterFinishRouterMulti(t *testing.T) {
|
||||
|
||||
mux := NewControllerRegister()
|
||||
mux.InsertFilter(url, FinishRouter, beegoFinishRouter1, false)
|
||||
mux.InsertFilter(url, FinishRouter, beegoFinishRouter2)
|
||||
mux.InsertFilter(url, FinishRouter, beegoFinishRouter2, false)
|
||||
|
||||
mux.Get(url, beegoFilterFunc)
|
||||
|
||||
|
@ -2,6 +2,8 @@ package session
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/astaxie/beego/session"
|
||||
@ -74,19 +76,29 @@ func (ls *LedisSessionStore) SessionRelease(w http.ResponseWriter) {
|
||||
type LedisProvider struct {
|
||||
maxlifetime int64
|
||||
savePath string
|
||||
db int
|
||||
}
|
||||
|
||||
// init ledis session
|
||||
// savepath like ledis server saveDataPath,pool size
|
||||
// e.g. 127.0.0.1:6379,100,astaxie
|
||||
func (lp *LedisProvider) SessionInit(maxlifetime int64, savePath string) error {
|
||||
var err error
|
||||
lp.maxlifetime = maxlifetime
|
||||
lp.savePath = savePath
|
||||
configs := strings.Split(savePath, ",")
|
||||
if len(configs) == 1 {
|
||||
lp.savePath = configs[0]
|
||||
} else if len(configs) == 2 {
|
||||
lp.savePath = configs[0]
|
||||
lp.db, err = strconv.Atoi(configs[1])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
cfg := new(config.Config)
|
||||
cfg.DataDir = lp.savePath
|
||||
var err error
|
||||
nowLedis, err := ledis.Open(cfg)
|
||||
c, err = nowLedis.Select(0)
|
||||
c, err = nowLedis.Select(lp.db)
|
||||
if err != nil {
|
||||
println(err)
|
||||
return nil
|
||||
|
@ -129,8 +129,9 @@ func (rp *MemProvider) SessionRead(sid string) (session.SessionStore, error) {
|
||||
}
|
||||
}
|
||||
item, err := client.Get(sid)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
if err != nil && err == memcache.ErrCacheMiss {
|
||||
rs := &MemcacheSessionStore{sid: sid, values: make(map[interface{}]interface{}), maxlifetime: rp.maxlifetime}
|
||||
return rs, nil
|
||||
}
|
||||
var kv map[interface{}]interface{}
|
||||
if len(item.Value) == 0 {
|
||||
@ -141,7 +142,6 @@ func (rp *MemProvider) SessionRead(sid string) (session.SessionStore, error) {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
rs := &MemcacheSessionStore{sid: sid, values: kv, maxlifetime: rp.maxlifetime}
|
||||
return rs, nil
|
||||
}
|
||||
@ -179,7 +179,6 @@ func (rp *MemProvider) SessionRegenerate(oldsid, sid string) (session.SessionSto
|
||||
} else {
|
||||
client.Delete(oldsid)
|
||||
item.Key = sid
|
||||
item.Value = item.Value
|
||||
item.Expiration = int32(rp.maxlifetime)
|
||||
client.Set(item)
|
||||
contain = item.Value
|
||||
|
@ -21,7 +21,7 @@
|
||||
// mysql session support need create table as sql:
|
||||
// CREATE TABLE `session` (
|
||||
// `session_key` char(64) NOT NULL,
|
||||
// session_data` blob,
|
||||
// `session_data` blob,
|
||||
// `session_expiry` int(11) unsigned NOT NULL,
|
||||
// PRIMARY KEY (`session_key`)
|
||||
// ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
|
||||
|
@ -118,12 +118,13 @@ type RedisProvider struct {
|
||||
savePath string
|
||||
poolsize int
|
||||
password string
|
||||
dbNum int
|
||||
poollist *redis.Pool
|
||||
}
|
||||
|
||||
// init redis session
|
||||
// savepath like redis server addr,pool size,password
|
||||
// e.g. 127.0.0.1:6379,100,astaxie
|
||||
// savepath like redis server addr,pool size,password,dbnum
|
||||
// e.g. 127.0.0.1:6379,100,astaxie,0
|
||||
func (rp *RedisProvider) SessionInit(maxlifetime int64, savePath string) error {
|
||||
rp.maxlifetime = maxlifetime
|
||||
configs := strings.Split(savePath, ",")
|
||||
@ -143,6 +144,16 @@ func (rp *RedisProvider) SessionInit(maxlifetime int64, savePath string) error {
|
||||
if len(configs) > 2 {
|
||||
rp.password = configs[2]
|
||||
}
|
||||
if len(configs) > 3 {
|
||||
dbnum, err := strconv.Atoi(configs[3])
|
||||
if err != nil || dbnum < 0 {
|
||||
rp.dbNum = 0
|
||||
} else {
|
||||
rp.dbNum = dbnum
|
||||
}
|
||||
} else {
|
||||
rp.dbNum = 0
|
||||
}
|
||||
rp.poollist = redis.NewPool(func() (redis.Conn, error) {
|
||||
c, err := redis.Dial("tcp", rp.savePath)
|
||||
if err != nil {
|
||||
@ -154,6 +165,11 @@ func (rp *RedisProvider) SessionInit(maxlifetime int64, savePath string) error {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
_, err = c.Do("SELECT", rp.dbNum)
|
||||
if err != nil {
|
||||
c.Close()
|
||||
return nil, err
|
||||
}
|
||||
return c, err
|
||||
}, rp.poolsize)
|
||||
|
||||
|
@ -1,199 +1,199 @@
|
||||
// Copyright 2014 beego Author. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package session
|
||||
|
||||
import (
|
||||
"container/list"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var mempder = &MemProvider{list: list.New(), sessions: make(map[string]*list.Element)}
|
||||
|
||||
// memory session store.
|
||||
// it saved sessions in a map in memory.
|
||||
type MemSessionStore struct {
|
||||
sid string //session id
|
||||
timeAccessed time.Time //last access time
|
||||
value map[interface{}]interface{} //session store
|
||||
lock sync.RWMutex
|
||||
}
|
||||
|
||||
// set value to memory session
|
||||
func (st *MemSessionStore) Set(key, value interface{}) error {
|
||||
st.lock.Lock()
|
||||
defer st.lock.Unlock()
|
||||
st.value[key] = value
|
||||
return nil
|
||||
}
|
||||
|
||||
// get value from memory session by key
|
||||
func (st *MemSessionStore) Get(key interface{}) interface{} {
|
||||
st.lock.RLock()
|
||||
defer st.lock.RUnlock()
|
||||
if v, ok := st.value[key]; ok {
|
||||
return v
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// delete in memory session by key
|
||||
func (st *MemSessionStore) Delete(key interface{}) error {
|
||||
st.lock.Lock()
|
||||
defer st.lock.Unlock()
|
||||
delete(st.value, key)
|
||||
return nil
|
||||
}
|
||||
|
||||
// clear all values in memory session
|
||||
func (st *MemSessionStore) Flush() error {
|
||||
st.lock.Lock()
|
||||
defer st.lock.Unlock()
|
||||
st.value = make(map[interface{}]interface{})
|
||||
return nil
|
||||
}
|
||||
|
||||
// get this id of memory session store
|
||||
func (st *MemSessionStore) SessionID() string {
|
||||
return st.sid
|
||||
}
|
||||
|
||||
// Implement method, no used.
|
||||
func (st *MemSessionStore) SessionRelease(w http.ResponseWriter) {
|
||||
}
|
||||
|
||||
type MemProvider struct {
|
||||
lock sync.RWMutex // locker
|
||||
sessions map[string]*list.Element // map in memory
|
||||
list *list.List // for gc
|
||||
maxlifetime int64
|
||||
savePath string
|
||||
}
|
||||
|
||||
// init memory session
|
||||
func (pder *MemProvider) SessionInit(maxlifetime int64, savePath string) error {
|
||||
pder.maxlifetime = maxlifetime
|
||||
pder.savePath = savePath
|
||||
return nil
|
||||
}
|
||||
|
||||
// get memory session store by sid
|
||||
func (pder *MemProvider) SessionRead(sid string) (SessionStore, error) {
|
||||
pder.lock.RLock()
|
||||
if element, ok := pder.sessions[sid]; ok {
|
||||
go pder.SessionUpdate(sid)
|
||||
pder.lock.RUnlock()
|
||||
return element.Value.(*MemSessionStore), nil
|
||||
} else {
|
||||
pder.lock.RUnlock()
|
||||
pder.lock.Lock()
|
||||
newsess := &MemSessionStore{sid: sid, timeAccessed: time.Now(), value: make(map[interface{}]interface{})}
|
||||
element := pder.list.PushBack(newsess)
|
||||
pder.sessions[sid] = element
|
||||
pder.lock.Unlock()
|
||||
return newsess, nil
|
||||
}
|
||||
}
|
||||
|
||||
// check session store exist in memory session by sid
|
||||
func (pder *MemProvider) SessionExist(sid string) bool {
|
||||
pder.lock.RLock()
|
||||
defer pder.lock.RUnlock()
|
||||
if _, ok := pder.sessions[sid]; ok {
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// generate new sid for session store in memory session
|
||||
func (pder *MemProvider) SessionRegenerate(oldsid, sid string) (SessionStore, error) {
|
||||
pder.lock.RLock()
|
||||
if element, ok := pder.sessions[oldsid]; ok {
|
||||
go pder.SessionUpdate(oldsid)
|
||||
pder.lock.RUnlock()
|
||||
pder.lock.Lock()
|
||||
element.Value.(*MemSessionStore).sid = sid
|
||||
pder.sessions[sid] = element
|
||||
delete(pder.sessions, oldsid)
|
||||
pder.lock.Unlock()
|
||||
return element.Value.(*MemSessionStore), nil
|
||||
} else {
|
||||
pder.lock.RUnlock()
|
||||
pder.lock.Lock()
|
||||
newsess := &MemSessionStore{sid: sid, timeAccessed: time.Now(), value: make(map[interface{}]interface{})}
|
||||
element := pder.list.PushBack(newsess)
|
||||
pder.sessions[sid] = element
|
||||
pder.lock.Unlock()
|
||||
return newsess, nil
|
||||
}
|
||||
}
|
||||
|
||||
// delete session store in memory session by id
|
||||
func (pder *MemProvider) SessionDestroy(sid string) error {
|
||||
pder.lock.Lock()
|
||||
defer pder.lock.Unlock()
|
||||
if element, ok := pder.sessions[sid]; ok {
|
||||
delete(pder.sessions, sid)
|
||||
pder.list.Remove(element)
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// clean expired session stores in memory session
|
||||
func (pder *MemProvider) SessionGC() {
|
||||
pder.lock.RLock()
|
||||
for {
|
||||
element := pder.list.Back()
|
||||
if element == nil {
|
||||
break
|
||||
}
|
||||
if (element.Value.(*MemSessionStore).timeAccessed.Unix() + pder.maxlifetime) < time.Now().Unix() {
|
||||
pder.lock.RUnlock()
|
||||
pder.lock.Lock()
|
||||
pder.list.Remove(element)
|
||||
delete(pder.sessions, element.Value.(*MemSessionStore).sid)
|
||||
pder.lock.Unlock()
|
||||
pder.lock.RLock()
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
pder.lock.RUnlock()
|
||||
}
|
||||
|
||||
// get count number of memory session
|
||||
func (pder *MemProvider) SessionAll() int {
|
||||
return pder.list.Len()
|
||||
}
|
||||
|
||||
// expand time of session store by id in memory session
|
||||
func (pder *MemProvider) SessionUpdate(sid string) error {
|
||||
pder.lock.Lock()
|
||||
defer pder.lock.Unlock()
|
||||
if element, ok := pder.sessions[sid]; ok {
|
||||
element.Value.(*MemSessionStore).timeAccessed = time.Now()
|
||||
pder.list.MoveToFront(element)
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func init() {
|
||||
Register("memory", mempder)
|
||||
}
|
||||
// Copyright 2014 beego Author. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package session
|
||||
|
||||
import (
|
||||
"container/list"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var mempder = &MemProvider{list: list.New(), sessions: make(map[string]*list.Element)}
|
||||
|
||||
// memory session store.
|
||||
// it saved sessions in a map in memory.
|
||||
type MemSessionStore struct {
|
||||
sid string //session id
|
||||
timeAccessed time.Time //last access time
|
||||
value map[interface{}]interface{} //session store
|
||||
lock sync.RWMutex
|
||||
}
|
||||
|
||||
// set value to memory session
|
||||
func (st *MemSessionStore) Set(key, value interface{}) error {
|
||||
st.lock.Lock()
|
||||
defer st.lock.Unlock()
|
||||
st.value[key] = value
|
||||
return nil
|
||||
}
|
||||
|
||||
// get value from memory session by key
|
||||
func (st *MemSessionStore) Get(key interface{}) interface{} {
|
||||
st.lock.RLock()
|
||||
defer st.lock.RUnlock()
|
||||
if v, ok := st.value[key]; ok {
|
||||
return v
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// delete in memory session by key
|
||||
func (st *MemSessionStore) Delete(key interface{}) error {
|
||||
st.lock.Lock()
|
||||
defer st.lock.Unlock()
|
||||
delete(st.value, key)
|
||||
return nil
|
||||
}
|
||||
|
||||
// clear all values in memory session
|
||||
func (st *MemSessionStore) Flush() error {
|
||||
st.lock.Lock()
|
||||
defer st.lock.Unlock()
|
||||
st.value = make(map[interface{}]interface{})
|
||||
return nil
|
||||
}
|
||||
|
||||
// get this id of memory session store
|
||||
func (st *MemSessionStore) SessionID() string {
|
||||
return st.sid
|
||||
}
|
||||
|
||||
// Implement method, no used.
|
||||
func (st *MemSessionStore) SessionRelease(w http.ResponseWriter) {
|
||||
}
|
||||
|
||||
type MemProvider struct {
|
||||
lock sync.RWMutex // locker
|
||||
sessions map[string]*list.Element // map in memory
|
||||
list *list.List // for gc
|
||||
maxlifetime int64
|
||||
savePath string
|
||||
}
|
||||
|
||||
// init memory session
|
||||
func (pder *MemProvider) SessionInit(maxlifetime int64, savePath string) error {
|
||||
pder.maxlifetime = maxlifetime
|
||||
pder.savePath = savePath
|
||||
return nil
|
||||
}
|
||||
|
||||
// get memory session store by sid
|
||||
func (pder *MemProvider) SessionRead(sid string) (SessionStore, error) {
|
||||
pder.lock.RLock()
|
||||
if element, ok := pder.sessions[sid]; ok {
|
||||
go pder.SessionUpdate(sid)
|
||||
pder.lock.RUnlock()
|
||||
return element.Value.(*MemSessionStore), nil
|
||||
} else {
|
||||
pder.lock.RUnlock()
|
||||
pder.lock.Lock()
|
||||
newsess := &MemSessionStore{sid: sid, timeAccessed: time.Now(), value: make(map[interface{}]interface{})}
|
||||
element := pder.list.PushBack(newsess)
|
||||
pder.sessions[sid] = element
|
||||
pder.lock.Unlock()
|
||||
return newsess, nil
|
||||
}
|
||||
}
|
||||
|
||||
// check session store exist in memory session by sid
|
||||
func (pder *MemProvider) SessionExist(sid string) bool {
|
||||
pder.lock.RLock()
|
||||
defer pder.lock.RUnlock()
|
||||
if _, ok := pder.sessions[sid]; ok {
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// generate new sid for session store in memory session
|
||||
func (pder *MemProvider) SessionRegenerate(oldsid, sid string) (SessionStore, error) {
|
||||
pder.lock.RLock()
|
||||
if element, ok := pder.sessions[oldsid]; ok {
|
||||
go pder.SessionUpdate(oldsid)
|
||||
pder.lock.RUnlock()
|
||||
pder.lock.Lock()
|
||||
element.Value.(*MemSessionStore).sid = sid
|
||||
pder.sessions[sid] = element
|
||||
delete(pder.sessions, oldsid)
|
||||
pder.lock.Unlock()
|
||||
return element.Value.(*MemSessionStore), nil
|
||||
} else {
|
||||
pder.lock.RUnlock()
|
||||
pder.lock.Lock()
|
||||
newsess := &MemSessionStore{sid: sid, timeAccessed: time.Now(), value: make(map[interface{}]interface{})}
|
||||
element := pder.list.PushBack(newsess)
|
||||
pder.sessions[sid] = element
|
||||
pder.lock.Unlock()
|
||||
return newsess, nil
|
||||
}
|
||||
}
|
||||
|
||||
// delete session store in memory session by id
|
||||
func (pder *MemProvider) SessionDestroy(sid string) error {
|
||||
pder.lock.Lock()
|
||||
defer pder.lock.Unlock()
|
||||
if element, ok := pder.sessions[sid]; ok {
|
||||
delete(pder.sessions, sid)
|
||||
pder.list.Remove(element)
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// clean expired session stores in memory session
|
||||
func (pder *MemProvider) SessionGC() {
|
||||
pder.lock.RLock()
|
||||
for {
|
||||
element := pder.list.Back()
|
||||
if element == nil {
|
||||
break
|
||||
}
|
||||
if (element.Value.(*MemSessionStore).timeAccessed.Unix() + pder.maxlifetime) < time.Now().Unix() {
|
||||
pder.lock.RUnlock()
|
||||
pder.lock.Lock()
|
||||
pder.list.Remove(element)
|
||||
delete(pder.sessions, element.Value.(*MemSessionStore).sid)
|
||||
pder.lock.Unlock()
|
||||
pder.lock.RLock()
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
pder.lock.RUnlock()
|
||||
}
|
||||
|
||||
// get count number of memory session
|
||||
func (pder *MemProvider) SessionAll() int {
|
||||
return pder.list.Len()
|
||||
}
|
||||
|
||||
// expand time of session store by id in memory session
|
||||
func (pder *MemProvider) SessionUpdate(sid string) error {
|
||||
pder.lock.Lock()
|
||||
defer pder.lock.Unlock()
|
||||
if element, ok := pder.sessions[sid]; ok {
|
||||
element.Value.(*MemSessionStore).timeAccessed = time.Now()
|
||||
pder.list.MoveToFront(element)
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func init() {
|
||||
Register("memory", mempder)
|
||||
}
|
||||
|
@ -143,14 +143,17 @@ func (manager *Manager) SessionStart(w http.ResponseWriter, r *http.Request) (se
|
||||
return nil, errs
|
||||
}
|
||||
session, err = manager.provider.SessionRead(sid)
|
||||
cookie = &http.Cookie{Name: manager.config.CookieName,
|
||||
cookie = &http.Cookie{
|
||||
Name: manager.config.CookieName,
|
||||
Value: url.QueryEscape(sid),
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
Secure: manager.config.Secure,
|
||||
Domain: manager.config.Domain}
|
||||
if manager.config.CookieLifeTime >= 0 {
|
||||
Secure: manager.isSecure(r),
|
||||
Domain: manager.config.Domain,
|
||||
}
|
||||
if manager.config.CookieLifeTime > 0 {
|
||||
cookie.MaxAge = manager.config.CookieLifeTime
|
||||
cookie.Expires = time.Now().Add(time.Duration(manager.config.CookieLifeTime) * time.Second)
|
||||
}
|
||||
if manager.config.EnableSetCookie {
|
||||
http.SetCookie(w, cookie)
|
||||
@ -169,14 +172,17 @@ func (manager *Manager) SessionStart(w http.ResponseWriter, r *http.Request) (se
|
||||
return nil, err
|
||||
}
|
||||
session, err = manager.provider.SessionRead(sid)
|
||||
cookie = &http.Cookie{Name: manager.config.CookieName,
|
||||
cookie = &http.Cookie{
|
||||
Name: manager.config.CookieName,
|
||||
Value: url.QueryEscape(sid),
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
Secure: manager.config.Secure,
|
||||
Domain: manager.config.Domain}
|
||||
if manager.config.CookieLifeTime >= 0 {
|
||||
Secure: manager.isSecure(r),
|
||||
Domain: manager.config.Domain,
|
||||
}
|
||||
if manager.config.CookieLifeTime > 0 {
|
||||
cookie.MaxAge = manager.config.CookieLifeTime
|
||||
cookie.Expires = time.Now().Add(time.Duration(manager.config.CookieLifeTime) * time.Second)
|
||||
}
|
||||
if manager.config.EnableSetCookie {
|
||||
http.SetCookie(w, cookie)
|
||||
@ -231,7 +237,7 @@ func (manager *Manager) SessionRegenerateId(w http.ResponseWriter, r *http.Reque
|
||||
Value: url.QueryEscape(sid),
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
Secure: manager.config.Secure,
|
||||
Secure: manager.isSecure(r),
|
||||
Domain: manager.config.Domain,
|
||||
}
|
||||
} else {
|
||||
@ -241,8 +247,9 @@ func (manager *Manager) SessionRegenerateId(w http.ResponseWriter, r *http.Reque
|
||||
cookie.HttpOnly = true
|
||||
cookie.Path = "/"
|
||||
}
|
||||
if manager.config.CookieLifeTime >= 0 {
|
||||
if manager.config.CookieLifeTime > 0 {
|
||||
cookie.MaxAge = manager.config.CookieLifeTime
|
||||
cookie.Expires = time.Now().Add(time.Duration(manager.config.CookieLifeTime) * time.Second)
|
||||
}
|
||||
http.SetCookie(w, cookie)
|
||||
r.AddCookie(cookie)
|
||||
@ -267,3 +274,17 @@ func (manager *Manager) sessionId(r *http.Request) (string, error) {
|
||||
}
|
||||
return hex.EncodeToString(b), nil
|
||||
}
|
||||
|
||||
// Set cookie with https.
|
||||
func (manager *Manager) isSecure(req *http.Request) bool {
|
||||
if !manager.config.Secure {
|
||||
return false
|
||||
}
|
||||
if req.URL.Scheme != "" {
|
||||
return req.URL.Scheme == "https"
|
||||
}
|
||||
if req.TLS == nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
@ -22,7 +22,6 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/astaxie/beego/context"
|
||||
"github.com/astaxie/beego/middleware"
|
||||
"github.com/astaxie/beego/utils"
|
||||
)
|
||||
|
||||
@ -59,7 +58,7 @@ func serverStaticRouter(ctx *context.Context) {
|
||||
finfo, err := os.Stat(file)
|
||||
if err != nil {
|
||||
if RunMode == "dev" {
|
||||
Warn(err)
|
||||
Warn("Can't find the file:", file, err)
|
||||
}
|
||||
http.NotFound(ctx.ResponseWriter, ctx.Request)
|
||||
return
|
||||
@ -67,7 +66,7 @@ func serverStaticRouter(ctx *context.Context) {
|
||||
//if the request is dir and DirectoryIndex is false then
|
||||
if finfo.IsDir() {
|
||||
if !DirectoryIndex {
|
||||
middleware.Exception("403", ctx.ResponseWriter, ctx.Request, "403 Forbidden")
|
||||
exception("403", ctx)
|
||||
return
|
||||
} else if ctx.Input.Request.URL.Path[len(ctx.Input.Request.URL.Path)-1] != '/' {
|
||||
http.Redirect(ctx.ResponseWriter, ctx.Request, ctx.Input.Request.URL.Path+"/", 302)
|
||||
|
@ -42,6 +42,9 @@ func init() {
|
||||
beegoTplFuncMap["dateformat"] = DateFormat
|
||||
beegoTplFuncMap["date"] = Date
|
||||
beegoTplFuncMap["compare"] = Compare
|
||||
beegoTplFuncMap["compare_not"] = CompareNot
|
||||
beegoTplFuncMap["not_nil"] = NotNil
|
||||
beegoTplFuncMap["not_null"] = NotNil
|
||||
beegoTplFuncMap["substr"] = Substr
|
||||
beegoTplFuncMap["html2str"] = Html2str
|
||||
beegoTplFuncMap["str2html"] = Str2html
|
||||
|
@ -139,6 +139,14 @@ func Compare(a, b interface{}) (equal bool) {
|
||||
return
|
||||
}
|
||||
|
||||
func CompareNot(a, b interface{}) (equal bool) {
|
||||
return ! Compare(a, b)
|
||||
}
|
||||
|
||||
func NotNil(a interface{}) (is_nil bool) {
|
||||
return CompareNot(a, nil)
|
||||
}
|
||||
|
||||
func Config(returnType, key string, defaultVal interface{}) (value interface{}, err error) {
|
||||
switch returnType {
|
||||
case "String":
|
||||
@ -246,7 +254,7 @@ func Htmlunquote(src string) string {
|
||||
// /user/John%20Doe
|
||||
//
|
||||
// more detail http://beego.me/docs/mvc/controller/urlbuilding.md
|
||||
func UrlFor(endpoint string, values ...string) string {
|
||||
func UrlFor(endpoint string, values ...interface{}) string {
|
||||
return BeeApp.Handlers.UrlFor(endpoint, values...)
|
||||
}
|
||||
|
||||
@ -350,11 +358,32 @@ func ParseForm(form url.Values, obj interface{}) error {
|
||||
}
|
||||
fieldV.Set(reflect.ValueOf(t))
|
||||
}
|
||||
case reflect.Slice:
|
||||
if fieldT.Type == sliceOfInts {
|
||||
formVals := form[tag]
|
||||
fieldV.Set(reflect.MakeSlice(reflect.SliceOf(reflect.TypeOf(int(1))), len(formVals), len(formVals)))
|
||||
for i := 0; i < len(formVals); i++ {
|
||||
val, err := strconv.Atoi(formVals[i])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fieldV.Index(i).SetInt(int64(val))
|
||||
}
|
||||
} else if fieldT.Type == sliceOfStrings {
|
||||
formVals := form[tag]
|
||||
fieldV.Set(reflect.MakeSlice(reflect.SliceOf(reflect.TypeOf("")), len(formVals), len(formVals)))
|
||||
for i := 0; i < len(formVals); i++ {
|
||||
fieldV.Index(i).SetString(formVals[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var sliceOfInts = reflect.TypeOf([]int(nil))
|
||||
var sliceOfStrings = reflect.TypeOf([]string(nil))
|
||||
|
||||
var unKind = map[reflect.Kind]bool{
|
||||
reflect.Uintptr: true,
|
||||
reflect.Complex64: true,
|
||||
|
@ -72,7 +72,7 @@ func TestDate(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompare(t *testing.T) {
|
||||
func TestCompareRelated(t *testing.T) {
|
||||
if !Compare("abc", "abc") {
|
||||
t.Error("should be equal")
|
||||
}
|
||||
@ -82,6 +82,15 @@ func TestCompare(t *testing.T) {
|
||||
if !Compare("1", 1) {
|
||||
t.Error("should be equal")
|
||||
}
|
||||
if CompareNot("abc", "abc") {
|
||||
t.Error("should be equal")
|
||||
}
|
||||
if !CompareNot("abc", "aBc") {
|
||||
t.Error("should be not equal")
|
||||
}
|
||||
if !NotNil("a string") {
|
||||
t.Error("should not be nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHtmlquote(t *testing.T) {
|
||||
|
@ -84,6 +84,7 @@ type TaskFunc func() error
|
||||
|
||||
// task interface
|
||||
type Tasker interface {
|
||||
GetSpec() string
|
||||
GetStatus() string
|
||||
Run() error
|
||||
SetNext(time.Time)
|
||||
@ -102,6 +103,7 @@ type taskerr struct {
|
||||
type Task struct {
|
||||
Taskname string
|
||||
Spec *Schedule
|
||||
SpecStr string
|
||||
DoFunc TaskFunc
|
||||
Prev time.Time
|
||||
Next time.Time
|
||||
@ -116,16 +118,22 @@ func NewTask(tname string, spec string, f TaskFunc) *Task {
|
||||
Taskname: tname,
|
||||
DoFunc: f,
|
||||
ErrLimit: 100,
|
||||
SpecStr: spec,
|
||||
}
|
||||
task.SetCron(spec)
|
||||
return task
|
||||
}
|
||||
|
||||
//get spec string
|
||||
func (s *Task) GetSpec() string {
|
||||
return s.SpecStr
|
||||
}
|
||||
|
||||
// get current task status
|
||||
func (tk *Task) GetStatus() string {
|
||||
var str string
|
||||
for _, v := range tk.Errlist {
|
||||
str += v.t.String() + ":" + v.errinfo + "\n"
|
||||
str += v.t.String() + ":" + v.errinfo + "<br>"
|
||||
}
|
||||
return str
|
||||
}
|
||||
|
45
tree.go
45
tree.go
@ -70,18 +70,23 @@ func (t *Tree) addtree(segments []string, tree *Tree, wildcards []string, reg st
|
||||
} else {
|
||||
regexpStr = "/" + regexpStr
|
||||
}
|
||||
} else {
|
||||
for _, w := range wildcards {
|
||||
if w == "." || w == ":" {
|
||||
continue
|
||||
} else if reg != "" {
|
||||
if seg == "*.*" {
|
||||
regexpStr = "([^.]+).(.+)"
|
||||
} else {
|
||||
for _, w := range params {
|
||||
if w == "." || w == ":" {
|
||||
continue
|
||||
}
|
||||
regexpStr = "([^/]+)/" + regexpStr
|
||||
}
|
||||
regexpStr = "([^/]+)/" + regexpStr
|
||||
}
|
||||
}
|
||||
reg = strings.Trim(reg+regexpStr, "/")
|
||||
reg = strings.Trim(reg+"/"+regexpStr, "/")
|
||||
filterTreeWithPrefix(tree, append(wildcards, params...), reg)
|
||||
t.wildcard = tree
|
||||
} else {
|
||||
reg = strings.Trim(reg+"/"+regexpStr, "/")
|
||||
filterTreeWithPrefix(tree, append(wildcards, params...), reg)
|
||||
t.fixrouters[seg] = tree
|
||||
}
|
||||
@ -104,23 +109,23 @@ func (t *Tree) addtree(segments []string, tree *Tree, wildcards []string, reg st
|
||||
rr = rr + "([^/]+)/"
|
||||
}
|
||||
}
|
||||
regexpStr = rr + regexpStr + "/"
|
||||
regexpStr = rr + regexpStr
|
||||
} else {
|
||||
regexpStr = "/" + regexpStr + "/"
|
||||
regexpStr = "/" + regexpStr
|
||||
}
|
||||
} else {
|
||||
for _, w := range wildcards {
|
||||
if w == "." || w == ":" {
|
||||
continue
|
||||
}
|
||||
if w == ":splat" {
|
||||
regexpStr = "(.+)/" + regexpStr
|
||||
} else {
|
||||
} else if reg != "" {
|
||||
if seg == "*.*" {
|
||||
regexpStr = "([^.]+).(.+)"
|
||||
} else {
|
||||
for _, w := range params {
|
||||
if w == "." || w == ":" {
|
||||
continue
|
||||
}
|
||||
regexpStr = "([^/]+)/" + regexpStr
|
||||
}
|
||||
}
|
||||
}
|
||||
reg = reg + regexpStr
|
||||
reg = strings.TrimRight(strings.TrimRight(reg, "/")+"/"+regexpStr, "/")
|
||||
t.wildcard.addtree(segments[1:], tree, append(wildcards, params...), reg)
|
||||
} else {
|
||||
subTree := NewTree()
|
||||
@ -140,7 +145,7 @@ func filterTreeWithPrefix(t *Tree, wildcards []string, reg string) {
|
||||
if reg != "" {
|
||||
if l.regexps != nil {
|
||||
l.wildcards = append(wildcards, l.wildcards...)
|
||||
l.regexps = regexp.MustCompile("^" + reg + strings.Trim(l.regexps.String(), "^$") + "$")
|
||||
l.regexps = regexp.MustCompile("^" + reg + "/" + strings.Trim(l.regexps.String(), "^$") + "$")
|
||||
} else {
|
||||
for _, v := range l.wildcards {
|
||||
if v == ":" || v == "." {
|
||||
@ -248,7 +253,6 @@ func (t *Tree) addseg(segments []string, route interface{}, wildcards []string,
|
||||
regexpStr = "/([^/]+)" + regexpStr
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
t.wildcard.addseg(segments[1:], route, append(wildcards, params...), reg+regexpStr)
|
||||
} else {
|
||||
@ -422,6 +426,9 @@ func (leaf *leafInfo) match(wildcardValues []string) (ok bool, params map[string
|
||||
// "/admin/" -> ["admin"]
|
||||
// "/admin/users" -> ["admin", "users"]
|
||||
func splitPath(key string) []string {
|
||||
if key == "" {
|
||||
return []string{}
|
||||
}
|
||||
elements := strings.Split(key, "/")
|
||||
if elements[0] == "" {
|
||||
elements = elements[1:]
|
||||
|
50
tree_test.go
50
tree_test.go
@ -148,8 +148,56 @@ func TestAddTree2(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddTree3(t *testing.T) {
|
||||
tr := NewTree()
|
||||
tr.AddRouter("/create", "astaxie")
|
||||
tr.AddRouter("/shop/:sd/account", "astaxie")
|
||||
t3 := NewTree()
|
||||
t3.AddTree("/table/:num", tr)
|
||||
obj, param := t3.Match("/table/123/shop/123/account")
|
||||
if obj == nil || obj.(string) != "astaxie" {
|
||||
t.Fatal("/table/:num/shop/:sd/account can't get obj ")
|
||||
}
|
||||
if param == nil {
|
||||
t.Fatal("get param error")
|
||||
}
|
||||
if param[":num"] != "123" || param[":sd"] != "123" {
|
||||
t.Fatal("get :num :sd param error")
|
||||
}
|
||||
obj, param = t3.Match("/table/123/create")
|
||||
if obj == nil || obj.(string) != "astaxie" {
|
||||
t.Fatal("/table/:num/create can't get obj ")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddTree4(t *testing.T) {
|
||||
tr := NewTree()
|
||||
tr.AddRouter("/create", "astaxie")
|
||||
tr.AddRouter("/shop/:sd/:account", "astaxie")
|
||||
t4 := NewTree()
|
||||
t4.AddTree("/:info:int/:num/:id", tr)
|
||||
obj, param := t4.Match("/12/123/456/shop/123/account")
|
||||
if obj == nil || obj.(string) != "astaxie" {
|
||||
t.Fatal("/:info:int/:num/:id/shop/:sd/:account can't get obj ")
|
||||
}
|
||||
if param == nil {
|
||||
t.Fatal("get param error")
|
||||
}
|
||||
if param[":info"] != "12" || param[":num"] != "123" || param[":id"] != "456" || param[":sd"] != "123" || param[":account"] != "account" {
|
||||
t.Fatal("get :info :num :id :sd :account param error")
|
||||
}
|
||||
obj, param = t4.Match("/12/123/456/create")
|
||||
if obj == nil || obj.(string) != "astaxie" {
|
||||
t.Fatal("/:info:int/:num/:id/create can't get obj ")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitPath(t *testing.T) {
|
||||
a := splitPath("/")
|
||||
a := splitPath("")
|
||||
if len(a) != 0 {
|
||||
t.Fatal("/ should retrun []")
|
||||
}
|
||||
a = splitPath("/")
|
||||
if len(a) != 0 {
|
||||
t.Fatal("/ should retrun []")
|
||||
}
|
||||
|
19
utils/captcha/LICENSE
Normal file
19
utils/captcha/LICENSE
Normal file
@ -0,0 +1,19 @@
|
||||
Copyright (c) 2011-2014 Dmitry Chestnykh <dmitry@codingrobots.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
@ -132,15 +132,6 @@ func (c *Captcha) Handler(ctx *context.Context) {
|
||||
|
||||
key := c.key(id)
|
||||
|
||||
if v, ok := c.store.Get(key).([]byte); ok {
|
||||
chars = v
|
||||
} else {
|
||||
ctx.Output.SetStatus(404)
|
||||
ctx.WriteString("captcha not found")
|
||||
return
|
||||
}
|
||||
|
||||
// reload captcha
|
||||
if len(ctx.Input.Query("reload")) > 0 {
|
||||
chars = c.genRandChars()
|
||||
if err := c.store.Put(key, chars, c.Expiration); err != nil {
|
||||
@ -149,6 +140,14 @@ func (c *Captcha) Handler(ctx *context.Context) {
|
||||
beego.Error("Reload Create Captcha Error:", err)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
if v, ok := c.store.Get(key).([]byte); ok {
|
||||
chars = v
|
||||
} else {
|
||||
ctx.Output.SetStatus(404)
|
||||
ctx.WriteString("captcha not found")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
img := NewImage(chars, c.StdWidth, c.StdHeight)
|
||||
|
@ -292,7 +292,7 @@ func qpEscape(dest []byte, c byte) {
|
||||
const nums = "0123456789ABCDEF"
|
||||
dest[0] = '='
|
||||
dest[1] = nums[(c&0xf0)>>4]
|
||||
dest[2] = nums[(c&0xf)]
|
||||
dest[2] = nums[(c & 0xf)]
|
||||
}
|
||||
|
||||
// headerToBytes enumerates the key and values in the header, and writes the results to the IO Writer
|
||||
|
@ -21,6 +21,6 @@ import (
|
||||
// Instantiates a Paginator and assigns it to context.Input.Data["paginator"].
|
||||
func SetPaginator(context *context.Context, per int, nums int64) (paginator *Paginator) {
|
||||
paginator = NewPaginator(context.Request, per, nums)
|
||||
context.Input.Data["paginator"] = paginator
|
||||
context.Input.Data["paginator"] = &paginator
|
||||
return
|
||||
}
|
||||
|
@ -92,18 +92,18 @@ func (p *Paginator) Pages() []int {
|
||||
case page >= pageNums-4 && pageNums > 9:
|
||||
start := pageNums - 9 + 1
|
||||
pages = make([]int, 9)
|
||||
for i, _ := range pages {
|
||||
for i := range pages {
|
||||
pages[i] = start + i
|
||||
}
|
||||
case page >= 5 && pageNums > 9:
|
||||
start := page - 5 + 1
|
||||
pages = make([]int, int(math.Min(9, float64(page+4+1))))
|
||||
for i, _ := range pages {
|
||||
for i := range pages {
|
||||
pages[i] = start + i
|
||||
}
|
||||
default:
|
||||
pages = make([]int, int(math.Min(9, float64(pageNums))))
|
||||
for i, _ := range pages {
|
||||
for i := range pages {
|
||||
pages[i] = i + 1
|
||||
}
|
||||
}
|
||||
@ -114,7 +114,7 @@ func (p *Paginator) Pages() []int {
|
||||
|
||||
// Returns URL for a given page index.
|
||||
func (p *Paginator) PageLink(page int) string {
|
||||
link, _ := url.ParseRequestURI(p.Request.RequestURI)
|
||||
link, _ := url.ParseRequestURI(p.Request.URL.String())
|
||||
values := link.Query()
|
||||
if page == 1 {
|
||||
values.Del("p")
|
||||
|
@ -51,7 +51,7 @@ func SliceRandList(min, max int) []int {
|
||||
t0 := time.Now()
|
||||
rand.Seed(int64(t0.Nanosecond()))
|
||||
list := rand.Perm(length)
|
||||
for index, _ := range list {
|
||||
for index := range list {
|
||||
list[index] += min
|
||||
}
|
||||
return list
|
||||
|
@ -137,7 +137,7 @@ func getRegFuncs(tag, key string) (vfs []ValidFunc, str string, err error) {
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
vfs = []ValidFunc{ValidFunc{"Match", []interface{}{reg, key + ".Match"}}}
|
||||
vfs = []ValidFunc{{"Match", []interface{}{reg, key + ".Match"}}}
|
||||
str = strings.TrimSpace(tag[:index]) + strings.TrimSpace(tag[end+len("/)"):])
|
||||
return
|
||||
}
|
||||
|
@ -107,6 +107,7 @@ type Validation struct {
|
||||
// Clean all ValidationError.
|
||||
func (v *Validation) Clear() {
|
||||
v.Errors = []*ValidationError{}
|
||||
v.ErrorsMap = nil
|
||||
}
|
||||
|
||||
// Has ValidationError nor not.
|
||||
@ -333,3 +334,41 @@ func (v *Validation) Valid(obj interface{}) (b bool, err error) {
|
||||
|
||||
return !v.HasErrors(), nil
|
||||
}
|
||||
|
||||
// Recursively validate a struct.
|
||||
// Step1: Validate by v.Valid
|
||||
// Step2: If pass on step1, then reflect obj's fields
|
||||
// Step3: Do the Recursively validation to all struct or struct pointer fields
|
||||
func (v *Validation) RecursiveValid(objc interface{}) (bool, error) {
|
||||
//Step 1: validate obj itself firstly
|
||||
// fails if objc is not struct
|
||||
pass, err := v.Valid(objc)
|
||||
if err != nil || false == pass {
|
||||
return pass, err // Stop recursive validation
|
||||
} else { //pass
|
||||
// Step 2: Validate struct's struct fields
|
||||
objT := reflect.TypeOf(objc)
|
||||
objV := reflect.ValueOf(objc)
|
||||
|
||||
if isStructPtr(objT) {
|
||||
objT = objT.Elem()
|
||||
objV = objV.Elem()
|
||||
}
|
||||
|
||||
for i := 0; i < objT.NumField(); i++ {
|
||||
|
||||
t := objT.Field(i).Type
|
||||
|
||||
// Recursive applies to struct or pointer to structs fields
|
||||
if isStruct(t) || isStructPtr(t) {
|
||||
// Step 3: do the recursive validation
|
||||
// Only valid the Public field recursively
|
||||
if objV.Field(i).CanInterface() {
|
||||
pass, err = v.RecursiveValid(objV.Field(i).Interface())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return pass, err
|
||||
}
|
||||
}
|
||||
|
@ -26,6 +26,12 @@ func TestRequired(t *testing.T) {
|
||||
if valid.Required(nil, "nil").Ok {
|
||||
t.Error("nil object should be false")
|
||||
}
|
||||
if !valid.Required(true, "bool").Ok {
|
||||
t.Error("Bool value should always return true")
|
||||
}
|
||||
if !valid.Required(false, "bool").Ok {
|
||||
t.Error("Bool value should always return true")
|
||||
}
|
||||
if valid.Required("", "string").Ok {
|
||||
t.Error("\"'\" string should be false")
|
||||
}
|
||||
@ -343,3 +349,33 @@ func TestValid(t *testing.T) {
|
||||
t.Errorf("Message key should be `Name.Match` but got %s", valid.Errors[0].Key)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecursiveValid(t *testing.T) {
|
||||
type User struct {
|
||||
Id int
|
||||
Name string `valid:"Required;Match(/^(test)?\\w*@(/test/);com$/)"`
|
||||
Age int `valid:"Required;Range(1, 140)"`
|
||||
}
|
||||
|
||||
type AnonymouseUser struct {
|
||||
Id2 int
|
||||
Name2 string `valid:"Required;Match(/^(test)?\\w*@(/test/);com$/)"`
|
||||
Age2 int `valid:"Required;Range(1, 140)"`
|
||||
}
|
||||
|
||||
type Account struct {
|
||||
Password string `valid:"Required"`
|
||||
U User
|
||||
AnonymouseUser
|
||||
}
|
||||
valid := Validation{}
|
||||
|
||||
u := Account{Password: "abc123_", U: User{}}
|
||||
b, err := valid.RecursiveValid(u)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if b {
|
||||
t.Error("validation should not be passed")
|
||||
}
|
||||
}
|
||||
|
@ -64,8 +64,8 @@ func (r Required) IsSatisfied(obj interface{}) bool {
|
||||
if str, ok := obj.(string); ok {
|
||||
return len(str) > 0
|
||||
}
|
||||
if b, ok := obj.(bool); ok {
|
||||
return b
|
||||
if _, ok := obj.(bool); ok {
|
||||
return true
|
||||
}
|
||||
if i, ok := obj.(int); ok {
|
||||
return i != 0
|
||||
@ -457,7 +457,7 @@ func (b Base64) GetLimitValue() interface{} {
|
||||
}
|
||||
|
||||
// just for chinese mobile phone number
|
||||
var mobilePattern = regexp.MustCompile("^((\\+86)|(86))?(1(([35][0-9])|(47)|[8][012356789]))\\d{8}$")
|
||||
var mobilePattern = regexp.MustCompile("^((\\+86)|(86))?(1(([35][0-9])|[8][0-9]|[7][67]|[4][579]))\\d{8}$")
|
||||
|
||||
type Mobile struct {
|
||||
Match
|
||||
|
Reference in New Issue
Block a user