Merge pull request #5232 from flycash/develop

httplib: fix unstable unit test which use the httplib.org
This commit is contained in:
Ming Deng 2023-06-04 18:08:36 +08:00 committed by GitHub
commit 27ae25ec12
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
86 changed files with 1166 additions and 917 deletions

View File

@ -1,4 +1,5 @@
# developing # developing
- [httplib: fix unstable unit test which use the httplib.org](https://github.com/beego/beego/pull/5232)
# v2.1.0 # v2.1.0
- [unified gopkg.in/yaml version to v2](https://github.com/beego/beego/pull/5169) - [unified gopkg.in/yaml version to v2](https://github.com/beego/beego/pull/5169)

View File

@ -15,6 +15,8 @@ Beego is composed of four parts:
**Please use RELEASE version, or master branch which contains the latest bug fix** **Please use RELEASE version, or master branch which contains the latest bug fix**
**We will remove the adapter package in v2.2.0 which will be released in Aug 2023**
## Quick Start ## Quick Start
[Old Doc - github](https://github.com/beego/beedoc) [Old Doc - github](https://github.com/beego/beedoc)

View File

@ -24,7 +24,8 @@ import (
// FilterMonitorFunc is default monitor filter when admin module is enable. // 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. // if this func returns, admin module records qps for this request by condition of this function logic.
// usage: // 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" { // if method == "POST" {
// return false // return false
// } // }
@ -35,8 +36,8 @@ import (
// return false // return false
// } // }
// return true // return true
// } // }
// beego.FilterMonitorFunc = MyFilterMonitor. // beego.FilterMonitorFunc = MyFilterMonitor.
var FilterMonitorFunc func(string, string, time.Duration, string, int) bool var FilterMonitorFunc func(string, string, time.Duration, string, int) bool
// PrintTree prints all registered routers. // 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. // Router adds a patterned controller handler to BeeApp.
// it's an alias method of HttpServer.Router. // it's an alias method of HttpServer.Router.
// usage: // 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/:id([0-9]+)", &controllers.RController{})
// beego.Router("/api/list",&RestController{},"*:ListFood") //
// beego.Router("/api/create",&RestController{},"post:CreateFood") // custom rules
// beego.Router("/api/update",&RestController{},"put:UpdateFood") // beego.Router("/api/list",&RestController{},"*:ListFood")
// beego.Router("/api/delete",&RestController{},"delete:DeleteFood") // 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 { func Router(rootpath string, c ControllerInterface, mappingMethods ...string) *App {
return (*App)(web.Router(rootpath, c, mappingMethods...)) 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. // method type (e.g. "GET" or "POST") for selective removal.
// //
// Usage (replace "GET" with "*" for all methods): // 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 { func UnregisterFixedRoute(fixedRoute string, method string) *App {
return (*App)(web.UnregisterFixedRoute(fixedRoute, method)) 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 // Include will generate router file in the router/xxx.go from the controller's comments
// usage: // usage:
// beego.Include(&BankAccount{}, &OrderController{},&RefundController{},&ReceiptController{}) // beego.Include(&BankAccount{}, &OrderController{},&RefundController{},&ReceiptController{})
// type BankAccount struct{ //
// beego.Controller // type BankAccount struct{
// } // beego.Controller
// }
// //
// register the function // register the function
// func (b *BankAccount)Mapping(){ //
// b.Mapping("ShowAccount" , b.ShowAccount) // func (b *BankAccount)Mapping(){
// b.Mapping("ModifyAccount", b.ModifyAccount) // b.Mapping("ShowAccount" , b.ShowAccount)
// } // b.Mapping("ModifyAccount", b.ModifyAccount)
// }
// //
// //@router /account/:id [get] // //@router /account/:id [get]
// func (b *BankAccount) ShowAccount(){
// //logic
// }
// //
// func (b *BankAccount) ShowAccount(){
// //logic
// }
// //
// //@router /account/:id [post] // //@router /account/:id [post]
// func (b *BankAccount) ModifyAccount(){ //
// //logic // func (b *BankAccount) ModifyAccount(){
// } // //logic
// }
// //
// the comments @router url methodlist // the comments @router url methodlist
// url support all the function Router's pattern // 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 // Get used to register router for Get method
// usage: // 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 { func Get(rootpath string, f FilterFunc) *App {
return (*App)(web.Get(rootpath, func(ctx *context.Context) { return (*App)(web.Get(rootpath, func(ctx *context.Context) {
f((*context2.Context)(ctx)) f((*context2.Context)(ctx))
@ -164,9 +170,10 @@ func Get(rootpath string, f FilterFunc) *App {
// Post used to register router for Post method // Post used to register router for Post method
// usage: // 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 { func Post(rootpath string, f FilterFunc) *App {
return (*App)(web.Post(rootpath, func(ctx *context.Context) { return (*App)(web.Post(rootpath, func(ctx *context.Context) {
f((*context2.Context)(ctx)) f((*context2.Context)(ctx))
@ -175,9 +182,10 @@ func Post(rootpath string, f FilterFunc) *App {
// Delete used to register router for Delete method // Delete used to register router for Delete method
// usage: // 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 { func Delete(rootpath string, f FilterFunc) *App {
return (*App)(web.Delete(rootpath, func(ctx *context.Context) { return (*App)(web.Delete(rootpath, func(ctx *context.Context) {
f((*context2.Context)(ctx)) f((*context2.Context)(ctx))
@ -186,9 +194,10 @@ func Delete(rootpath string, f FilterFunc) *App {
// Put used to register router for Put method // Put used to register router for Put method
// usage: // 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 { func Put(rootpath string, f FilterFunc) *App {
return (*App)(web.Put(rootpath, func(ctx *context.Context) { return (*App)(web.Put(rootpath, func(ctx *context.Context) {
f((*context2.Context)(ctx)) f((*context2.Context)(ctx))
@ -197,9 +206,10 @@ func Put(rootpath string, f FilterFunc) *App {
// Head used to register router for Head method // Head used to register router for Head method
// usage: // 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 { func Head(rootpath string, f FilterFunc) *App {
return (*App)(web.Head(rootpath, func(ctx *context.Context) { return (*App)(web.Head(rootpath, func(ctx *context.Context) {
f((*context2.Context)(ctx)) f((*context2.Context)(ctx))
@ -208,9 +218,10 @@ func Head(rootpath string, f FilterFunc) *App {
// Options used to register router for Options method // Options used to register router for Options method
// usage: // 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 { func Options(rootpath string, f FilterFunc) *App {
return (*App)(web.Options(rootpath, func(ctx *context.Context) { return (*App)(web.Options(rootpath, func(ctx *context.Context) {
f((*context2.Context)(ctx)) f((*context2.Context)(ctx))
@ -219,9 +230,10 @@ func Options(rootpath string, f FilterFunc) *App {
// Patch used to register router for Patch method // Patch used to register router for Patch method
// usage: // 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 { func Patch(rootpath string, f FilterFunc) *App {
return (*App)(web.Patch(rootpath, func(ctx *context.Context) { return (*App)(web.Patch(rootpath, func(ctx *context.Context) {
f((*context2.Context)(ctx)) f((*context2.Context)(ctx))
@ -230,9 +242,10 @@ func Patch(rootpath string, f FilterFunc) *App {
// Any used to register router for all methods // Any used to register router for all methods
// usage: // 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 { func Any(rootpath string, f FilterFunc) *App {
return (*App)(web.Any(rootpath, func(ctx *context.Context) { return (*App)(web.Any(rootpath, func(ctx *context.Context) {
f((*context2.Context)(ctx)) f((*context2.Context)(ctx))
@ -241,9 +254,10 @@ func Any(rootpath string, f FilterFunc) *App {
// Handler used to register a Handler router // Handler used to register a Handler router
// usage: // 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 { func Handler(rootpath string, h http.Handler, options ...interface{}) *App {
return (*App)(web.Handler(rootpath, h, options...)) return (*App)(web.Handler(rootpath, h, options...))
} }

View File

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

View File

@ -20,12 +20,13 @@
// //
// Usage: // Usage:
// import( // 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 package memcache
import ( import (

View File

@ -20,12 +20,13 @@
// //
// Usage: // Usage:
// import( // 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 package redis
import ( import (

View File

@ -14,29 +14,31 @@
// Package config is used to parse config. // Package config is used to parse config.
// Usage: // Usage:
// import "github.com/beego/beego/v2/core/config" //
// import "github.com/beego/beego/v2/core/config"
//
// Examples. // 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.Set(key, val string) error
// cnf.String(key string) string // cnf.String(key string) string
// cnf.Strings(key string) []string // cnf.Strings(key string) []string
// cnf.Int(key string) (int, error) // cnf.Int(key string) (int, error)
// cnf.Int64(key string) (int64, error) // cnf.Int64(key string) (int64, error)
// cnf.Bool(key string) (bool, error) // cnf.Bool(key string) (bool, error)
// cnf.Float(key string) (float64, error) // cnf.Float(key string) (float64, error)
// cnf.DefaultString(key string, defaultVal string) string // cnf.DefaultString(key string, defaultVal string) string
// cnf.DefaultStrings(key string, defaultVal []string) []string // cnf.DefaultStrings(key string, defaultVal []string) []string
// cnf.DefaultInt(key string, defaultVal int) int // cnf.DefaultInt(key string, defaultVal int) int
// cnf.DefaultInt64(key string, defaultVal int64) int64 // cnf.DefaultInt64(key string, defaultVal int64) int64
// cnf.DefaultBool(key string, defaultVal bool) bool // cnf.DefaultBool(key string, defaultVal bool) bool
// cnf.DefaultFloat(key string, defaultVal float64) float64 // cnf.DefaultFloat(key string, defaultVal float64) float64
// cnf.DIY(key string) (interface{}, error) // cnf.DIY(key string) (interface{}, error)
// cnf.GetSection(section string) (map[string]string, error) // cnf.GetSection(section string) (map[string]string, error)
// cnf.SaveConfigFile(filename string) error // cnf.SaveConfigFile(filename string) error
package config package config
import ( import (
@ -128,6 +130,7 @@ func ExpandValueEnvForMap(m map[string]interface{}) map[string]interface{} {
// //
// It accept value formats "${env}" , "${env||}}" , "${env||defaultValue}" , "defaultvalue". // It accept value formats "${env}" , "${env||}}" , "${env||defaultValue}" , "defaultvalue".
// Examples: // Examples:
//
// v1 := config.ExpandValueEnv("${GOPATH}") // return the GOPATH environment variable. // v1 := config.ExpandValueEnv("${GOPATH}") // return the GOPATH environment variable.
// v2 := config.ExpandValueEnv("${GOAsta||/usr/local/go}") // return the default value "/usr/local/go/". // v2 := config.ExpandValueEnv("${GOAsta||/usr/local/go}") // return the default value "/usr/local/go/".
// v3 := config.ExpandValueEnv("Astaxie") // return the value "Astaxie". // 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 not use this file except in compliance with the License.
// You may obtain a copy of the License at // 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 // Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, // distributed under the License is distributed on an "AS IS" BASIS,

View File

@ -19,13 +19,13 @@
// go install github.com/beego/x2j. // go install github.com/beego/x2j.
// //
// Usage: // 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 package xml
import ( import (

View File

@ -19,13 +19,13 @@
// go install github.com/beego/goyaml2 // go install github.com/beego/goyaml2
// //
// Usage: // 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 package yaml
import ( import (

View File

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

View File

@ -296,31 +296,33 @@ func (c *Controller) GetFile(key string) (multipart.File, *multipart.FileHeader,
// GetFiles return multi-upload files // GetFiles return multi-upload files
// files, err:=c.GetFiles("myfiles") // files, err:=c.GetFiles("myfiles")
//
// if err != nil { // if err != nil {
// http.Error(w, err.Error(), http.StatusNoContent) // http.Error(w, err.Error(), http.StatusNoContent)
// return // return
// } // }
// for i, _ := range files { //
// //for each fileheader, get a handle to the actual file // for i, _ := range files {
// file, err := files[i].Open() // //for each fileheader, get a handle to the actual file
// defer file.Close() // file, err := files[i].Open()
// if err != nil { // defer file.Close()
// http.Error(w, err.Error(), http.StatusInternalServerError) // if err != nil {
// return // 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) { func (c *Controller) GetFiles(key string) ([]*multipart.FileHeader, error) {
return (*web.Controller)(c).GetFiles(key) 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. // ErrorHandler registers http.HandlerFunc to each http err code string.
// usage: // usage:
// beego.ErrorHandler("404",NotFound) //
// beego.ErrorHandler("404",NotFound)
// beego.ErrorHandler("500",InternalServerError) // beego.ErrorHandler("500",InternalServerError)
func ErrorHandler(code string, h http.HandlerFunc) *App { func ErrorHandler(code string, h http.HandlerFunc) *App {
return (*App)(web.ErrorHandler(code, h)) 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. // ErrorController registers ControllerInterface to each http err code string.
// usage: // usage:
// beego.ErrorController(&controllers.ErrorController{}) //
// beego.ErrorController(&controllers.ErrorController{})
func ErrorController(c ControllerInterface) *App { func ErrorController(c ControllerInterface) *App {
return (*App)(web.ErrorController(c)) return (*App)(web.ErrorController(c))
} }

View File

@ -18,28 +18,30 @@
// Usage: // Usage:
// //
// import( // 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) { // func handler(w http.ResponseWriter, r *http.Request) {
// w.Write([]byte("WORLD!")) // w.Write([]byte("WORLD!"))
// } // }
// //
// func main() { // func main() {
// mux := http.NewServeMux() // mux := http.NewServeMux()
// mux.HandleFunc("/hello", handler) // mux.HandleFunc("/hello", handler)
// //
// err := grace.ListenAndServe("localhost:8080", mux) // err := grace.ListenAndServe("localhost:8080", mux)
// if err != nil { // if err != nil {
// log.Println(err) // log.Println(err)
// } // }
// log.Println("Server on 8080 stopped") // log.Println("Server on 8080 stopped")
// os.Exit(0) // os.Exit(0)
// } // }
package grace package grace
import ( import (

View File

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

View File

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

View File

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

View File

@ -50,7 +50,6 @@
// // delete // // delete
// num, err = o.Delete(&u) // num, err = o.Delete(&u)
// } // }
//
package orm package orm
import ( import (
@ -170,8 +169,9 @@ func (o *ormer) QueryM2M(md interface{}, name string) QueryM2Mer {
// args are limit, offset int and order string. // args are limit, offset int and order string.
// //
// example: // 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. // make sure the relation is defined in model struct tags.
func (o *ormer) LoadRelated(md interface{}, name string, args ...interface{}) (int64, error) { 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 // RawSeter raw query seter
// create From Ormer.Raw // create From Ormer.Raw
// for example: // 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 type RawSeter orm.RawSeter

View File

@ -15,6 +15,7 @@
// Package apiauth provides handlers to enable apiauth support. // Package apiauth provides handlers to enable apiauth support.
// //
// Simple Usage: // Simple Usage:
//
// import( // import(
// "github.com/beego/beego/v2" // "github.com/beego/beego/v2"
// "github.com/beego/beego/v2/server/web/filter/apiauth" // "github.com/beego/beego/v2/server/web/filter/apiauth"
@ -37,11 +38,11 @@
// //
// Information: // 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 // 1. appid
// //
// appid is assigned to the application // appid is assigned to the application
// //
// 2. signature // 2. signature
// //
@ -51,8 +52,7 @@
// //
// 3. timestamp: // 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 package apiauth
import ( import (

View File

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

View File

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

View File

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

View File

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

View File

@ -20,15 +20,16 @@
// //
// Usage: // Usage:
// import( // 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() { // func init() {
// globalSessions, _ = session.NewManager("couchbase", ``{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"http://host:port/, Pool, Bucket"}``) // globalSessions, _ = session.NewManager("couchbase", ``{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"http://host:port/, Pool, Bucket"}``)
// go globalSessions.GC() // go globalSessions.GC()
// } // }
//
package couchbase package couchbase
import ( import (

View File

@ -20,15 +20,16 @@
// //
// Usage: // Usage:
// import( // 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() { // func init() {
// globalSessions, _ = session.NewManager("memcache", ``{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:11211"}``) // globalSessions, _ = session.NewManager("memcache", ``{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:11211"}``)
// go globalSessions.GC() // go globalSessions.GC()
// } // }
//
package memcache package memcache
import ( import (

View File

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

View File

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

View File

@ -20,15 +20,16 @@
// //
// Usage: // Usage:
// import( // 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() { // func init() {
// globalSessions, _ = session.NewManager("redis", ``{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:7070"}``) // globalSessions, _ = session.NewManager("redis", ``{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:7070"}``)
// go globalSessions.GC() // go globalSessions.GC()
// } // }
//
package redis package redis
import ( import (

View File

@ -20,15 +20,16 @@
// //
// Usage: // Usage:
// import( // 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() { // func init() {
// globalSessions, _ = session.NewManager("redis_cluster", ``{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:7070;127.0.0.1:7071"}``) // globalSessions, _ = session.NewManager("redis_cluster", ``{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:7070;127.0.0.1:7071"}``)
// go globalSessions.GC() // go globalSessions.GC()
// } // }
//
package redis_cluster package redis_cluster
import ( import (

View File

@ -20,8 +20,10 @@
// //
// Usage: // Usage:
// import( // 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() { // func init() {

View File

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

View File

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

View File

@ -91,21 +91,21 @@ func Htmlunquote(text string) string {
} }
// URLFor returns url string with another registered controller handler with params. // URLFor returns url string with another registered controller handler with params.
// usage:
// //
// URLFor(".index") // usage:
// 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
// //
// 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 { func URLFor(endpoint string, values ...interface{}) string {
return web.URLFor(endpoint, values...) return web.URLFor(endpoint, values...)
} }
@ -135,12 +135,13 @@ func RenderForm(obj interface{}) template.HTML {
// MapGet getting value from map by keys // MapGet getting value from map by keys
// usage: // usage:
// Data["m"] = M{ //
// "a": 1, // Data["m"] = M{
// "1": map[string]float64{ // "a": 1,
// "c": 4, // "1": map[string]float64{
// }, // "c": 4,
// } // },
// }
// //
// {{ map_get m "a" }} // return 1 // {{ map_get m "a" }} // return 1
// {{ map_get m 1 "c" }} // return 4 // {{ map_get m 1 "c" }} // return 4

View File

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

View File

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

View File

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

View File

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

View File

@ -47,11 +47,11 @@ func (p *Paginator) Page() int {
// //
// Usage (in a view template): // Usage (in a view template):
// //
// {{range $index, $page := .paginator.Pages}} // {{range $index, $page := .paginator.Pages}}
// <li{{if $.paginator.IsActive .}} class="active"{{end}}> // <li{{if $.paginator.IsActive .}} class="active"{{end}}>
// <a href="{{$.paginator.PageLink $page}}">{{$page}}</a> // <a href="{{$.paginator.PageLink $page}}">{{$page}}</a>
// </li> // </li>
// {{end}} // {{end}}
func (p *Paginator) Pages() []int { func (p *Paginator) Pages() []int {
return (*pagination.Paginator)(p).Pages() 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 // AddCustomFunc Add a custom function to validation
// The name can not be: // The name can not be:
// Clear //
// HasErrors // Clear
// ErrorMap // HasErrors
// Error // ErrorMap
// Check // Error
// Valid // Check
// NoMatch // Valid
// NoMatch
//
// If the name is same with exists function, it will replace the origin valid function // If the name is same with exists function, it will replace the origin valid function
func AddCustomFunc(name string, f CustomFunc) error { func AddCustomFunc(name string, f CustomFunc) error {
return validation.AddCustomFunc(name, func(v *validation.Validation, obj interface{}, key string) { 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) // log.Println(v.Error.Key, v.Error.Message)
// } // }
// } // }
//
package validation package validation
import ( import (

View File

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

View File

@ -23,9 +23,10 @@ import (
"testing" "testing"
"time" "time"
"github.com/beego/beego/v2/core/berror"
"github.com/bits-and-blooms/bloom/v3" "github.com/bits-and-blooms/bloom/v3"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/beego/beego/v2/core/berror"
) )
type MockDB struct { type MockDB struct {

View File

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

View File

@ -20,12 +20,13 @@
// //
// Usage: // Usage:
// import( // 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 package memcache
import ( import (

View File

@ -20,12 +20,13 @@
// //
// Usage: // Usage:
// import( // 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 package redis
import ( import (

View File

@ -17,7 +17,6 @@ package httplib
import ( import (
"bytes" "bytes"
"io" "io"
"io/ioutil"
"net/http" "net/http"
) )
@ -105,7 +104,7 @@ func (c *Client) handleCarrier(value interface{}, req *BeegoHTTPRequest) error {
if err != nil { if err != nil {
return err return err
} }
req.resp.Body = ioutil.NopCloser(bytes.NewReader(b)) req.resp.Body = io.NopCloser(bytes.NewReader(b))
carrier.SetHTTPResponse(req.resp) carrier.SetHTTPResponse(req.resp)
} }
if carrier, ok := value.(HTTPBodyCarrier); ok { if carrier, ok := value.(HTTPBodyCarrier); ok {
@ -113,7 +112,7 @@ func (c *Client) handleCarrier(value interface{}, req *BeegoHTTPRequest) error {
if err != nil { if err != nil {
return err return err
} }
reader := ioutil.NopCloser(bytes.NewReader(b)) reader := io.NopCloser(bytes.NewReader(b))
carrier.SetReader(reader) carrier.SetReader(reader)
} }
if carrier, ok := value.(HTTPBytesCarrier); ok { if carrier, ok := value.(HTTPBytesCarrier); ok {

View File

@ -15,12 +15,17 @@
package httplib package httplib
import ( import (
"encoding/json"
"encoding/xml" "encoding/xml"
"io" "io"
"io/ioutil" "net"
"net/http" "net/http"
"testing" "testing"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"gopkg.in/yaml.v3"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -32,13 +37,13 @@ func TestNewClient(t *testing.T) {
} }
type slideShowResponse struct { type slideShowResponse struct {
Resp *http.Response Resp *http.Response `json:"resp,omitempty"`
bytes []byte bytes []byte `json:"bytes,omitempty"`
StatusCode int StatusCode int `json:"status_code,omitempty"`
Body io.ReadCloser Body io.ReadCloser `json:"body,omitempty"`
Header map[string][]string Header map[string][]string `json:"header,omitempty"`
Slideshow slideshow `json:"slideshow" yaml:"slideshow"` Slideshow slideshow `json:"slideshow,omitempty" yaml:"slideshow" xml:"slideshow"`
} }
func (r *slideShowResponse) SetHTTPResponse(resp *http.Response) { func (r *slideShowResponse) SetHTTPResponse(resp *http.Response) {
@ -66,7 +71,7 @@ func (r *slideShowResponse) String() string {
} }
type slideshow struct { type slideshow struct {
XMLName xml.Name `xml:"slideshow"` //XMLName xml.Name `xml:"slideshow"`
Title string `json:"title" yaml:"title" xml:"title,attr"` Title string `json:"title" yaml:"title" xml:"title,attr"`
Author string `json:"author" yaml:"author" xml:"author,attr"` Author string `json:"author" yaml:"author" xml:"author,attr"`
@ -80,63 +85,122 @@ type slide struct {
Title string `json:"title" yaml:"title" xml:"title"` Title string `json:"title" yaml:"title" xml:"title"`
} }
func TestClientHandleCarrier(t *testing.T) { type ClientTestSuite struct {
v := "beego" suite.Suite
client, err := NewClient("test", "http://httpbin.org/", l net.Listener
WithUserAgent(v))
if err != nil {
t.Fatal(err)
}
s := &slideShowResponse{}
err = client.Get(s, "/json")
if err != nil {
t.Fatal(err)
}
defer s.Body.Close()
assert.NotNil(t, s.Resp)
assert.NotNil(t, s.Body)
assert.Equal(t, "429", s.Header["Content-Length"][0])
assert.Equal(t, 200, s.StatusCode)
b, err := ioutil.ReadAll(s.Body)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, 429, len(b))
assert.Equal(t, s.String(), string(b))
} }
func TestClientGet(t *testing.T) { func (c *ClientTestSuite) SetupSuite() {
client, err := NewClient("test", "http://httpbin.org/") listener, err := net.Listen("tcp", ":8080")
require.NoError(c.T(), err)
c.l = listener
handler := http.NewServeMux()
handler.HandleFunc("/json", func(writer http.ResponseWriter, request *http.Request) {
data, _ := json.Marshal(slideshow{})
_, _ = writer.Write(data)
})
ssr := slideShowResponse{
Slideshow: slideshow{
Title: "Sample Slide Show",
Slides: []slide{
{
Title: "Content",
},
{
Title: "Overview",
},
},
},
}
handler.HandleFunc("/req2resp", func(writer http.ResponseWriter, request *http.Request) {
data, _ := io.ReadAll(request.Body)
_, _ = writer.Write(data)
})
handler.HandleFunc("/get", func(writer http.ResponseWriter, request *http.Request) {
data, _ := json.Marshal(ssr)
_, _ = writer.Write(data)
})
handler.HandleFunc("/get/xml", func(writer http.ResponseWriter, request *http.Request) {
data, err := xml.Marshal(ssr.Slideshow)
require.NoError(c.T(), err)
_, _ = writer.Write(data)
})
handler.HandleFunc("/get/yaml", func(writer http.ResponseWriter, request *http.Request) {
data, _ := yaml.Marshal(ssr)
_, _ = writer.Write(data)
})
go func() {
_ = http.Serve(listener, handler)
}()
}
func (c *ClientTestSuite) TearDownSuite() {
_ = c.l.Close()
}
func TestClient(t *testing.T) {
suite.Run(t, &ClientTestSuite{})
}
func (c *ClientTestSuite) TestClientHandleCarrier() {
t := c.T()
v := "beego"
client, err := NewClient("test", "http://localhost:8080/",
WithUserAgent(v))
require.NoError(t, err)
resp := &slideShowResponse{}
err = client.Get(resp, "/json")
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
assert.NotNil(t, resp.Resp)
assert.NotNil(t, resp.Body)
assert.Equal(t, "48", resp.Header["Content-Length"][0])
assert.Equal(t, 200, resp.StatusCode)
b, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, 48, len(b))
assert.Equal(t, resp.String(), string(b))
}
func (c *ClientTestSuite) TestClientGet() {
t := c.T()
client, err := NewClient("test", "http://localhost:8080/")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
// json // json
var s *slideShowResponse var s slideShowResponse
err = client.Get(&s, "/json") err = client.Get(&s, "/get")
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
assert.Equal(t, "Sample Slide Show", s.Slideshow.Title) assert.Equal(t, "Sample Slide Show", s.Slideshow.Title)
assert.Equal(t, 2, len(s.Slideshow.Slides)) assert.Equal(t, 2, len(s.Slideshow.Slides))
assert.Equal(t, "Overview", s.Slideshow.Slides[1].Title) assert.Equal(t, "Overview", s.Slideshow.Slides[1].Title)
// xml // xml
var ssp *slideshow var ss slideshow
err = client.Get(&ssp, "/base64/PD94bWwgPz48c2xpZGVzaG93CnRpdGxlPSJTYW1wbGUgU2xpZGUgU2hvdyIKZGF0ZT0iRGF0ZSBvZiBwdWJsaWNhdGlvbiIKYXV0aG9yPSJZb3VycyBUcnVseSI+PHNsaWRlIHR5cGU9ImFsbCI+PHRpdGxlPldha2UgdXAgdG8gV29uZGVyV2lkZ2V0cyE8L3RpdGxlPjwvc2xpZGU+PHNsaWRlIHR5cGU9ImFsbCI+PHRpdGxlPk92ZXJ2aWV3PC90aXRsZT48aXRlbT5XaHkgPGVtPldvbmRlcldpZGdldHM8L2VtPiBhcmUgZ3JlYXQ8L2l0ZW0+PGl0ZW0vPjxpdGVtPldobyA8ZW0+YnV5czwvZW0+IFdvbmRlcldpZGdldHM8L2l0ZW0+PC9zbGlkZT48L3NsaWRlc2hvdz4=") err = client.Get(&ss, "/get/xml")
if err != nil { require.NoError(t, err)
t.Fatal(err) assert.Equal(t, "Sample Slide Show", ss.Title)
} assert.Equal(t, 2, len(ss.Slides))
assert.Equal(t, "Sample Slide Show", ssp.Title) assert.Equal(t, "Overview", ss.Slides[1].Title)
assert.Equal(t, 2, len(ssp.Slides))
assert.Equal(t, "Overview", ssp.Slides[1].Title)
// yaml // yaml
s = nil s = slideShowResponse{}
err = client.Get(&s, "/base64/c2xpZGVzaG93OgogIGF1dGhvcjogWW91cnMgVHJ1bHkKICBkYXRlOiBkYXRlIG9mIHB1YmxpY2F0aW9uCiAgc2xpZGVzOgogIC0gdGl0bGU6IFdha2UgdXAgdG8gV29uZGVyV2lkZ2V0cyEKICAgIHR5cGU6IGFsbAogIC0gaXRlbXM6CiAgICAtIFdoeSA8ZW0+V29uZGVyV2lkZ2V0czwvZW0+IGFyZSBncmVhdAogICAgLSBXaG8gPGVtPmJ1eXM8L2VtPiBXb25kZXJXaWRnZXRzCiAgICB0aXRsZTogT3ZlcnZpZXcKICAgIHR5cGU6IGFsbAogIHRpdGxlOiBTYW1wbGUgU2xpZGUgU2hvdw==") err = client.Get(&s, "/get/yaml")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -145,72 +209,82 @@ func TestClientGet(t *testing.T) {
assert.Equal(t, "Overview", s.Slideshow.Slides[1].Title) assert.Equal(t, "Overview", s.Slideshow.Slides[1].Title)
} }
func TestClientPost(t *testing.T) { func (c *ClientTestSuite) TestClientPost() {
client, err := NewClient("test", "http://httpbin.org") t := c.T()
if err != nil { client, err := NewClient("test", "http://localhost:8080")
t.Fatal(err) require.NoError(t, err)
input := slideShowResponse{
Slideshow: slideshow{
Title: "Sample Slide Show",
Slides: []slide{
{
Title: "Content",
},
{
Title: "Overview",
},
},
},
} }
resp := &slideShowResponse{} jsonStr, err := json.Marshal(input)
err = client.Get(resp, "/json") require.NoError(t, err)
if err != nil { resp := slideShowResponse{}
t.Fatal(err) err = client.Post(&resp, "/req2resp", jsonStr)
} require.NoError(t, err)
assert.Equal(t, input.Slideshow, resp.Slideshow)
jsonStr := resp.String()
err = client.Post(resp, "/post", jsonStr)
if err != nil {
t.Fatal(err)
}
assert.NotNil(t, resp)
assert.Equal(t, http.MethodPost, resp.Resp.Request.Method) assert.Equal(t, http.MethodPost, resp.Resp.Request.Method)
} }
func TestClientPut(t *testing.T) { func (c *ClientTestSuite) TestClientPut() {
client, err := NewClient("test", "http://httpbin.org") t := c.T()
if err != nil { client, err := NewClient("test", "http://localhost:8080")
t.Fatal(err) require.NoError(t, err)
input := slideShowResponse{
Slideshow: slideshow{
Title: "Sample Slide Show",
Slides: []slide{
{
Title: "Content",
},
{
Title: "Overview",
},
},
},
} }
resp := &slideShowResponse{} jsonStr, err := json.Marshal(input)
err = client.Get(resp, "/json") require.NoError(t, err)
if err != nil { resp := slideShowResponse{}
t.Fatal(err) err = client.Put(&resp, "/req2resp", jsonStr)
} require.NoError(t, err)
assert.Equal(t, input.Slideshow, resp.Slideshow)
jsonStr := resp.String()
err = client.Put(resp, "/put", jsonStr)
if err != nil {
t.Fatal(err)
}
assert.NotNil(t, resp)
assert.Equal(t, http.MethodPut, resp.Resp.Request.Method) assert.Equal(t, http.MethodPut, resp.Resp.Request.Method)
} }
func TestClientDelete(t *testing.T) { func (c *ClientTestSuite) TestClientDelete() {
client, err := NewClient("test", "http://httpbin.org") t := c.T()
if err != nil { client, err := NewClient("test", "http://localhost:8080")
t.Fatal(err) require.NoError(t, err)
}
resp := &slideShowResponse{} resp := &slideShowResponse{}
err = client.Delete(resp, "/delete") err = client.Delete(resp, "/req2resp")
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
defer resp.Resp.Body.Close() defer resp.Resp.Body.Close()
assert.NotNil(t, resp) assert.NotNil(t, resp)
assert.Equal(t, http.MethodDelete, resp.Resp.Request.Method) assert.Equal(t, http.MethodDelete, resp.Resp.Request.Method)
} }
func TestClientHead(t *testing.T) { func (c *ClientTestSuite) TestClientHead() {
client, err := NewClient("test", "http://beego.gocn.vip") t := c.T()
if err != nil { client, err := NewClient("test", "http://localhost:8080")
t.Fatal(err) require.NoError(t, err)
}
resp := &slideShowResponse{} resp := &slideShowResponse{}
err = client.Head(resp, "") err = client.Head(resp, "/req2resp")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

View File

@ -27,7 +27,6 @@
// t.Fatal(err) // t.Fatal(err)
// } // }
// fmt.Println(str) // fmt.Println(str)
//
package httplib package httplib
import ( import (
@ -225,9 +224,9 @@ func (b *BeegoHTTPRequest) SetTransport(transport http.RoundTripper) *BeegoHTTPR
// example: // example:
// //
// func(req *http.Request) (*url.URL, error) { // func(req *http.Request) (*url.URL, error) {
// u, _ := url.ParseRequestURI("http://127.0.0.1:8118") // u, _ := url.ParseRequestURI("http://127.0.0.1:8118")
// return u, nil // return u, nil
// } // }
func (b *BeegoHTTPRequest) SetProxy(proxy func(*http.Request) (*url.URL, error)) *BeegoHTTPRequest { func (b *BeegoHTTPRequest) SetProxy(proxy func(*http.Request) (*url.URL, error)) *BeegoHTTPRequest {
b.setting.Proxy = proxy b.setting.Proxy = proxy
return b return b
@ -592,10 +591,10 @@ func (b *BeegoHTTPRequest) Bytes() ([]byte, error) {
if err != nil { if err != nil {
return nil, berror.Wrap(err, ReadGzipBodyFailed, "building gzip reader failed") return nil, berror.Wrap(err, ReadGzipBodyFailed, "building gzip reader failed")
} }
b.body, err = ioutil.ReadAll(reader) b.body, err = io.ReadAll(reader)
return b.body, berror.Wrap(err, ReadGzipBodyFailed, "reading gzip data failed") return b.body, berror.Wrap(err, ReadGzipBodyFailed, "reading gzip data failed")
} }
b.body, err = ioutil.ReadAll(resp.Body) b.body, err = io.ReadAll(resp.Body)
return b.body, err return b.body, err
} }

View File

@ -17,9 +17,10 @@ package httplib
import ( import (
"bytes" "bytes"
"context" "context"
json "encoding/json"
"errors" "errors"
"fmt" "fmt"
"io/ioutil" "io"
"net" "net"
"net/http" "net/http"
"os" "os"
@ -27,19 +28,104 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/suite"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
func TestResponse(t *testing.T) { type HttplibTestSuite struct {
req := Get("http://httpbin.org/get") suite.Suite
resp, err := req.Response() l net.Listener
require.NoError(t, err)
t.Log(resp)
} }
func TestDoRequest(t *testing.T) { func (h *HttplibTestSuite) SetupSuite() {
req := Get("https://goolnk.com/33BD2j") listener, err := net.Listen("tcp", ":8080")
require.NoError(h.T(), err)
h.l = listener
handler := http.NewServeMux()
handler.HandleFunc("/get", func(writer http.ResponseWriter, request *http.Request) {
agent := request.Header.Get("User-Agent")
_, _ = writer.Write([]byte("hello, " + agent))
})
handler.HandleFunc("/put", func(writer http.ResponseWriter, request *http.Request) {
_, _ = writer.Write([]byte("hello, put"))
})
handler.HandleFunc("/post", func(writer http.ResponseWriter, request *http.Request) {
body, _ := io.ReadAll(request.Body)
_, _ = writer.Write(body)
})
handler.HandleFunc("/delete", func(writer http.ResponseWriter, request *http.Request) {
_, _ = writer.Write([]byte("hello, delete"))
})
handler.HandleFunc("/cookies/set", func(writer http.ResponseWriter, request *http.Request) {
k1 := request.URL.Query().Get("k1")
http.SetCookie(writer, &http.Cookie{
Name: "k1",
Value: k1,
})
_, _ = writer.Write([]byte("hello, set cookie"))
})
handler.HandleFunc("/cookies", func(writer http.ResponseWriter, request *http.Request) {
body := request.Cookies()[0].String()
_, _ = writer.Write([]byte(body))
})
handler.HandleFunc("/basic-auth/user/passwd", func(writer http.ResponseWriter, request *http.Request) {
_, _, ok := request.BasicAuth()
if ok {
_, _ = writer.Write([]byte("authenticated"))
} else {
_, _ = writer.Write([]byte("no auth"))
}
})
handler.HandleFunc("/headers", func(writer http.ResponseWriter, request *http.Request) {
agent := request.Header.Get("User-Agent")
_, _ = writer.Write([]byte(agent))
})
handler.HandleFunc("/ip", func(writer http.ResponseWriter, request *http.Request) {
data := map[string]string{"origin": "127.0.0.1"}
jsonBytes, _ := json.Marshal(data)
_, _ = writer.Write(jsonBytes)
})
handler.HandleFunc("/redirect", func(writer http.ResponseWriter, request *http.Request) {
http.Redirect(writer, request, "redirect_dst", http.StatusTemporaryRedirect)
})
handler.HandleFunc("redirect_dst", func(writer http.ResponseWriter, request *http.Request) {
_, _ = writer.Write([]byte("hello"))
})
go func() {
_ = http.Serve(listener, handler)
}()
}
func (h *HttplibTestSuite) TearDownSuite() {
_ = h.l.Close()
}
func TestHttplib(t *testing.T) {
suite.Run(t, &HttplibTestSuite{})
}
func (h *HttplibTestSuite) TestResponse() {
req := Get("http://localhost:8080/get")
_, err := req.Response()
require.NoError(h.T(), err)
}
func (h *HttplibTestSuite) TestDoRequest() {
t := h.T()
req := Get("http://localhost:8080/redirect")
retryAmount := 1 retryAmount := 1
req.Retries(1) req.Retries(1)
req.RetryDelay(1400 * time.Millisecond) req.RetryDelay(1400 * time.Millisecond)
@ -63,107 +149,79 @@ func TestDoRequest(t *testing.T) {
} }
} }
func TestGet(t *testing.T) { func (h *HttplibTestSuite) TestGet() {
req := Get("http://httpbin.org/get") t := h.T()
req := Get("http://localhost:8080/get")
b, err := req.Bytes() b, err := req.Bytes()
require.NoError(t, err) require.NoError(t, err)
t.Log(b)
s, err := req.String() s, err := req.String()
require.NoError(t, err) require.NoError(t, err)
t.Log(s)
require.Equal(t, string(b), s) require.Equal(t, string(b), s)
} }
func TestSimplePost(t *testing.T) { func (h *HttplibTestSuite) TestSimplePost() {
t := h.T()
v := "smallfish" v := "smallfish"
req := Post("http://httpbin.org/post") req := Post("http://localhost:8080/post")
req.Param("username", v) req.Param("username", v)
str, err := req.String() str, err := req.String()
require.NoError(t, err) require.NoError(t, err)
t.Log(str) n := strings.Index(str, v)
require.NotEqual(t, -1, n)
}
func (h *HttplibTestSuite) TestSimplePut() {
t := h.T()
_, err := Put("http://localhost:8080/put").String()
require.NoError(t, err)
}
func (h *HttplibTestSuite) TestSimpleDelete() {
t := h.T()
_, err := Delete("http://localhost:8080/delete").String()
require.NoError(t, err)
}
func (h *HttplibTestSuite) TestSimpleDeleteParam() {
t := h.T()
_, err := Delete("http://localhost:8080/delete").Param("key", "val").String()
require.NoError(t, err)
}
func (h *HttplibTestSuite) TestWithCookie() {
t := h.T()
v := "smallfish"
_, err := Get("http://localhost:8080/cookies/set?k1=" + v).SetEnableCookie(true).String()
require.NoError(t, err)
str, err := Get("http://localhost:8080/cookies").SetEnableCookie(true).String()
require.NoError(t, err)
n := strings.Index(str, v) n := strings.Index(str, v)
require.NotEqual(t, -1, n) require.NotEqual(t, -1, n)
} }
// func TestPostFile(t *testing.T) { func (h *HttplibTestSuite) TestWithBasicAuth() {
// v := "smallfish" t := h.T()
// req := Post("http://httpbin.org/post") str, err := Get("http://localhost:8080/basic-auth/user/passwd").SetBasicAuth("user", "passwd").String()
// req.Debug(true)
// req.Param("username", v)
// req.PostFile("uploadfile", "httplib_test.go")
// str, err := req.String()
// if err != nil {
// t.Fatal(err)
// }
// t.Log(str)
// n := strings.Index(str, v)
// if n == -1 {
// t.Fatal(v + " not found in post")
// }
// }
func TestSimplePut(t *testing.T) {
str, err := Put("http://httpbin.org/put").String()
require.NoError(t, err) require.NoError(t, err)
t.Log(str)
}
func TestSimpleDelete(t *testing.T) {
str, err := Delete("http://httpbin.org/delete").String()
require.NoError(t, err)
t.Log(str)
}
func TestSimpleDeleteParam(t *testing.T) {
str, err := Delete("http://httpbin.org/delete").Param("key", "val").String()
require.NoError(t, err)
t.Log(str)
}
func TestWithCookie(t *testing.T) {
v := "smallfish"
str, err := Get("http://httpbin.org/cookies/set?k1=" + v).SetEnableCookie(true).String()
require.NoError(t, err)
t.Log(str)
str, err = Get("http://httpbin.org/cookies").SetEnableCookie(true).String()
require.NoError(t, err)
t.Log(str)
n := strings.Index(str, v)
if n == -1 {
t.Fatal(v + " not found in cookie")
}
}
func TestWithBasicAuth(t *testing.T) {
str, err := Get("http://httpbin.org/basic-auth/user/passwd").SetBasicAuth("user", "passwd").String()
require.NoError(t, err)
t.Log(str)
n := strings.Index(str, "authenticated") n := strings.Index(str, "authenticated")
if n == -1 { require.NotEqual(t, -1, n)
t.Fatal("authenticated not found in response")
}
} }
func TestWithUserAgent(t *testing.T) { func (h *HttplibTestSuite) TestWithUserAgent() {
t := h.T()
v := "beego" v := "beego"
str, err := Get("http://httpbin.org/headers").SetUserAgent(v).String() str, err := Get("http://localhost:8080/headers").SetUserAgent(v).String()
require.NoError(t, err) require.NoError(t, err)
t.Log(str)
n := strings.Index(str, v) n := strings.Index(str, v)
if n == -1 { require.NotEqual(t, -1, n)
t.Fatal(v + " not found in user-agent")
}
} }
func TestWithSetting(t *testing.T) { func (h *HttplibTestSuite) TestWithSetting() {
t := h.T()
v := "beego" v := "beego"
var setting BeegoHTTPSettings var setting BeegoHTTPSettings
setting.EnableCookie = true setting.EnableCookie = true
@ -181,75 +239,68 @@ func TestWithSetting(t *testing.T) {
setting.ReadWriteTimeout = 5 * time.Second setting.ReadWriteTimeout = 5 * time.Second
SetDefaultSetting(setting) SetDefaultSetting(setting)
str, err := Get("http://httpbin.org/get").String() str, err := Get("http://localhost:8080/get").String()
require.NoError(t, err) require.NoError(t, err)
t.Log(str)
n := strings.Index(str, v) n := strings.Index(str, v)
if n == -1 { require.NotEqual(t, -1, n)
t.Fatal(v + " not found in user-agent")
}
} }
func TestToJson(t *testing.T) { func (h *HttplibTestSuite) TestToJson() {
req := Get("http://httpbin.org/ip") t := h.T()
req := Get("http://localhost:8080/ip")
resp, err := req.Response() resp, err := req.Response()
require.NoError(t, err) require.NoError(t, err)
t.Log(resp) t.Log(resp)
// httpbin will return http remote addr
type IP struct { type IP struct {
Origin string `json:"origin"` Origin string `json:"origin"`
} }
var ip IP var ip IP
err = req.ToJSON(&ip) err = req.ToJSON(&ip)
require.NoError(t, err) require.NoError(t, err)
t.Log(ip.Origin) require.Equal(t, "127.0.0.1", ip.Origin)
ips := strings.Split(ip.Origin, ",") ips := strings.Split(ip.Origin, ",")
if len(ips) == 0 { require.NotEmpty(t, ips)
t.Fatal("response is not valid ip")
}
for i := range ips {
if net.ParseIP(strings.TrimSpace(ips[i])).To4() == nil {
t.Fatal("response is not valid ip")
}
}
} }
func TestToFile(t *testing.T) { func (h *HttplibTestSuite) TestToFile() {
t := h.T()
f := "beego_testfile" f := "beego_testfile"
req := Get("http://httpbin.org/ip") req := Get("http://localhost:8080/ip")
err := req.ToFile(f) err := req.ToFile(f)
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(f) defer os.Remove(f)
b, err := ioutil.ReadFile(f)
if n := bytes.Index(b, []byte("origin")); n == -1 { b, err := os.ReadFile(f)
t.Fatal(err) n := bytes.Index(b, []byte("origin"))
} require.NotEqual(t, -1, n)
} }
func TestToFileDir(t *testing.T) { func (h *HttplibTestSuite) TestToFileDir() {
t := h.T()
f := "./files/beego_testfile" f := "./files/beego_testfile"
req := Get("http://httpbin.org/ip") req := Get("http://localhost:8080/ip")
err := req.ToFile(f) err := req.ToFile(f)
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll("./files") defer os.RemoveAll("./files")
b, err := ioutil.ReadFile(f) b, err := os.ReadFile(f)
if n := bytes.Index(b, []byte("origin")); n == -1 { require.NoError(t, err)
t.Fatal(err) n := bytes.Index(b, []byte("origin"))
} require.NotEqual(t, -1, n)
} }
func TestHeader(t *testing.T) { func (h *HttplibTestSuite) TestHeader() {
req := Get("http://httpbin.org/headers") t := h.T()
req := Get("http://localhost:8080/headers")
req.Header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36") req.Header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36")
str, err := req.String() _, err := req.String()
require.NoError(t, err) require.NoError(t, err)
t.Log(str)
} }
// TestAddFilter make sure that AddFilters only work for the specific request // TestAddFilter make sure that AddFilters only work for the specific request
func TestAddFilter(t *testing.T) { func (h *HttplibTestSuite) TestAddFilter() {
t := h.T()
req := Get("http://beego.vip") req := Get("http://beego.vip")
req.AddFilters(func(next Filter) Filter { req.AddFilters(func(next Filter) Filter {
return func(ctx context.Context, req *BeegoHTTPRequest) (*http.Response, error) { return func(ctx context.Context, req *BeegoHTTPRequest) (*http.Response, error) {
@ -261,7 +312,8 @@ func TestAddFilter(t *testing.T) {
assert.Equal(t, 1, len(req.setting.FilterChains)-len(r.setting.FilterChains)) assert.Equal(t, 1, len(req.setting.FilterChains)-len(r.setting.FilterChains))
} }
func TestFilterChainOrder(t *testing.T) { func (h *HttplibTestSuite) TestFilterChainOrder() {
t := h.T()
req := Get("http://beego.vip") req := Get("http://beego.vip")
req.AddFilters(func(next Filter) Filter { req.AddFilters(func(next Filter) Filter {
return func(ctx context.Context, req *BeegoHTTPRequest) (*http.Response, error) { return func(ctx context.Context, req *BeegoHTTPRequest) (*http.Response, error) {
@ -282,24 +334,34 @@ func TestFilterChainOrder(t *testing.T) {
assert.Equal(t, "first", string(data)) assert.Equal(t, "first", string(data))
} }
func TestHead(t *testing.T) { func (h *HttplibTestSuite) TestHead() {
t := h.T()
req := Head("http://beego.vip") req := Head("http://beego.vip")
assert.NotNil(t, req) assert.NotNil(t, req)
assert.Equal(t, "HEAD", req.req.Method) assert.Equal(t, "HEAD", req.req.Method)
} }
func TestDelete(t *testing.T) { func (h *HttplibTestSuite) TestDelete() {
t := h.T()
req := Delete("http://beego.vip") req := Delete("http://beego.vip")
assert.NotNil(t, req) assert.NotNil(t, req)
assert.Equal(t, "DELETE", req.req.Method) assert.Equal(t, "DELETE", req.req.Method)
} }
func TestPost(t *testing.T) { func (h *HttplibTestSuite) TestPost() {
t := h.T()
req := Post("http://beego.vip") req := Post("http://beego.vip")
assert.NotNil(t, req) assert.NotNil(t, req)
assert.Equal(t, "POST", req.req.Method) assert.Equal(t, "POST", req.req.Method)
} }
func (h *HttplibTestSuite) TestPut() {
t := h.T()
req := Put("http://beego.vip")
assert.NotNil(t, req)
assert.Equal(t, "PUT", req.req.Method)
}
func TestNewBeegoRequest(t *testing.T) { func TestNewBeegoRequest(t *testing.T) {
req := NewBeegoRequest("http://beego.vip", "GET") req := NewBeegoRequest("http://beego.vip", "GET")
assert.NotNil(t, req) assert.NotNil(t, req)
@ -341,12 +403,6 @@ func TestBeegoHTTPRequestSetProtocolVersion(t *testing.T) {
assert.Equal(t, 1, req.req.ProtoMinor) assert.Equal(t, 1, req.req.ProtoMinor)
} }
func TestPut(t *testing.T) {
req := Put("http://beego.vip")
assert.NotNil(t, req)
assert.Equal(t, "PUT", req.req.Method)
}
func TestBeegoHTTPRequestHeader(t *testing.T) { func TestBeegoHTTPRequestHeader(t *testing.T) {
req := Post("http://beego.vip") req := Post("http://beego.vip")
key, value := "test-header", "test-header-value" key, value := "test-header", "test-header-value"

View File

@ -106,8 +106,10 @@ func MockDeleteWithCtx(tableName string, affectedRow int64, err error) *Mock {
// Now you may be need to use golang/mock to generate QueryM2M mock instance // Now you may be need to use golang/mock to generate QueryM2M mock instance
// Or use DoNothingQueryM2Mer // Or use DoNothingQueryM2Mer
// for example: // for example:
// post := Post{Id: 4} //
// m2m := Ormer.QueryM2M(&post, "Tags") // post := Post{Id: 4}
// m2m := Ormer.QueryM2M(&post, "Tags")
//
// when you write test code: // when you write test code:
// MockQueryM2MWithCtx("post", "Tags", mockM2Mer) // MockQueryM2MWithCtx("post", "Tags", mockM2Mer)
// "post" is the table name of model Post structure // "post" is the table name of model Post structure

View File

@ -50,7 +50,6 @@
// // delete // // delete
// num, err = o.Delete(&u) // num, err = o.Delete(&u)
// } // }
//
package orm package orm
import ( import (
@ -324,8 +323,9 @@ func (o *ormBase) QueryM2MWithCtx(_ context.Context, md interface{}, name string
// args are limit, offset int and order string. // args are limit, offset int and order string.
// //
// example: // 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. // make sure the relation is defined in model struct tags.
func (o *ormBase) LoadRelated(md interface{}, name string, args ...utils.KV) (int64, error) { func (o *ormBase) LoadRelated(md interface{}, name string, args ...utils.KV) (int64, error) {

View File

@ -30,9 +30,10 @@ type queryM2M struct {
// add models to origin models when creating queryM2M. // add models to origin models when creating queryM2M.
// example: // example:
// m2m := orm.QueryM2M(post,"Tag") //
// m2m.Add(&Tag1{},&Tag2{}) // m2m := orm.QueryM2M(post,"Tag")
// for _,tag := range post.Tags{} // m2m.Add(&Tag1{},&Tag2{})
// for _,tag := range post.Tags{}
// //
// make sure the relation is defined in post model struct tag. // make sure the relation is defined in post model struct tag.
func (o *queryM2M) Add(mds ...interface{}) (int64, error) { func (o *queryM2M) Add(mds ...interface{}) (int64, error) {

View File

@ -43,9 +43,10 @@ const (
) )
// ColValue do the field raw changes. e.g Nums = Nums + 10. usage: // ColValue do the field raw changes. e.g Nums = Nums + 10. usage:
// Params{ //
// "Nums": ColValue(Col_Add, 10), // Params{
// } // "Nums": ColValue(Col_Add, 10),
// }
func ColValue(opt operator, value interface{}) interface{} { func ColValue(opt operator, value interface{}) interface{} {
switch opt { switch opt {
case ColAdd, ColMinus, ColMultiply, ColExcept, ColBitAnd, ColBitRShift, case ColAdd, ColMinus, ColMultiply, ColExcept, ColBitAnd, ColBitRShift,
@ -260,8 +261,9 @@ func (o *querySet) DeleteWithCtx(ctx context.Context) (int64, error) {
// return an insert queryer. // return an insert queryer.
// it can be used in times. // it can be used in times.
// example: // example:
// i,err := sq.PrepareInsert() //
// i.Add(&user1{},&user2{}) // i,err := sq.PrepareInsert()
// i.Add(&user1{},&user2{})
func (o *querySet) PrepareInsert() (Inserter, error) { func (o *querySet) PrepareInsert() (Inserter, error) {
return o.PrepareInsertWithCtx(context.Background()) return o.PrepareInsertWithCtx(context.Background())
} }
@ -339,10 +341,11 @@ func (o *querySet) ValuesFlatWithCtx(ctx context.Context, result *ParamsList, ex
// name | value // name | value
// total | 100 // total | 100
// found | 200 // found | 200
// to map[string]interface{}{ //
// "total": 100, // to map[string]interface{}{
// "found": 200, // "total": 100,
// } // "found": 200,
// }
func (o *querySet) RowsToMap(result *Params, keyCol, valueCol string) (int64, error) { func (o *querySet) RowsToMap(result *Params, keyCol, valueCol string) (int64, error) {
panic(ErrNotImplement) panic(ErrNotImplement)
} }
@ -353,10 +356,11 @@ func (o *querySet) RowsToMap(result *Params, keyCol, valueCol string) (int64, er
// name | value // name | value
// total | 100 // total | 100
// found | 200 // found | 200
// to struct { //
// Total int // to struct {
// Found int // Total int
// } // Found int
// }
func (o *querySet) RowsToStruct(ptrStruct interface{}, keyCol, valueCol string) (int64, error) { func (o *querySet) RowsToStruct(ptrStruct interface{}, keyCol, valueCol string) (int64, error) {
panic(ErrNotImplement) panic(ErrNotImplement)
} }

View File

@ -874,10 +874,11 @@ func (o *rawSet) ValuesFlat(container *ParamsList, cols ...string) (int64, error
// name | value // name | value
// total | 100 // total | 100
// found | 200 // found | 200
// to map[string]interface{}{ //
// "total": 100, // to map[string]interface{}{
// "found": 200, // "total": 100,
// } // "found": 200,
// }
func (o *rawSet) RowsToMap(result *Params, keyCol, valueCol string) (int64, error) { func (o *rawSet) RowsToMap(result *Params, keyCol, valueCol string) (int64, error) {
return o.queryRowsTo(result, keyCol, valueCol) return o.queryRowsTo(result, keyCol, valueCol)
} }
@ -888,10 +889,11 @@ func (o *rawSet) RowsToMap(result *Params, keyCol, valueCol string) (int64, erro
// name | value // name | value
// total | 100 // total | 100
// found | 200 // found | 200
// to struct { //
// Total int // to struct {
// Found int // Total int
// } // Found int
// }
func (o *rawSet) RowsToStruct(ptrStruct interface{}, keyCol, valueCol string) (int64, error) { func (o *rawSet) RowsToStruct(ptrStruct interface{}, keyCol, valueCol string) (int64, error) {
return o.queryRowsTo(ptrStruct, keyCol, valueCol) return o.queryRowsTo(ptrStruct, keyCol, valueCol)
} }

View File

@ -27,12 +27,14 @@ import (
// TableNaming is usually used by model // TableNaming is usually used by model
// when you custom your table name, please implement this interfaces // when you custom your table name, please implement this interfaces
// for example: // for example:
// type User struct { //
// ... // type User struct {
// } // ...
// func (u *User) TableName() string { // }
// return "USER_TABLE" //
// } // func (u *User) TableName() string {
// return "USER_TABLE"
// }
type TableNameI interface { type TableNameI interface {
TableName() string TableName() string
} }
@ -40,12 +42,14 @@ type TableNameI interface {
// TableEngineI is usually used by model // TableEngineI is usually used by model
// when you want to use specific engine, like myisam, you can implement this interface // when you want to use specific engine, like myisam, you can implement this interface
// for example: // for example:
// type User struct { //
// ... // type User struct {
// } // ...
// func (u *User) TableEngine() string { // }
// return "myisam" //
// } // func (u *User) TableEngine() string {
// return "myisam"
// }
type TableEngineI interface { type TableEngineI interface {
TableEngine() string TableEngine() string
} }
@ -53,12 +57,14 @@ type TableEngineI interface {
// TableIndexI is usually used by model // TableIndexI is usually used by model
// when you want to create indexes, you can implement this interface // when you want to create indexes, you can implement this interface
// for example: // for example:
// type User struct { //
// ... // type User struct {
// } // ...
// func (u *User) TableIndex() [][]string { // }
// return [][]string{{"Name"}} //
// } // func (u *User) TableIndex() [][]string {
// return [][]string{{"Name"}}
// }
type TableIndexI interface { type TableIndexI interface {
TableIndex() [][]string TableIndex() [][]string
} }
@ -66,12 +72,14 @@ type TableIndexI interface {
// TableUniqueI is usually used by model // TableUniqueI is usually used by model
// when you want to create unique indexes, you can implement this interface // when you want to create unique indexes, you can implement this interface
// for example: // for example:
// type User struct { //
// ... // type User struct {
// } // ...
// func (u *User) TableUnique() [][]string { // }
// return [][]string{{"Email"}} //
// } // func (u *User) TableUnique() [][]string {
// return [][]string{{"Email"}}
// }
type TableUniqueI interface { type TableUniqueI interface {
TableUnique() [][]string TableUnique() [][]string
} }
@ -526,8 +534,9 @@ type RawPreparer interface {
// RawSeter raw query seter // RawSeter raw query seter
// create From Ormer.Raw // create From Ormer.Raw
// for example: // 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 interface { type RawSeter interface {
// execute sql and get result // execute sql and get result
Exec() (sql.Result, error) Exec() (sql.Result, error)

View File

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

View File

@ -14,29 +14,31 @@
// Package config is used to parse config. // Package config is used to parse config.
// Usage: // Usage:
// import "github.com/beego/beego/v2/core/config" //
// import "github.com/beego/beego/v2/core/config"
//
// Examples. // 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.Set(key, val string) error
// cnf.String(key string) string // cnf.String(key string) string
// cnf.Strings(key string) []string // cnf.Strings(key string) []string
// cnf.Int(key string) (int, error) // cnf.Int(key string) (int, error)
// cnf.Int64(key string) (int64, error) // cnf.Int64(key string) (int64, error)
// cnf.Bool(key string) (bool, error) // cnf.Bool(key string) (bool, error)
// cnf.Float(key string) (float64, error) // cnf.Float(key string) (float64, error)
// cnf.DefaultString(key string, defaultVal string) string // cnf.DefaultString(key string, defaultVal string) string
// cnf.DefaultStrings(key string, defaultVal []string) []string // cnf.DefaultStrings(key string, defaultVal []string) []string
// cnf.DefaultInt(key string, defaultVal int) int // cnf.DefaultInt(key string, defaultVal int) int
// cnf.DefaultInt64(key string, defaultVal int64) int64 // cnf.DefaultInt64(key string, defaultVal int64) int64
// cnf.DefaultBool(key string, defaultVal bool) bool // cnf.DefaultBool(key string, defaultVal bool) bool
// cnf.DefaultFloat(key string, defaultVal float64) float64 // cnf.DefaultFloat(key string, defaultVal float64) float64
// cnf.DIY(key string) (interface{}, error) // cnf.DIY(key string) (interface{}, error)
// cnf.GetSection(section string) (map[string]string, error) // cnf.GetSection(section string) (map[string]string, error)
// cnf.SaveConfigFile(filename string) error // cnf.SaveConfigFile(filename string) error
package config package config
import ( import (
@ -266,6 +268,7 @@ func ExpandValueEnvForMap(m map[string]interface{}) map[string]interface{} {
// //
// It accept value formats "${env}" , "${env||}}" , "${env||defaultValue}" , "defaultvalue". // It accept value formats "${env}" , "${env||}}" , "${env||defaultValue}" , "defaultvalue".
// Examples: // Examples:
//
// v1 := config.ExpandValueEnv("${GOPATH}") // return the GOPATH environment variable. // v1 := config.ExpandValueEnv("${GOPATH}") // return the GOPATH environment variable.
// v2 := config.ExpandValueEnv("${GOAsta||/usr/local/go}") // return the default value "/usr/local/go/". // v2 := config.ExpandValueEnv("${GOAsta||/usr/local/go}") // return the default value "/usr/local/go/".
// v3 := config.ExpandValueEnv("Astaxie") // return the value "Astaxie". // 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 not use this file except in compliance with the License.
// You may obtain a copy of the License at // 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 // Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, // distributed under the License is distributed on an "AS IS" BASIS,

View File

@ -19,13 +19,13 @@
// go install github.com/beego/x2j. // go install github.com/beego/x2j.
// //
// Usage: // 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 package xml
import ( import (
@ -40,9 +40,10 @@ import (
"github.com/mitchellh/mapstructure" "github.com/mitchellh/mapstructure"
"github.com/beego/x2j"
"github.com/beego/beego/v2/core/config" "github.com/beego/beego/v2/core/config"
"github.com/beego/beego/v2/core/logs" "github.com/beego/beego/v2/core/logs"
"github.com/beego/x2j"
) )
// Config is a xml config parser and implements Config interface. // Config is a xml config parser and implements Config interface.

View File

@ -14,13 +14,13 @@
// Package yaml for config provider // Package yaml for config provider
// Usage: // 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 package yaml
import ( import (

View File

@ -110,15 +110,16 @@ func (w *fileLogWriter) SetFormatter(f LogFormatter) {
// Init file logger with json config. // Init file logger with json config.
// jsonConfig like: // jsonConfig like:
// { //
// "filename":"logs/beego.log", // {
// "maxLines":10000, // "filename":"logs/beego.log",
// "maxsize":1024, // "maxLines":10000,
// "daily":true, // "maxsize":1024,
// "maxDays":15, // "daily":true,
// "rotate":true, // "maxDays":15,
// "perm":"0600" // "rotate":true,
// } // "perm":"0600"
// }
func (w *fileLogWriter) Init(config string) error { func (w *fileLogWriter) Init(config string) error {
err := json.Unmarshal([]byte(config), w) err := json.Unmarshal([]byte(config), w)
if err != nil { if err != nil {

View File

@ -47,6 +47,7 @@ func newSMTPWriter() Logger {
// Init smtp writer with json config. // Init smtp writer with json config.
// config like: // config like:
//
// { // {
// "username":"example@gmail.com", // "username":"example@gmail.com",
// "password:"password", // "password:"password",

View File

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

View File

@ -78,11 +78,11 @@ func (p *Paginator) Page() int {
// //
// Usage (in a view template): // Usage (in a view template):
// //
// {{range $index, $page := .paginator.Pages}} // {{range $index, $page := .paginator.Pages}}
// <li{{if $.paginator.IsActive .}} class="active"{{end}}> // <li{{if $.paginator.IsActive .}} class="active"{{end}}>
// <a href="{{$.paginator.PageLink $page}}">{{$page}}</a> // <a href="{{$.paginator.PageLink $page}}">{{$page}}</a>
// </li> // </li>
// {{end}} // {{end}}
func (p *Paginator) Pages() []int { func (p *Paginator) Pages() []int {
if p.pageRange == nil && p.nums > 0 { if p.pageRange == nil && p.nums > 0 {
var pages []int var pages []int

View File

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

View File

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

View File

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

View File

@ -30,7 +30,8 @@ var beeAdminApp *adminApp
// FilterMonitorFunc is default monitor filter when admin module is enable. // 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. // if this func returns, admin module records qps for this request by condition of this function logic.
// usage: // 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" { // if method == "POST" {
// return false // return false
// } // }
@ -41,8 +42,8 @@ var beeAdminApp *adminApp
// return false // return false
// } // }
// return true // return true
// } // }
// beego.FilterMonitorFunc = MyFilterMonitor. // beego.FilterMonitorFunc = MyFilterMonitor.
var FilterMonitorFunc func(string, string, time.Duration, string, int) bool var FilterMonitorFunc func(string, string, time.Duration, string, int) bool
func init() { func init() {

View File

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

View File

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

View File

@ -635,31 +635,33 @@ func (c *Controller) GetFile(key string) (multipart.File, *multipart.FileHeader,
// GetFiles return multi-upload files // GetFiles return multi-upload files
// files, err:=c.GetFiles("myfiles") // files, err:=c.GetFiles("myfiles")
//
// if err != nil { // if err != nil {
// http.Error(w, err.Error(), http.StatusNoContent) // http.Error(w, err.Error(), http.StatusNoContent)
// return // return
// } // }
// for i, _ := range files { //
// //for each fileheader, get a handle to the actual file // for i, _ := range files {
// file, err := files[i].Open() // //for each fileheader, get a handle to the actual file
// defer file.Close() // file, err := files[i].Open()
// if err != nil { // defer file.Close()
// http.Error(w, err.Error(), http.StatusInternalServerError) // if err != nil {
// return // 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) { func (c *Controller) GetFiles(key string) ([]*multipart.FileHeader, error) {
if files, ok := c.Ctx.Request.MultipartForm.File[key]; ok { if files, ok := c.Ctx.Request.MultipartForm.File[key]; ok {
return files, nil return files, nil

View File

@ -11,6 +11,5 @@ beego is inspired by Tornado, Sinatra and Flask with the added benefit of some G
func main() { func main() {
beego.Run() beego.Run()
} }
*/ */
package web package web

View File

@ -386,7 +386,8 @@ func responseError(rw http.ResponseWriter, r *http.Request, errCode int, errCont
// ErrorHandler registers http.HandlerFunc to each http err code string. // ErrorHandler registers http.HandlerFunc to each http err code string.
// usage: // usage:
// beego.ErrorHandler("404",NotFound) //
// beego.ErrorHandler("404",NotFound)
// beego.ErrorHandler("500",InternalServerError) // beego.ErrorHandler("500",InternalServerError)
func ErrorHandler(code string, h http.HandlerFunc) *HttpServer { func ErrorHandler(code string, h http.HandlerFunc) *HttpServer {
ErrorMaps[code] = &errorInfo{ ErrorMaps[code] = &errorInfo{
@ -399,7 +400,8 @@ func ErrorHandler(code string, h http.HandlerFunc) *HttpServer {
// ErrorController registers ControllerInterface to each http err code string. // ErrorController registers ControllerInterface to each http err code string.
// usage: // usage:
// beego.ErrorController(&controllers.ErrorController{}) //
// beego.ErrorController(&controllers.ErrorController{})
func ErrorController(c ControllerInterface) *HttpServer { func ErrorController(c ControllerInterface) *HttpServer {
reflectVal := reflect.ValueOf(c) reflectVal := reflect.ValueOf(c)
rt := reflectVal.Type() rt := reflectVal.Type()

View File

@ -43,8 +43,8 @@ type FilterRouter struct {
} }
// params is for: // params is for:
// 1. setting the returnOnOutput value (false allows multiple filters to execute) // 1. setting the returnOnOutput value (false allows multiple filters to execute)
// 2. determining whether or not params need to be reset. // 2. determining whether or not params need to be reset.
func newFilterRouter(pattern string, filter FilterFunc, opts ...FilterOpt) *FilterRouter { func newFilterRouter(pattern string, filter FilterFunc, opts ...FilterOpt) *FilterRouter {
mr := &FilterRouter{ mr := &FilterRouter{
tree: NewTree(), tree: NewTree(),

View File

@ -15,6 +15,7 @@
// Package apiauth provides handlers to enable apiauth support. // Package apiauth provides handlers to enable apiauth support.
// //
// Simple Usage: // Simple Usage:
//
// import( // import(
// "github.com/beego/beego/v2" // "github.com/beego/beego/v2"
// "github.com/beego/beego/v2/server/web/filter/apiauth" // "github.com/beego/beego/v2/server/web/filter/apiauth"
@ -37,11 +38,11 @@
// //
// Information: // 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 // 1. appid
// //
// appid is assigned to the application // appid is assigned to the application
// //
// 2. signature // 2. signature
// //
@ -51,8 +52,7 @@
// //
// 3. timestamp: // 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 package apiauth
import ( import (

View File

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

View File

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

View File

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

View File

@ -18,28 +18,30 @@
// Usage: // Usage:
// //
// import( // 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) { // func handler(w http.ResponseWriter, r *http.Request) {
// w.Write([]byte("WORLD!")) // w.Write([]byte("WORLD!"))
// } // }
// //
// func main() { // func main() {
// mux := http.NewServeMux() // mux := http.NewServeMux()
// mux.HandleFunc("/hello", handler) // mux.HandleFunc("/hello", handler)
// //
// err := grace.ListenAndServe("localhost:8080", mux) // err := grace.ListenAndServe("localhost:8080", mux)
// if err != nil { // if err != nil {
// log.Println(err) // log.Println(err)
// } // }
// log.Println("Server on 8080 stopped") // log.Println("Server on 8080 stopped")
// os.Exit(0) // os.Exit(0)
// } // }
package grace package grace
import ( import (

View File

@ -47,12 +47,14 @@ func NewNamespace(prefix string, params ...LinkNamespace) *Namespace {
// Cond set condition function // Cond set condition function
// if cond return true can run this namespace, else can't // if cond return true can run this namespace, else can't
// usage: // usage:
// ns.Cond(func (ctx *context.Context) bool{ //
// if ctx.Input.Domain() == "api.beego.vip" { // ns.Cond(func (ctx *context.Context) bool{
// return true // if ctx.Input.Domain() == "api.beego.vip" {
// } // return true
// return false // }
// }) // return false
// })
//
// Cond as the first filter // Cond as the first filter
func (n *Namespace) Cond(cond namespaceCond) *Namespace { func (n *Namespace) Cond(cond namespaceCond) *Namespace {
fn := func(ctx *beecontext.Context) { fn := func(ctx *beecontext.Context) {
@ -77,12 +79,13 @@ func (n *Namespace) Cond(cond namespaceCond) *Namespace {
// action has before & after // action has before & after
// FilterFunc // FilterFunc
// usage: // usage:
// Filter("before", func (ctx *context.Context){ //
// _, ok := ctx.Input.Session("uid").(int) // Filter("before", func (ctx *context.Context){
// if !ok && ctx.Request.RequestURI != "/login" { // _, ok := ctx.Input.Session("uid").(int)
// ctx.Redirect(302, "/login") // if !ok && ctx.Request.RequestURI != "/login" {
// } // ctx.Redirect(302, "/login")
// }) // }
// })
func (n *Namespace) Filter(action string, filter ...FilterFunc) *Namespace { func (n *Namespace) Filter(action string, filter ...FilterFunc) *Namespace {
var a int var a int
if action == "before" { if action == "before" {
@ -239,18 +242,20 @@ func (n *Namespace) CtrlAny(rootpath string, f interface{}) *Namespace {
// usage: // usage:
// ns := beego.NewNamespace(“/v1”). // ns := beego.NewNamespace(“/v1”).
// Namespace( // Namespace(
// beego.NewNamespace("/shop"). //
// Get("/:id", func(ctx *context.Context) { // beego.NewNamespace("/shop").
// ctx.Output.Body([]byte("shopinfo")) // Get("/:id", func(ctx *context.Context) {
// }), // ctx.Output.Body([]byte("shopinfo"))
// beego.NewNamespace("/order"). // }),
// Get("/:id", func(ctx *context.Context) { // beego.NewNamespace("/order").
// ctx.Output.Body([]byte("orderinfo")) // Get("/:id", func(ctx *context.Context) {
// }), // ctx.Output.Body([]byte("orderinfo"))
// beego.NewNamespace("/crm"). // }),
// Get("/:id", func(ctx *context.Context) { // beego.NewNamespace("/crm").
// ctx.Output.Body([]byte("crminfo")) // Get("/:id", func(ctx *context.Context) {
// }), // ctx.Output.Body([]byte("crminfo"))
// }),
//
// ) // )
func (n *Namespace) Namespace(ns ...*Namespace) *Namespace { func (n *Namespace) Namespace(ns ...*Namespace) *Namespace {
for _, ni := range ns { for _, ni := range ns {

View File

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

View File

@ -227,21 +227,21 @@ func Htmlunquote(text string) string {
} }
// URLFor returns url string with another registered controller handler with params. // URLFor returns url string with another registered controller handler with params.
// usage:
// //
// URLFor(".index") // usage:
// 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
// //
// 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 { func URLFor(endpoint string, values ...interface{}) string {
return BeeApp.Handlers.URLFor(endpoint, values...) return BeeApp.Handlers.URLFor(endpoint, values...)
} }
@ -564,12 +564,13 @@ func ge(arg1, arg2 interface{}) (bool, error) {
// MapGet getting value from map by keys // MapGet getting value from map by keys
// usage: // usage:
// Data["m"] = M{ //
// "a": 1, // Data["m"] = M{
// "1": map[string]float64{ // "a": 1,
// "c": 4, // "1": map[string]float64{
// }, // "c": 4,
// } // },
// }
// //
// {{ map_get m "a" }} // return 1 // {{ map_get m "a" }} // return 1
// {{ map_get m 1 "c" }} // return 4 // {{ map_get m 1 "c" }} // return 4

View File

@ -237,11 +237,16 @@ func TimeoutOption(timeout time.Duration) Option {
// week0-60 means Sunday // week0-60 means Sunday
// SetCron some signals // SetCron some signals
// * any time //
// ,  separate signal // * any time
// ,  separate signal
//
//    duration //    duration
// /n : do as n times of time duration //
// /n : do as n times of time duration
//
// /////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////
//
// 0/30 * * * * * every 30s // 0/30 * * * * * every 30s
// 0 43 21 * * * 21:43 // 0 43 21 * * * 21:43
// 0 15 05 * * *    05:15 // 0 15 05 * * *    05:15
@ -724,7 +729,8 @@ func getField(field string, r bounds) uint64 {
} }
// getRange returns the bits indicated by the given expression: // getRange returns the bits indicated by the given expression:
// number | number "-" number [ "/" number ] //
// number | number "-" number [ "/" number ]
func getRange(expr string, r bounds) uint64 { func getRange(expr string, r bounds) uint64 {
var ( var (
start, end, step uint start, end, step uint

View File

@ -198,11 +198,13 @@ var _bindata = map[string]func() (*asset, error){
// directory embedded in the file by go-bindata. // directory embedded in the file by go-bindata.
// For example if you run go-bindata on data/... and data contains the // For example if you run go-bindata on data/... and data contains the
// following hierarchy: // following hierarchy:
// data/ //
// foo.txt // data/
// img/ // foo.txt
// a.png // img/
// b.png // a.png
// b.png
//
// then AssetDir("data") would return []string{"foo.txt", "img"} // then AssetDir("data") would return []string{"foo.txt", "img"}
// AssetDir("data/img") would return []string{"a.png", "b.png"} // AssetDir("data/img") would return []string{"a.png", "b.png"}
// AssetDir("foo.txt") and AssetDir("notexist") would return an error // AssetDir("foo.txt") and AssetDir("notexist") would return an error