httplib: fix unstable test, do not use httplib.org

This commit is contained in:
Deng Ming
2023-06-04 14:26:53 +08:00
parent 4f4cf565f0
commit 3e96b23551
86 changed files with 1166 additions and 917 deletions

View File

@@ -24,7 +24,8 @@ import (
// FilterMonitorFunc is default monitor filter when admin module is enable.
// if this func returns, admin module records qps for this request by condition of this function logic.
// usage:
// func MyFilterMonitor(method, requestPath string, t time.Duration, pattern string, statusCode int) bool {
//
// func MyFilterMonitor(method, requestPath string, t time.Duration, pattern string, statusCode int) bool {
// if method == "POST" {
// return false
// }
@@ -35,8 +36,8 @@ import (
// return false
// }
// return true
// }
// beego.FilterMonitorFunc = MyFilterMonitor.
// }
// beego.FilterMonitorFunc = MyFilterMonitor.
var FilterMonitorFunc func(string, string, time.Duration, string, int) bool
// PrintTree prints all registered routers.

View File

@@ -58,19 +58,20 @@ func oldMiddlewareToNew(mws []MiddleWare) []web.MiddleWare {
// Router adds a patterned controller handler to BeeApp.
// it's an alias method of HttpServer.Router.
// usage:
// simple router
// beego.Router("/admin", &admin.UserController{})
// beego.Router("/admin/index", &admin.ArticleController{})
//
// regex router
// simple router
// beego.Router("/admin", &admin.UserController{})
// beego.Router("/admin/index", &admin.ArticleController{})
//
// beego.Router("/api/:id([0-9]+)", &controllers.RController{})
// regex router
//
// custom rules
// beego.Router("/api/list",&RestController{},"*:ListFood")
// beego.Router("/api/create",&RestController{},"post:CreateFood")
// beego.Router("/api/update",&RestController{},"put:UpdateFood")
// beego.Router("/api/delete",&RestController{},"delete:DeleteFood")
// beego.Router("/api/:id([0-9]+)", &controllers.RController{})
//
// custom rules
// beego.Router("/api/list",&RestController{},"*:ListFood")
// beego.Router("/api/create",&RestController{},"post:CreateFood")
// beego.Router("/api/update",&RestController{},"put:UpdateFood")
// beego.Router("/api/delete",&RestController{},"delete:DeleteFood")
func Router(rootpath string, c ControllerInterface, mappingMethods ...string) *App {
return (*App)(web.Router(rootpath, c, mappingMethods...))
}
@@ -82,8 +83,9 @@ func Router(rootpath string, c ControllerInterface, mappingMethods ...string) *A
// method type (e.g. "GET" or "POST") for selective removal.
//
// Usage (replace "GET" with "*" for all methods):
// beego.UnregisterFixedRoute("/yourpreviouspath", "GET")
// beego.Router("/yourpreviouspath", yourControllerAddress, "get:GetNewPage")
//
// beego.UnregisterFixedRoute("/yourpreviouspath", "GET")
// beego.Router("/yourpreviouspath", yourControllerAddress, "get:GetNewPage")
func UnregisterFixedRoute(fixedRoute string, method string) *App {
return (*App)(web.UnregisterFixedRoute(fixedRoute, method))
}
@@ -91,26 +93,29 @@ func UnregisterFixedRoute(fixedRoute string, method string) *App {
// Include will generate router file in the router/xxx.go from the controller's comments
// usage:
// beego.Include(&BankAccount{}, &OrderController{},&RefundController{},&ReceiptController{})
// type BankAccount struct{
// beego.Controller
// }
//
// type BankAccount struct{
// beego.Controller
// }
//
// register the function
// func (b *BankAccount)Mapping(){
// b.Mapping("ShowAccount" , b.ShowAccount)
// b.Mapping("ModifyAccount", b.ModifyAccount)
// }
//
// func (b *BankAccount)Mapping(){
// b.Mapping("ShowAccount" , b.ShowAccount)
// b.Mapping("ModifyAccount", b.ModifyAccount)
// }
//
// //@router /account/:id [get]
// func (b *BankAccount) ShowAccount(){
// //logic
// }
//
// func (b *BankAccount) ShowAccount(){
// //logic
// }
//
// //@router /account/:id [post]
// func (b *BankAccount) ModifyAccount(){
// //logic
// }
//
// func (b *BankAccount) ModifyAccount(){
// //logic
// }
//
// the comments @router url methodlist
// url support all the function Router's pattern
@@ -153,9 +158,10 @@ func AutoPrefix(prefix string, c ControllerInterface) *App {
// Get used to register router for Get method
// usage:
// beego.Get("/", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
//
// beego.Get("/", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
func Get(rootpath string, f FilterFunc) *App {
return (*App)(web.Get(rootpath, func(ctx *context.Context) {
f((*context2.Context)(ctx))
@@ -164,9 +170,10 @@ func Get(rootpath string, f FilterFunc) *App {
// Post used to register router for Post method
// usage:
// beego.Post("/api", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
//
// beego.Post("/api", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
func Post(rootpath string, f FilterFunc) *App {
return (*App)(web.Post(rootpath, func(ctx *context.Context) {
f((*context2.Context)(ctx))
@@ -175,9 +182,10 @@ func Post(rootpath string, f FilterFunc) *App {
// Delete used to register router for Delete method
// usage:
// beego.Delete("/api", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
//
// beego.Delete("/api", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
func Delete(rootpath string, f FilterFunc) *App {
return (*App)(web.Delete(rootpath, func(ctx *context.Context) {
f((*context2.Context)(ctx))
@@ -186,9 +194,10 @@ func Delete(rootpath string, f FilterFunc) *App {
// Put used to register router for Put method
// usage:
// beego.Put("/api", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
//
// beego.Put("/api", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
func Put(rootpath string, f FilterFunc) *App {
return (*App)(web.Put(rootpath, func(ctx *context.Context) {
f((*context2.Context)(ctx))
@@ -197,9 +206,10 @@ func Put(rootpath string, f FilterFunc) *App {
// Head used to register router for Head method
// usage:
// beego.Head("/api", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
//
// beego.Head("/api", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
func Head(rootpath string, f FilterFunc) *App {
return (*App)(web.Head(rootpath, func(ctx *context.Context) {
f((*context2.Context)(ctx))
@@ -208,9 +218,10 @@ func Head(rootpath string, f FilterFunc) *App {
// Options used to register router for Options method
// usage:
// beego.Options("/api", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
//
// beego.Options("/api", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
func Options(rootpath string, f FilterFunc) *App {
return (*App)(web.Options(rootpath, func(ctx *context.Context) {
f((*context2.Context)(ctx))
@@ -219,9 +230,10 @@ func Options(rootpath string, f FilterFunc) *App {
// Patch used to register router for Patch method
// usage:
// beego.Patch("/api", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
//
// beego.Patch("/api", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
func Patch(rootpath string, f FilterFunc) *App {
return (*App)(web.Patch(rootpath, func(ctx *context.Context) {
f((*context2.Context)(ctx))
@@ -230,9 +242,10 @@ func Patch(rootpath string, f FilterFunc) *App {
// Any used to register router for all methods
// usage:
// beego.Any("/api", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
//
// beego.Any("/api", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
func Any(rootpath string, f FilterFunc) *App {
return (*App)(web.Any(rootpath, func(ctx *context.Context) {
f((*context2.Context)(ctx))
@@ -241,9 +254,10 @@ func Any(rootpath string, f FilterFunc) *App {
// Handler used to register a Handler router
// usage:
// beego.Handler("/api", http.HandlerFunc(func (w http.ResponseWriter, r *http.Request) {
// fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
// }))
//
// beego.Handler("/api", http.HandlerFunc(func (w http.ResponseWriter, r *http.Request) {
// fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
// }))
func Handler(rootpath string, h http.Handler, options ...interface{}) *App {
return (*App)(web.Handler(rootpath, h, options...))
}

View File

@@ -16,7 +16,9 @@
// Usage:
//
// import(
// "github.com/beego/beego/v2/client/cache"
//
// "github.com/beego/beego/v2/client/cache"
//
// )
//
// bm, err := cache.NewCache("memory", `{"interval":60}`)
@@ -27,7 +29,6 @@
// bm.Get("astaxie")
// bm.IsExist("astaxie")
// bm.Delete("astaxie")
//
package cache
import (
@@ -37,6 +38,7 @@ import (
// Cache interface contains all behaviors for cache adapter.
// usage:
//
// cache.Register("file",cache.NewFileCache) // this operation is run in init method of file.go.
// c,err := cache.NewCache("file","{....}")
// c.Put("key",value, 3600 * time.Second)

View File

@@ -20,12 +20,13 @@
//
// Usage:
// import(
// _ "github.com/beego/beego/v2/client/cache/memcache"
// "github.com/beego/beego/v2/client/cache"
//
// _ "github.com/beego/beego/v2/client/cache/memcache"
// "github.com/beego/beego/v2/client/cache"
//
// )
//
// bm, err := cache.NewCache("memcache", `{"conn":"127.0.0.1:11211"}`)
//
// bm, err := cache.NewCache("memcache", `{"conn":"127.0.0.1:11211"}`)
package memcache
import (

View File

@@ -20,12 +20,13 @@
//
// Usage:
// import(
// _ "github.com/beego/beego/v2/client/cache/redis"
// "github.com/beego/beego/v2/client/cache"
//
// _ "github.com/beego/beego/v2/client/cache/redis"
// "github.com/beego/beego/v2/client/cache"
//
// )
//
// bm, err := cache.NewCache("redis", `{"conn":"127.0.0.1:11211"}`)
//
// bm, err := cache.NewCache("redis", `{"conn":"127.0.0.1:11211"}`)
package redis
import (

View File

@@ -14,29 +14,31 @@
// Package config is used to parse config.
// Usage:
// import "github.com/beego/beego/v2/core/config"
//
// import "github.com/beego/beego/v2/core/config"
//
// Examples.
//
// cnf, err := config.NewConfig("ini", "config.conf")
// cnf, err := config.NewConfig("ini", "config.conf")
//
// cnf APIS:
// cnf APIS:
//
// cnf.Set(key, val string) error
// cnf.String(key string) string
// cnf.Strings(key string) []string
// cnf.Int(key string) (int, error)
// cnf.Int64(key string) (int64, error)
// cnf.Bool(key string) (bool, error)
// cnf.Float(key string) (float64, error)
// cnf.DefaultString(key string, defaultVal string) string
// cnf.DefaultStrings(key string, defaultVal []string) []string
// cnf.DefaultInt(key string, defaultVal int) int
// cnf.DefaultInt64(key string, defaultVal int64) int64
// cnf.DefaultBool(key string, defaultVal bool) bool
// cnf.DefaultFloat(key string, defaultVal float64) float64
// cnf.DIY(key string) (interface{}, error)
// cnf.GetSection(section string) (map[string]string, error)
// cnf.SaveConfigFile(filename string) error
// cnf.Set(key, val string) error
// cnf.String(key string) string
// cnf.Strings(key string) []string
// cnf.Int(key string) (int, error)
// cnf.Int64(key string) (int64, error)
// cnf.Bool(key string) (bool, error)
// cnf.Float(key string) (float64, error)
// cnf.DefaultString(key string, defaultVal string) string
// cnf.DefaultStrings(key string, defaultVal []string) []string
// cnf.DefaultInt(key string, defaultVal int) int
// cnf.DefaultInt64(key string, defaultVal int64) int64
// cnf.DefaultBool(key string, defaultVal bool) bool
// cnf.DefaultFloat(key string, defaultVal float64) float64
// cnf.DIY(key string) (interface{}, error)
// cnf.GetSection(section string) (map[string]string, error)
// cnf.SaveConfigFile(filename string) error
package config
import (
@@ -128,6 +130,7 @@ func ExpandValueEnvForMap(m map[string]interface{}) map[string]interface{} {
//
// It accept value formats "${env}" , "${env||}}" , "${env||defaultValue}" , "defaultvalue".
// Examples:
//
// v1 := config.ExpandValueEnv("${GOPATH}") // return the GOPATH environment variable.
// v2 := config.ExpandValueEnv("${GOAsta||/usr/local/go}") // return the default value "/usr/local/go/".
// v3 := config.ExpandValueEnv("Astaxie") // return the value "Astaxie".

View File

@@ -5,7 +5,7 @@
// 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
// 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,

View File

@@ -19,13 +19,13 @@
// go install github.com/beego/x2j.
//
// Usage:
// import(
// _ "github.com/beego/beego/v2/core/config/xml"
// "github.com/beego/beego/v2/core/config"
// )
//
// cnf, err := config.NewConfig("xml", "config.xml")
// import(
// _ "github.com/beego/beego/v2/core/config/xml"
// "github.com/beego/beego/v2/core/config"
// )
//
// cnf, err := config.NewConfig("xml", "config.xml")
package xml
import (

View File

@@ -19,13 +19,13 @@
// go install github.com/beego/goyaml2
//
// Usage:
// import(
// _ "github.com/beego/beego/v2/core/config/yaml"
// "github.com/beego/beego/v2/core/config"
// )
//
// cnf, err := config.NewConfig("yaml", "config.yaml")
// import(
// _ "github.com/beego/beego/v2/core/config/yaml"
// "github.com/beego/beego/v2/core/config"
// )
//
// cnf, err := config.NewConfig("yaml", "config.yaml")
package yaml
import (

View File

@@ -18,7 +18,6 @@
// import "github.com/beego/beego/v2/server/web/context"
//
// ctx := context.Context{Request:req,ResponseWriter:rw}
//
package context
import (

View File

@@ -296,31 +296,33 @@ func (c *Controller) GetFile(key string) (multipart.File, *multipart.FileHeader,
// 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
//
// 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
// }
// }
// //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) {
return (*web.Controller)(c).GetFiles(key)
}

View File

@@ -182,7 +182,8 @@ var ErrorMaps = web.ErrorMaps
// ErrorHandler registers http.HandlerFunc to each http err code string.
// usage:
// beego.ErrorHandler("404",NotFound)
//
// beego.ErrorHandler("404",NotFound)
// beego.ErrorHandler("500",InternalServerError)
func ErrorHandler(code string, h http.HandlerFunc) *App {
return (*App)(web.ErrorHandler(code, h))
@@ -190,7 +191,8 @@ func ErrorHandler(code string, h http.HandlerFunc) *App {
// ErrorController registers ControllerInterface to each http err code string.
// usage:
// beego.ErrorController(&controllers.ErrorController{})
//
// beego.ErrorController(&controllers.ErrorController{})
func ErrorController(c ControllerInterface) *App {
return (*App)(web.ErrorController(c))
}

View File

@@ -18,28 +18,30 @@
// Usage:
//
// import(
// "log"
// "net/http"
// "os"
//
// "github.com/beego/beego/v2/server/web/grace"
// "log"
// "net/http"
// "os"
//
// "github.com/beego/beego/v2/server/web/grace"
//
// )
//
// func handler(w http.ResponseWriter, r *http.Request) {
// w.Write([]byte("WORLD!"))
// }
// func handler(w http.ResponseWriter, r *http.Request) {
// w.Write([]byte("WORLD!"))
// }
//
// func main() {
// mux := http.NewServeMux()
// mux.HandleFunc("/hello", handler)
// func main() {
// mux := http.NewServeMux()
// mux.HandleFunc("/hello", handler)
//
// err := grace.ListenAndServe("localhost:8080", mux)
// if err != nil {
// log.Println(err)
// }
// log.Println("Server on 8080 stopped")
// os.Exit(0)
// }
// err := grace.ListenAndServe("localhost:8080", mux)
// if err != nil {
// log.Println(err)
// }
// log.Println("Server on 8080 stopped")
// os.Exit(0)
// }
package grace
import (

View File

@@ -27,7 +27,6 @@
// t.Fatal(err)
// }
// fmt.Println(str)
//
package httplib
import (
@@ -175,9 +174,9 @@ func (b *BeegoHTTPRequest) SetTransport(transport http.RoundTripper) *BeegoHTTPR
// example:
//
// func(req *http.Request) (*url.URL, error) {
// u, _ := url.ParseRequestURI("http://127.0.0.1:8118")
// return u, nil
// }
// u, _ := url.ParseRequestURI("http://127.0.0.1:8118")
// return u, nil
// }
func (b *BeegoHTTPRequest) SetProxy(proxy func(*http.Request) (*url.URL, error)) *BeegoHTTPRequest {
b.delegate.SetProxy(proxy)
return b

View File

@@ -29,7 +29,6 @@
// log.Warn("warning")
// log.Debug("debug")
// log.Critical("critical")
//
package logs
import (

View File

@@ -50,12 +50,14 @@ func oldToNewLinkNs(params []LinkNamespace) []web.LinkNamespace {
// Cond set condition function
// if cond return true can run this namespace, else can't
// usage:
// ns.Cond(func (ctx *context.Context) bool{
// if ctx.Input.Domain() == "api.beego.vip" {
// return true
// }
// return false
// })
//
// ns.Cond(func (ctx *context.Context) bool{
// if ctx.Input.Domain() == "api.beego.vip" {
// return true
// }
// return false
// })
//
// Cond as the first filter
func (n *Namespace) Cond(cond namespaceCond) *Namespace {
(*web.Namespace)(n).Cond(func(context *context.Context) bool {
@@ -68,12 +70,13 @@ func (n *Namespace) Cond(cond namespaceCond) *Namespace {
// action has before & after
// FilterFunc
// usage:
// Filter("before", func (ctx *context.Context){
// _, ok := ctx.Input.Session("uid").(int)
// if !ok && ctx.Request.RequestURI != "/login" {
// ctx.Redirect(302, "/login")
// }
// })
//
// Filter("before", func (ctx *context.Context){
// _, ok := ctx.Input.Session("uid").(int)
// if !ok && ctx.Request.RequestURI != "/login" {
// ctx.Redirect(302, "/login")
// }
// })
func (n *Namespace) Filter(action string, filter ...FilterFunc) *Namespace {
nfs := oldToNewFilter(filter)
(*web.Namespace)(n).Filter(action, nfs...)
@@ -203,18 +206,20 @@ func (n *Namespace) Include(cList ...ControllerInterface) *Namespace {
// usage:
// ns := beego.NewNamespace(“/v1”).
// Namespace(
// beego.NewNamespace("/shop").
// Get("/:id", func(ctx *context.Context) {
// ctx.Output.Body([]byte("shopinfo"))
// }),
// beego.NewNamespace("/order").
// Get("/:id", func(ctx *context.Context) {
// ctx.Output.Body([]byte("orderinfo"))
// }),
// beego.NewNamespace("/crm").
// Get("/:id", func(ctx *context.Context) {
// ctx.Output.Body([]byte("crminfo"))
// }),
//
// beego.NewNamespace("/shop").
// Get("/:id", func(ctx *context.Context) {
// ctx.Output.Body([]byte("shopinfo"))
// }),
// beego.NewNamespace("/order").
// Get("/:id", func(ctx *context.Context) {
// ctx.Output.Body([]byte("orderinfo"))
// }),
// beego.NewNamespace("/crm").
// Get("/:id", func(ctx *context.Context) {
// ctx.Output.Body([]byte("crminfo"))
// }),
//
// )
func (n *Namespace) Namespace(ns ...*Namespace) *Namespace {
nns := oldToNewNs(ns)

View File

@@ -50,7 +50,6 @@
// // delete
// num, err = o.Delete(&u)
// }
//
package orm
import (
@@ -170,8 +169,9 @@ func (o *ormer) QueryM2M(md interface{}, name string) QueryM2Mer {
// args are limit, offset int and order string.
//
// example:
// orm.LoadRelated(post,"Tags")
// for _,tag := range post.Tags{...}
//
// orm.LoadRelated(post,"Tags")
// for _,tag := range post.Tags{...}
//
// make sure the relation is defined in model struct tags.
func (o *ormer) LoadRelated(md interface{}, name string, args ...interface{}) (int64, error) {

View File

@@ -145,6 +145,7 @@ type RawPreparer orm.RawPreparer
// RawSeter raw query seter
// create From Ormer.Raw
// for example:
// sql := fmt.Sprintf("SELECT %sid%s,%sname%s FROM %suser%s WHERE id = ?",Q,Q,Q,Q,Q,Q)
// rs := Ormer.Raw(sql, 1)
//
// sql := fmt.Sprintf("SELECT %sid%s,%sname%s FROM %suser%s WHERE id = ?",Q,Q,Q,Q,Q,Q)
// rs := Ormer.Raw(sql, 1)
type RawSeter orm.RawSeter

View File

@@ -15,6 +15,7 @@
// Package apiauth provides handlers to enable apiauth support.
//
// Simple Usage:
//
// import(
// "github.com/beego/beego/v2"
// "github.com/beego/beego/v2/server/web/filter/apiauth"
@@ -37,11 +38,11 @@
//
// Information:
//
// In the request user should include these params in the query
// # In the request user should include these params in the query
//
// 1. appid
//
// appid is assigned to the application
// appid is assigned to the application
//
// 2. signature
//
@@ -51,8 +52,7 @@
//
// 3. timestamp:
//
// send the request time, the format is yyyy-mm-dd HH:ii:ss
//
// send the request time, the format is yyyy-mm-dd HH:ii:ss
package apiauth
import (

View File

@@ -14,6 +14,7 @@
// Package auth provides handlers to enable basic auth support.
// Simple Usage:
//
// import(
// "github.com/beego/beego/v2"
// "github.com/beego/beego/v2/server/web/filter/auth"
@@ -25,7 +26,6 @@
// beego.Run()
// }
//
//
// Advanced Usage:
//
// func SecretAuth(username, password string) bool {

View File

@@ -14,6 +14,7 @@
// Package authz provides handlers to enable ACL, RBAC, ABAC authorization support.
// Simple Usage:
//
// import(
// "github.com/beego/beego/v2"
// "github.com/beego/beego/v2/server/web/filter/authz"
@@ -26,7 +27,6 @@
// beego.Run()
// }
//
//
// Advanced Usage:
//
// func main(){

View File

@@ -14,9 +14,11 @@
// Package cors provides handlers to enable CORS support.
// Usage
//
// import (
// "github.com/beego/beego/v2"
// "github.com/beego/beego/v2"
// "github.com/beego/beego/v2/server/web/filter/cors"
//
// )
//
// func main() {

View File

@@ -77,6 +77,7 @@ func NewControllerRegister() *ControllerRegister {
// Add controller handler and pattern rules to ControllerRegister.
// usage:
//
// default methods is the same name as method
// Add("/user",&UserController{})
// Add("/api/list",&RestController{},"*:ListFood")
@@ -99,9 +100,10 @@ func (p *ControllerRegister) Include(cList ...ControllerInterface) {
// GetContext returns a context from pool, so usually you should remember to call Reset function to clean the context
// And don't forget to give back context to pool
// example:
// ctx := p.GetContext()
// ctx.Reset(w, q)
// defer p.GiveBackContext(ctx)
//
// ctx := p.GetContext()
// ctx.Reset(w, q)
// defer p.GiveBackContext(ctx)
func (p *ControllerRegister) GetContext() *beecontext.Context {
return (*beecontext.Context)((*web.ControllerRegister)(p).GetContext())
}
@@ -113,9 +115,10 @@ func (p *ControllerRegister) GiveBackContext(ctx *beecontext.Context) {
// Get add get method
// usage:
// Get("/", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
//
// Get("/", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
func (p *ControllerRegister) Get(pattern string, f FilterFunc) {
(*web.ControllerRegister)(p).Get(pattern, func(ctx *context.Context) {
f((*beecontext.Context)(ctx))
@@ -124,9 +127,10 @@ func (p *ControllerRegister) Get(pattern string, f FilterFunc) {
// Post add post method
// usage:
// Post("/api", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
//
// Post("/api", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
func (p *ControllerRegister) Post(pattern string, f FilterFunc) {
(*web.ControllerRegister)(p).Post(pattern, func(ctx *context.Context) {
f((*beecontext.Context)(ctx))
@@ -135,9 +139,10 @@ func (p *ControllerRegister) Post(pattern string, f FilterFunc) {
// Put add put method
// usage:
// Put("/api/:id", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
//
// Put("/api/:id", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
func (p *ControllerRegister) Put(pattern string, f FilterFunc) {
(*web.ControllerRegister)(p).Put(pattern, func(ctx *context.Context) {
f((*beecontext.Context)(ctx))
@@ -146,9 +151,10 @@ func (p *ControllerRegister) Put(pattern string, f FilterFunc) {
// Delete add delete method
// usage:
// Delete("/api/:id", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
//
// Delete("/api/:id", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
func (p *ControllerRegister) Delete(pattern string, f FilterFunc) {
(*web.ControllerRegister)(p).Delete(pattern, func(ctx *context.Context) {
f((*beecontext.Context)(ctx))
@@ -157,9 +163,10 @@ func (p *ControllerRegister) Delete(pattern string, f FilterFunc) {
// Head add head method
// usage:
// Head("/api/:id", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
//
// Head("/api/:id", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
func (p *ControllerRegister) Head(pattern string, f FilterFunc) {
(*web.ControllerRegister)(p).Head(pattern, func(ctx *context.Context) {
f((*beecontext.Context)(ctx))
@@ -168,9 +175,10 @@ func (p *ControllerRegister) Head(pattern string, f FilterFunc) {
// Patch add patch method
// usage:
// Patch("/api/:id", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
//
// Patch("/api/:id", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
func (p *ControllerRegister) Patch(pattern string, f FilterFunc) {
(*web.ControllerRegister)(p).Patch(pattern, func(ctx *context.Context) {
f((*beecontext.Context)(ctx))
@@ -179,9 +187,10 @@ func (p *ControllerRegister) Patch(pattern string, f FilterFunc) {
// Options add options method
// usage:
// Options("/api/:id", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
//
// Options("/api/:id", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
func (p *ControllerRegister) Options(pattern string, f FilterFunc) {
(*web.ControllerRegister)(p).Options(pattern, func(ctx *context.Context) {
f((*beecontext.Context)(ctx))
@@ -190,9 +199,10 @@ func (p *ControllerRegister) Options(pattern string, f FilterFunc) {
// Any add all method
// usage:
// Any("/api/:id", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
//
// Any("/api/:id", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
func (p *ControllerRegister) Any(pattern string, f FilterFunc) {
(*web.ControllerRegister)(p).Any(pattern, func(ctx *context.Context) {
f((*beecontext.Context)(ctx))
@@ -201,9 +211,10 @@ func (p *ControllerRegister) Any(pattern string, f FilterFunc) {
// AddMethod add http method router
// usage:
// AddMethod("get","/api/:id", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
//
// AddMethod("get","/api/:id", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
func (p *ControllerRegister) AddMethod(method, pattern string, f FilterFunc) {
(*web.ControllerRegister)(p).AddMethod(method, pattern, func(ctx *context.Context) {
f((*beecontext.Context)(ctx))
@@ -235,8 +246,8 @@ func (p *ControllerRegister) AddAutoPrefix(prefix string, c ControllerInterface)
// InsertFilter Add a FilterFunc with pattern rule and action constant.
// params is for:
// 1. setting the returnOnOutput value (false allows multiple filters to execute)
// 2. determining whether or not params need to be reset.
// 1. setting the returnOnOutput value (false allows multiple filters to execute)
// 2. determining whether or not params need to be reset.
func (p *ControllerRegister) InsertFilter(pattern string, pos int, filter FilterFunc, params ...bool) error {
opts := oldToNewFilterOpts(params)
return (*web.ControllerRegister)(p).InsertFilter(pattern, pos, func(ctx *context.Context) {

View File

@@ -20,15 +20,16 @@
//
// Usage:
// import(
// _ "github.com/beego/beego/v2/server/web/session/couchbase"
// "github.com/beego/beego/v2/server/web/session"
//
// _ "github.com/beego/beego/v2/server/web/session/couchbase"
// "github.com/beego/beego/v2/server/web/session"
//
// )
//
// func init() {
// globalSessions, _ = session.NewManager("couchbase", ``{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"http://host:port/, Pool, Bucket"}``)
// go globalSessions.GC()
// }
//
package couchbase
import (

View File

@@ -20,15 +20,16 @@
//
// Usage:
// import(
// _ "github.com/beego/beego/v2/server/web/session/memcache"
// "github.com/beego/beego/v2/server/web/session"
//
// _ "github.com/beego/beego/v2/server/web/session/memcache"
// "github.com/beego/beego/v2/server/web/session"
//
// )
//
// func init() {
// globalSessions, _ = session.NewManager("memcache", ``{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:11211"}``)
// go globalSessions.GC()
// }
//
package memcache
import (

View File

@@ -19,6 +19,7 @@
// go install github.com/go-sql-driver/mysql
//
// mysql session support need create table as sql:
//
// CREATE TABLE `session` (
// `session_key` char(64) NOT NULL,
// `session_data` blob,
@@ -28,15 +29,16 @@
//
// Usage:
// import(
// _ "github.com/beego/beego/v2/server/web/session/mysql"
// "github.com/beego/beego/v2/server/web/session"
//
// _ "github.com/beego/beego/v2/server/web/session/mysql"
// "github.com/beego/beego/v2/server/web/session"
//
// )
//
// func init() {
// globalSessions, _ = session.NewManager("mysql", ``{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"[username[:password]@][protocol[(address)]]/dbname[?param1=value1&...&paramN=valueN]"}``)
// go globalSessions.GC()
// }
//
package mysql
import (

View File

@@ -18,7 +18,6 @@
//
// go install github.com/lib/pq
//
//
// needs this table in your database:
//
// CREATE TABLE session (
@@ -35,18 +34,18 @@
// SessionSavePath = "user=a password=b dbname=c sslmode=disable"
// SessionName = session
//
//
// Usage:
// import(
// _ "github.com/beego/beego/v2/server/web/session/postgresql"
// "github.com/beego/beego/v2/server/web/session"
//
// _ "github.com/beego/beego/v2/server/web/session/postgresql"
// "github.com/beego/beego/v2/server/web/session"
//
// )
//
// func init() {
// globalSessions, _ = session.NewManager("postgresql", ``{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"user=pqgotest dbname=pqgotest sslmode=verify-full"}``)
// go globalSessions.GC()
// }
//
package postgres
import (

View File

@@ -20,15 +20,16 @@
//
// Usage:
// import(
// _ "github.com/beego/beego/v2/server/web/session/redis"
// "github.com/beego/beego/v2/server/web/session"
//
// _ "github.com/beego/beego/v2/server/web/session/redis"
// "github.com/beego/beego/v2/server/web/session"
//
// )
//
// func init() {
// globalSessions, _ = session.NewManager("redis", ``{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:7070"}``)
// go globalSessions.GC()
// }
//
// func init() {
// globalSessions, _ = session.NewManager("redis", ``{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:7070"}``)
// go globalSessions.GC()
// }
package redis
import (

View File

@@ -20,15 +20,16 @@
//
// Usage:
// import(
// _ "github.com/beego/beego/v2/server/web/session/redis_cluster"
// "github.com/beego/beego/v2/server/web/session"
//
// _ "github.com/beego/beego/v2/server/web/session/redis_cluster"
// "github.com/beego/beego/v2/server/web/session"
//
// )
//
// func init() {
// globalSessions, _ = session.NewManager("redis_cluster", ``{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:7070;127.0.0.1:7071"}``)
// go globalSessions.GC()
// }
//
package redis_cluster
import (

View File

@@ -20,8 +20,10 @@
//
// Usage:
// import(
// _ "github.com/beego/beego/v2/server/web/session/redis_sentinel"
// "github.com/beego/beego/v2/server/web/session"
//
// _ "github.com/beego/beego/v2/server/web/session/redis_sentinel"
// "github.com/beego/beego/v2/server/web/session"
//
// )
//
// func init() {

View File

@@ -61,11 +61,12 @@ type CookieProvider session.CookieProvider
// SessionInit Init cookie session provider with max lifetime and config json.
// maxlifetime is ignored.
// json config:
// securityKey - hash string
// blockKey - gob encode hash string. it's saved as aes crypto.
// securityName - recognized name in encoded cookie string
// cookieName - cookie name
// maxage - cookie max life time.
//
// securityKey - hash string
// blockKey - gob encode hash string. it's saved as aes crypto.
// securityName - recognized name in encoded cookie string
// cookieName - cookie name
// maxage - cookie max life time.
func (pder *CookieProvider) SessionInit(maxlifetime int64, config string) error {
return (*session.CookieProvider)(pder).SessionInit(context.Background(), maxlifetime, config)
}

View File

@@ -16,14 +16,15 @@
//
// Usage:
// import(
// "github.com/beego/beego/v2/server/web/session"
//
// "github.com/beego/beego/v2/server/web/session"
//
// )
//
// func init() {
// globalSessions, _ = session.NewManager("memory", `{"cookieName":"gosessionid", "enableSetCookie,omitempty": true, "gclifetime":3600, "maxLifetime": 3600, "secure": false, "cookieLifeTime": 3600, "providerConfig": ""}`)
// go globalSessions.GC()
// }
//
// func init() {
// globalSessions, _ = session.NewManager("memory", `{"cookieName":"gosessionid", "enableSetCookie,omitempty": true, "gclifetime":3600, "maxLifetime": 3600, "secure": false, "cookieLifeTime": 3600, "providerConfig": ""}`)
// go globalSessions.GC()
// }
package session
import (

View File

@@ -91,21 +91,21 @@ func Htmlunquote(text string) string {
}
// URLFor returns url string with another registered controller handler with params.
// usage:
//
// URLFor(".index")
// print URLFor("index")
// router /login
// print URLFor("login")
// print URLFor("login", "next","/"")
// router /profile/:username
// print UrlFor("profile", ":username","John Doe")
// result:
// /
// /login
// /login?next=/
// /user/John%20Doe
// usage:
//
// URLFor(".index")
// print URLFor("index")
// router /login
// print URLFor("login")
// print URLFor("login", "next","/"")
// router /profile/:username
// print UrlFor("profile", ":username","John Doe")
// result:
// /
// /login
// /login?next=/
// /user/John%20Doe
func URLFor(endpoint string, values ...interface{}) string {
return web.URLFor(endpoint, values...)
}
@@ -135,12 +135,13 @@ func RenderForm(obj interface{}) template.HTML {
// MapGet getting value from map by keys
// usage:
// Data["m"] = M{
// "a": 1,
// "1": map[string]float64{
// "c": 4,
// },
// }
//
// Data["m"] = M{
// "a": 1,
// "1": map[string]float64{
// "c": 4,
// },
// }
//
// {{ map_get m "a" }} // return 1
// {{ map_get m 1 "c" }} // return 4

View File

@@ -17,16 +17,15 @@
// type DatabaseCheck struct {
// }
//
// func (dc *DatabaseCheck) Check() error {
// if dc.isConnected() {
// return nil
// } else {
// return errors.New("can't connect database")
// }
// }
// func (dc *DatabaseCheck) Check() error {
// if dc.isConnected() {
// return nil
// } else {
// return errors.New("can't connect database")
// }
// }
//
// AddHealthCheck("database",&DatabaseCheck{})
//
package toolbox
import (

View File

@@ -141,11 +141,16 @@ func (t *Task) GetPrev() time.Time {
// week0-60 means Sunday
// SetCron some signals
// * any time
// ,  separate signal
//
// * any time
// ,  separate signal
//
//    duration
// /n : do as n times of time duration
//
// /n : do as n times of time duration
//
// ///////////////////////////////////////////////////////
//
// 0/30 * * * * * every 30s
// 0 43 21 * * * 21:43
// 0 15 05 * * *    05:15

View File

@@ -19,32 +19,35 @@
// package controllers
//
// import (
// "github.com/beego/beego/v2"
// "github.com/beego/beego/v2/client/cache"
// "github.com/beego/beego/v2/server/web/captcha"
//
// "github.com/beego/beego/v2"
// "github.com/beego/beego/v2/client/cache"
// "github.com/beego/beego/v2/server/web/captcha"
//
// )
//
// var cpt *captcha.Captcha
//
// func init() {
// // use beego cache system store the captcha data
// store := cache.NewMemoryCache()
// cpt = captcha.NewWithFilter("/captcha/", store)
// }
// func init() {
// // use beego cache system store the captcha data
// store := cache.NewMemoryCache()
// cpt = captcha.NewWithFilter("/captcha/", store)
// }
//
// type MainController struct {
// beego.Controller
// }
// type MainController struct {
// beego.Controller
// }
//
// func (this *MainController) Get() {
// this.TplName = "index.tpl"
// }
// func (this *MainController) Get() {
// this.TplName = "index.tpl"
// }
//
// func (this *MainController) Post() {
// this.TplName = "index.tpl"
// func (this *MainController) Post() {
// this.TplName = "index.tpl"
//
// this.Data["Success"] = cpt.VerifyReq(this.Ctx.Request)
// }
//
// this.Data["Success"] = cpt.VerifyReq(this.Ctx.Request)
// }
// ```
//
// template usage
@@ -52,8 +55,10 @@
// ```
// {{.Success}}
// <form action="/" method="post">
// {{create_captcha}}
// <input name="captcha" type="text">
//
// {{create_captcha}}
// <input name="captcha" type="text">
//
// </form>
// ```
package captcha

View File

@@ -2,53 +2,51 @@
Package pagination provides utilities to setup a paginator within the
context of a http request.
Usage
# Usage
In your beego.Controller:
package controllers
package controllers
import "github.com/beego/beego/v2/server/web/pagination"
import "github.com/beego/beego/v2/server/web/pagination"
type PostsController struct {
beego.Controller
}
type PostsController struct {
beego.Controller
}
func (this *PostsController) ListAllPosts() {
// sets this.Data["paginator"] with the current offset (from the url query param)
postsPerPage := 20
paginator := pagination.SetPaginator(this.Ctx, postsPerPage, CountPosts())
// fetch the next 20 posts
this.Data["posts"] = ListPostsByOffsetAndLimit(paginator.Offset(), postsPerPage)
}
func (this *PostsController) ListAllPosts() {
// sets this.Data["paginator"] with the current offset (from the url query param)
postsPerPage := 20
paginator := pagination.SetPaginator(this.Ctx, postsPerPage, CountPosts())
// fetch the next 20 posts
this.Data["posts"] = ListPostsByOffsetAndLimit(paginator.Offset(), postsPerPage)
}
In your view templates:
{{if .paginator.HasPages}}
<ul class="pagination pagination">
{{if .paginator.HasPrev}}
<li><a href="{{.paginator.PageLinkFirst}}">{{ i18n .Lang "paginator.first_page"}}</a></li>
<li><a href="{{.paginator.PageLinkPrev}}">&laquo;</a></li>
{{else}}
<li class="disabled"><a>{{ i18n .Lang "paginator.first_page"}}</a></li>
<li class="disabled"><a>&laquo;</a></li>
{{end}}
{{range $index, $page := .paginator.Pages}}
<li{{if $.paginator.IsActive .}} class="active"{{end}}>
<a href="{{$.paginator.PageLink $page}}">{{$page}}</a>
</li>
{{end}}
{{if .paginator.HasNext}}
<li><a href="{{.paginator.PageLinkNext}}">&raquo;</a></li>
<li><a href="{{.paginator.PageLinkLast}}">{{ i18n .Lang "paginator.last_page"}}</a></li>
{{else}}
<li class="disabled"><a>&raquo;</a></li>
<li class="disabled"><a>{{ i18n .Lang "paginator.last_page"}}</a></li>
{{end}}
</ul>
{{end}}
{{if .paginator.HasPages}}
<ul class="pagination pagination">
{{if .paginator.HasPrev}}
<li><a href="{{.paginator.PageLinkFirst}}">{{ i18n .Lang "paginator.first_page"}}</a></li>
<li><a href="{{.paginator.PageLinkPrev}}">&laquo;</a></li>
{{else}}
<li class="disabled"><a>{{ i18n .Lang "paginator.first_page"}}</a></li>
<li class="disabled"><a>&laquo;</a></li>
{{end}}
{{range $index, $page := .paginator.Pages}}
<li{{if $.paginator.IsActive .}} class="active"{{end}}>
<a href="{{$.paginator.PageLink $page}}">{{$page}}</a>
</li>
{{end}}
{{if .paginator.HasNext}}
<li><a href="{{.paginator.PageLinkNext}}">&raquo;</a></li>
<li><a href="{{.paginator.PageLinkLast}}">{{ i18n .Lang "paginator.last_page"}}</a></li>
{{else}}
<li class="disabled"><a>&raquo;</a></li>
<li class="disabled"><a>{{ i18n .Lang "paginator.last_page"}}</a></li>
{{end}}
</ul>
{{end}}
*/
package pagination

View File

@@ -47,11 +47,11 @@ func (p *Paginator) Page() int {
//
// Usage (in a view template):
//
// {{range $index, $page := .paginator.Pages}}
// <li{{if $.paginator.IsActive .}} class="active"{{end}}>
// <a href="{{$.paginator.PageLink $page}}">{{$page}}</a>
// </li>
// {{end}}
// {{range $index, $page := .paginator.Pages}}
// <li{{if $.paginator.IsActive .}} class="active"{{end}}>
// <a href="{{$.paginator.PageLink $page}}">{{$page}}</a>
// </li>
// {{end}}
func (p *Paginator) Pages() []int {
return (*pagination.Paginator)(p).Pages()
}

View File

@@ -34,13 +34,15 @@ type CustomFunc func(v *Validation, obj interface{}, key string)
// AddCustomFunc Add a custom function to validation
// The name can not be:
// Clear
// HasErrors
// ErrorMap
// Error
// Check
// Valid
// NoMatch
//
// Clear
// HasErrors
// ErrorMap
// Error
// Check
// Valid
// NoMatch
//
// If the name is same with exists function, it will replace the origin valid function
func AddCustomFunc(name string, f CustomFunc) error {
return validation.AddCustomFunc(name, func(v *validation.Validation, obj interface{}, key string) {

View File

@@ -42,7 +42,6 @@
// log.Println(v.Error.Key, v.Error.Message)
// }
// }
//
package validation
import (

View File

@@ -51,26 +51,27 @@ var once sync.Once
// SetDefaultMessage set default messages
// if not set, the default messages are
// "Required": "Can not be empty",
// "Min": "Minimum is %d",
// "Max": "Maximum is %d",
// "Range": "Range is %d to %d",
// "MinSize": "Minimum size is %d",
// "MaxSize": "Maximum size is %d",
// "Length": "Required length is %d",
// "Alpha": "Must be valid alpha characters",
// "Numeric": "Must be valid numeric characters",
// "AlphaNumeric": "Must be valid alpha or numeric characters",
// "Match": "Must match %s",
// "NoMatch": "Must not match %s",
// "AlphaDash": "Must be valid alpha or numeric or dash(-_) characters",
// "Email": "Must be a valid email address",
// "IP": "Must be a valid ip address",
// "Base64": "Must be valid base64 characters",
// "Mobile": "Must be valid mobile number",
// "Tel": "Must be valid telephone number",
// "Phone": "Must be valid telephone or mobile phone number",
// "ZipCode": "Must be valid zipcode",
//
// "Required": "Can not be empty",
// "Min": "Minimum is %d",
// "Max": "Maximum is %d",
// "Range": "Range is %d to %d",
// "MinSize": "Minimum size is %d",
// "MaxSize": "Maximum size is %d",
// "Length": "Required length is %d",
// "Alpha": "Must be valid alpha characters",
// "Numeric": "Must be valid numeric characters",
// "AlphaNumeric": "Must be valid alpha or numeric characters",
// "Match": "Must match %s",
// "NoMatch": "Must not match %s",
// "AlphaDash": "Must be valid alpha or numeric or dash(-_) characters",
// "Email": "Must be a valid email address",
// "IP": "Must be a valid ip address",
// "Base64": "Must be valid base64 characters",
// "Mobile": "Must be valid mobile number",
// "Tel": "Must be valid telephone number",
// "Phone": "Must be valid telephone or mobile phone number",
// "ZipCode": "Must be valid zipcode",
func SetDefaultMessage(msg map[string]string) {
validation.SetDefaultMessage(msg)
}