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
- [httplib: fix unstable unit test which use the httplib.org](https://github.com/beego/beego/pull/5232)
# v2.1.0
- [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**
**We will remove the adapter package in v2.2.0 which will be released in Aug 2023**
## Quick Start
[Old Doc - github](https://github.com/beego/beedoc)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -14,7 +14,9 @@
// Package config is used to parse config.
// Usage:
//
// import "github.com/beego/beego/v2/core/config"
//
// Examples.
//
// cnf, err := config.NewConfig("ini", "config.conf")
@ -128,6 +130,7 @@ func ExpandValueEnvForMap(m map[string]interface{}) map[string]interface{} {
//
// It accept value formats "${env}" , "${env||}}" , "${env||defaultValue}" , "defaultvalue".
// Examples:
//
// v1 := config.ExpandValueEnv("${GOPATH}") // return the GOPATH environment variable.
// v2 := config.ExpandValueEnv("${GOAsta||/usr/local/go}") // return the default value "/usr/local/go/".
// v3 := config.ExpandValueEnv("Astaxie") // return the value "Astaxie".

View File

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

View File

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

View File

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

View File

@ -296,10 +296,12 @@ func (c *Controller) GetFile(key string) (multipart.File, *multipart.FileHeader,
// GetFiles return multi-upload files
// files, err:=c.GetFiles("myfiles")
//
// if err != nil {
// http.Error(w, err.Error(), http.StatusNoContent)
// return
// }
//
// for i, _ := range files {
// //for each fileheader, get a handle to the actual file
// file, err := files[i].Open()

View File

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

View File

@ -18,11 +18,13 @@
// Usage:
//
// import(
//
// "log"
// "net/http"
// "os"
//
// "github.com/beego/beego/v2/server/web/grace"
//
// )
//
// func handler(w http.ResponseWriter, r *http.Request) {

View File

@ -27,7 +27,6 @@
// t.Fatal(err)
// }
// fmt.Println(str)
//
package httplib
import (

View File

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

View File

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

View File

@ -50,7 +50,6 @@
// // delete
// num, err = o.Delete(&u)
// }
//
package orm
import (
@ -170,6 +169,7 @@ func (o *ormer) QueryM2M(md interface{}, name string) QueryM2Mer {
// args are limit, offset int and order string.
//
// example:
//
// orm.LoadRelated(post,"Tags")
// for _,tag := range post.Tags{...}
//

View File

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

View File

@ -15,6 +15,7 @@
// Package apiauth provides handlers to enable apiauth support.
//
// Simple Usage:
//
// import(
// "github.com/beego/beego/v2"
// "github.com/beego/beego/v2/server/web/filter/apiauth"
@ -37,7 +38,7 @@
//
// 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
//
@ -52,7 +53,6 @@
// 3. timestamp:
//
// send the request time, the format is yyyy-mm-dd HH:ii:ss
//
package apiauth
import (

View File

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

View File

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

View File

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

View File

@ -77,6 +77,7 @@ func NewControllerRegister() *ControllerRegister {
// Add controller handler and pattern rules to ControllerRegister.
// usage:
//
// default methods is the same name as method
// Add("/user",&UserController{})
// Add("/api/list",&RestController{},"*:ListFood")
@ -99,6 +100,7 @@ func (p *ControllerRegister) Include(cList ...ControllerInterface) {
// GetContext returns a context from pool, so usually you should remember to call Reset function to clean the context
// And don't forget to give back context to pool
// example:
//
// ctx := p.GetContext()
// ctx.Reset(w, q)
// defer p.GiveBackContext(ctx)
@ -113,6 +115,7 @@ func (p *ControllerRegister) GiveBackContext(ctx *beecontext.Context) {
// Get add get method
// usage:
//
// Get("/", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
@ -124,6 +127,7 @@ func (p *ControllerRegister) Get(pattern string, f FilterFunc) {
// Post add post method
// usage:
//
// Post("/api", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
@ -135,6 +139,7 @@ func (p *ControllerRegister) Post(pattern string, f FilterFunc) {
// Put add put method
// usage:
//
// Put("/api/:id", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
@ -146,6 +151,7 @@ func (p *ControllerRegister) Put(pattern string, f FilterFunc) {
// Delete add delete method
// usage:
//
// Delete("/api/:id", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
@ -157,6 +163,7 @@ func (p *ControllerRegister) Delete(pattern string, f FilterFunc) {
// Head add head method
// usage:
//
// Head("/api/:id", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
@ -168,6 +175,7 @@ func (p *ControllerRegister) Head(pattern string, f FilterFunc) {
// Patch add patch method
// usage:
//
// Patch("/api/:id", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
@ -179,6 +187,7 @@ func (p *ControllerRegister) Patch(pattern string, f FilterFunc) {
// Options add options method
// usage:
//
// Options("/api/:id", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
@ -190,6 +199,7 @@ func (p *ControllerRegister) Options(pattern string, f FilterFunc) {
// Any add all method
// usage:
//
// Any("/api/:id", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })
@ -201,6 +211,7 @@ func (p *ControllerRegister) Any(pattern string, f FilterFunc) {
// AddMethod add http method router
// usage:
//
// AddMethod("get","/api/:id", func(ctx *context.Context){
// ctx.Output.Body("hello world")
// })

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -61,6 +61,7 @@ type CookieProvider session.CookieProvider
// SessionInit Init cookie session provider with max lifetime and config json.
// maxlifetime is ignored.
// json config:
//
// securityKey - hash string
// blockKey - gob encode hash string. it's saved as aes crypto.
// securityName - recognized name in encoded cookie string

View File

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

View File

@ -91,6 +91,7 @@ func Htmlunquote(text string) string {
}
// URLFor returns url string with another registered controller handler with params.
//
// usage:
//
// URLFor(".index")
@ -105,7 +106,6 @@ func Htmlunquote(text string) string {
// /login
// /login?next=/
// /user/John%20Doe
//
func URLFor(endpoint string, values ...interface{}) string {
return web.URLFor(endpoint, values...)
}
@ -135,6 +135,7 @@ func RenderForm(obj interface{}) template.HTML {
// MapGet getting value from map by keys
// usage:
//
// Data["m"] = M{
// "a": 1,
// "1": map[string]float64{

View File

@ -26,7 +26,6 @@
// }
//
// AddHealthCheck("database",&DatabaseCheck{})
//
package toolbox
import (

View File

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

View File

@ -19,9 +19,11 @@
// package controllers
//
// import (
//
// "github.com/beego/beego/v2"
// "github.com/beego/beego/v2/client/cache"
// "github.com/beego/beego/v2/server/web/captcha"
//
// )
//
// var cpt *captcha.Captcha
@ -45,6 +47,7 @@
//
// this.Data["Success"] = cpt.VerifyReq(this.Ctx.Request)
// }
//
// ```
//
// template usage
@ -52,8 +55,10 @@
// ```
// {{.Success}}
// <form action="/" method="post">
//
// {{create_captcha}}
// <input name="captcha" type="text">
//
// </form>
// ```
package captcha

View File

@ -2,7 +2,7 @@
Package pagination provides utilities to setup a paginator within the
context of a http request.
Usage
# Usage
In your beego.Controller:
@ -23,7 +23,6 @@ In your beego.Controller:
this.Data["posts"] = ListPostsByOffsetAndLimit(paginator.Offset(), postsPerPage)
}
In your view templates:
{{if .paginator.HasPages}}
@ -49,6 +48,5 @@ In your view templates:
{{end}}
</ul>
{{end}}
*/
package pagination

View File

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

View File

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

View File

@ -51,6 +51,7 @@ var once sync.Once
// SetDefaultMessage set default messages
// if not set, the default messages are
//
// "Required": "Can not be empty",
// "Min": "Minimum is %d",
// "Max": "Maximum is %d",

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -15,12 +15,17 @@
package httplib
import (
"encoding/json"
"encoding/xml"
"io"
"io/ioutil"
"net"
"net/http"
"testing"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"gopkg.in/yaml.v3"
"github.com/stretchr/testify/assert"
)
@ -32,13 +37,13 @@ func TestNewClient(t *testing.T) {
}
type slideShowResponse struct {
Resp *http.Response
bytes []byte
StatusCode int
Body io.ReadCloser
Header map[string][]string
Resp *http.Response `json:"resp,omitempty"`
bytes []byte `json:"bytes,omitempty"`
StatusCode int `json:"status_code,omitempty"`
Body io.ReadCloser `json:"body,omitempty"`
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) {
@ -66,7 +71,7 @@ func (r *slideShowResponse) String() string {
}
type slideshow struct {
XMLName xml.Name `xml:"slideshow"`
//XMLName xml.Name `xml:"slideshow"`
Title string `json:"title" yaml:"title" xml:"title,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"`
}
func TestClientHandleCarrier(t *testing.T) {
v := "beego"
client, err := NewClient("test", "http://httpbin.org/",
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))
type ClientTestSuite struct {
suite.Suite
l net.Listener
}
func TestClientGet(t *testing.T) {
client, err := NewClient("test", "http://httpbin.org/")
func (c *ClientTestSuite) SetupSuite() {
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 {
t.Fatal(err)
}
// json
var s *slideShowResponse
err = client.Get(&s, "/json")
if err != nil {
t.Fatal(err)
}
var s slideShowResponse
err = client.Get(&s, "/get")
require.NoError(t, err)
assert.Equal(t, "Sample Slide Show", s.Slideshow.Title)
assert.Equal(t, 2, len(s.Slideshow.Slides))
assert.Equal(t, "Overview", s.Slideshow.Slides[1].Title)
// xml
var ssp *slideshow
err = client.Get(&ssp, "/base64/PD94bWwgPz48c2xpZGVzaG93CnRpdGxlPSJTYW1wbGUgU2xpZGUgU2hvdyIKZGF0ZT0iRGF0ZSBvZiBwdWJsaWNhdGlvbiIKYXV0aG9yPSJZb3VycyBUcnVseSI+PHNsaWRlIHR5cGU9ImFsbCI+PHRpdGxlPldha2UgdXAgdG8gV29uZGVyV2lkZ2V0cyE8L3RpdGxlPjwvc2xpZGU+PHNsaWRlIHR5cGU9ImFsbCI+PHRpdGxlPk92ZXJ2aWV3PC90aXRsZT48aXRlbT5XaHkgPGVtPldvbmRlcldpZGdldHM8L2VtPiBhcmUgZ3JlYXQ8L2l0ZW0+PGl0ZW0vPjxpdGVtPldobyA8ZW0+YnV5czwvZW0+IFdvbmRlcldpZGdldHM8L2l0ZW0+PC9zbGlkZT48L3NsaWRlc2hvdz4=")
if err != nil {
t.Fatal(err)
}
assert.Equal(t, "Sample Slide Show", ssp.Title)
assert.Equal(t, 2, len(ssp.Slides))
assert.Equal(t, "Overview", ssp.Slides[1].Title)
var ss slideshow
err = client.Get(&ss, "/get/xml")
require.NoError(t, err)
assert.Equal(t, "Sample Slide Show", ss.Title)
assert.Equal(t, 2, len(ss.Slides))
assert.Equal(t, "Overview", ss.Slides[1].Title)
// yaml
s = nil
err = client.Get(&s, "/base64/c2xpZGVzaG93OgogIGF1dGhvcjogWW91cnMgVHJ1bHkKICBkYXRlOiBkYXRlIG9mIHB1YmxpY2F0aW9uCiAgc2xpZGVzOgogIC0gdGl0bGU6IFdha2UgdXAgdG8gV29uZGVyV2lkZ2V0cyEKICAgIHR5cGU6IGFsbAogIC0gaXRlbXM6CiAgICAtIFdoeSA8ZW0+V29uZGVyV2lkZ2V0czwvZW0+IGFyZSBncmVhdAogICAgLSBXaG8gPGVtPmJ1eXM8L2VtPiBXb25kZXJXaWRnZXRzCiAgICB0aXRsZTogT3ZlcnZpZXcKICAgIHR5cGU6IGFsbAogIHRpdGxlOiBTYW1wbGUgU2xpZGUgU2hvdw==")
s = slideShowResponse{}
err = client.Get(&s, "/get/yaml")
if err != nil {
t.Fatal(err)
}
@ -145,72 +209,82 @@ func TestClientGet(t *testing.T) {
assert.Equal(t, "Overview", s.Slideshow.Slides[1].Title)
}
func TestClientPost(t *testing.T) {
client, err := NewClient("test", "http://httpbin.org")
if err != nil {
t.Fatal(err)
func (c *ClientTestSuite) TestClientPost() {
t := c.T()
client, err := NewClient("test", "http://localhost:8080")
require.NoError(t, err)
input := slideShowResponse{
Slideshow: slideshow{
Title: "Sample Slide Show",
Slides: []slide{
{
Title: "Content",
},
{
Title: "Overview",
},
},
},
}
resp := &slideShowResponse{}
err = client.Get(resp, "/json")
if err != nil {
t.Fatal(err)
}
jsonStr := resp.String()
err = client.Post(resp, "/post", jsonStr)
if err != nil {
t.Fatal(err)
}
assert.NotNil(t, resp)
jsonStr, err := json.Marshal(input)
require.NoError(t, err)
resp := slideShowResponse{}
err = client.Post(&resp, "/req2resp", jsonStr)
require.NoError(t, err)
assert.Equal(t, input.Slideshow, resp.Slideshow)
assert.Equal(t, http.MethodPost, resp.Resp.Request.Method)
}
func TestClientPut(t *testing.T) {
client, err := NewClient("test", "http://httpbin.org")
if err != nil {
t.Fatal(err)
func (c *ClientTestSuite) TestClientPut() {
t := c.T()
client, err := NewClient("test", "http://localhost:8080")
require.NoError(t, err)
input := slideShowResponse{
Slideshow: slideshow{
Title: "Sample Slide Show",
Slides: []slide{
{
Title: "Content",
},
{
Title: "Overview",
},
},
},
}
resp := &slideShowResponse{}
err = client.Get(resp, "/json")
if err != nil {
t.Fatal(err)
}
jsonStr := resp.String()
err = client.Put(resp, "/put", jsonStr)
if err != nil {
t.Fatal(err)
}
assert.NotNil(t, resp)
jsonStr, err := json.Marshal(input)
require.NoError(t, err)
resp := slideShowResponse{}
err = client.Put(&resp, "/req2resp", jsonStr)
require.NoError(t, err)
assert.Equal(t, input.Slideshow, resp.Slideshow)
assert.Equal(t, http.MethodPut, resp.Resp.Request.Method)
}
func TestClientDelete(t *testing.T) {
client, err := NewClient("test", "http://httpbin.org")
if err != nil {
t.Fatal(err)
}
func (c *ClientTestSuite) TestClientDelete() {
t := c.T()
client, err := NewClient("test", "http://localhost:8080")
require.NoError(t, err)
resp := &slideShowResponse{}
err = client.Delete(resp, "/delete")
if err != nil {
t.Fatal(err)
}
err = client.Delete(resp, "/req2resp")
require.NoError(t, err)
defer resp.Resp.Body.Close()
assert.NotNil(t, resp)
assert.Equal(t, http.MethodDelete, resp.Resp.Request.Method)
}
func TestClientHead(t *testing.T) {
client, err := NewClient("test", "http://beego.gocn.vip")
if err != nil {
t.Fatal(err)
}
func (c *ClientTestSuite) TestClientHead() {
t := c.T()
client, err := NewClient("test", "http://localhost:8080")
require.NoError(t, err)
resp := &slideShowResponse{}
err = client.Head(resp, "")
err = client.Head(resp, "/req2resp")
if err != nil {
t.Fatal(err)
}

View File

@ -27,7 +27,6 @@
// t.Fatal(err)
// }
// fmt.Println(str)
//
package httplib
import (
@ -592,10 +591,10 @@ func (b *BeegoHTTPRequest) Bytes() ([]byte, error) {
if err != nil {
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")
}
b.body, err = ioutil.ReadAll(resp.Body)
b.body, err = io.ReadAll(resp.Body)
return b.body, err
}

View File

@ -17,9 +17,10 @@ package httplib
import (
"bytes"
"context"
json "encoding/json"
"errors"
"fmt"
"io/ioutil"
"io"
"net"
"net/http"
"os"
@ -27,19 +28,104 @@ import (
"testing"
"time"
"github.com/stretchr/testify/suite"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestResponse(t *testing.T) {
req := Get("http://httpbin.org/get")
resp, err := req.Response()
require.NoError(t, err)
t.Log(resp)
type HttplibTestSuite struct {
suite.Suite
l net.Listener
}
func TestDoRequest(t *testing.T) {
req := Get("https://goolnk.com/33BD2j")
func (h *HttplibTestSuite) SetupSuite() {
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
req.Retries(1)
req.RetryDelay(1400 * time.Millisecond)
@ -63,107 +149,79 @@ func TestDoRequest(t *testing.T) {
}
}
func TestGet(t *testing.T) {
req := Get("http://httpbin.org/get")
func (h *HttplibTestSuite) TestGet() {
t := h.T()
req := Get("http://localhost:8080/get")
b, err := req.Bytes()
require.NoError(t, err)
t.Log(b)
s, err := req.String()
require.NoError(t, err)
t.Log(s)
require.Equal(t, string(b), s)
}
func TestSimplePost(t *testing.T) {
func (h *HttplibTestSuite) TestSimplePost() {
t := h.T()
v := "smallfish"
req := Post("http://httpbin.org/post")
req := Post("http://localhost:8080/post")
req.Param("username", v)
str, err := req.String()
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)
require.NotEqual(t, -1, n)
}
// func TestPostFile(t *testing.T) {
// v := "smallfish"
// req := Post("http://httpbin.org/post")
// 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()
func (h *HttplibTestSuite) TestWithBasicAuth() {
t := h.T()
str, err := Get("http://localhost:8080/basic-auth/user/passwd").SetBasicAuth("user", "passwd").String()
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")
if n == -1 {
t.Fatal("authenticated not found in response")
}
require.NotEqual(t, -1, n)
}
func TestWithUserAgent(t *testing.T) {
func (h *HttplibTestSuite) TestWithUserAgent() {
t := h.T()
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)
t.Log(str)
n := strings.Index(str, v)
if n == -1 {
t.Fatal(v + " not found in user-agent")
}
require.NotEqual(t, -1, n)
}
func TestWithSetting(t *testing.T) {
func (h *HttplibTestSuite) TestWithSetting() {
t := h.T()
v := "beego"
var setting BeegoHTTPSettings
setting.EnableCookie = true
@ -181,75 +239,68 @@ func TestWithSetting(t *testing.T) {
setting.ReadWriteTimeout = 5 * time.Second
SetDefaultSetting(setting)
str, err := Get("http://httpbin.org/get").String()
str, err := Get("http://localhost:8080/get").String()
require.NoError(t, err)
t.Log(str)
n := strings.Index(str, v)
if n == -1 {
t.Fatal(v + " not found in user-agent")
}
require.NotEqual(t, -1, n)
}
func TestToJson(t *testing.T) {
req := Get("http://httpbin.org/ip")
func (h *HttplibTestSuite) TestToJson() {
t := h.T()
req := Get("http://localhost:8080/ip")
resp, err := req.Response()
require.NoError(t, err)
t.Log(resp)
// httpbin will return http remote addr
type IP struct {
Origin string `json:"origin"`
}
var ip IP
err = req.ToJSON(&ip)
require.NoError(t, err)
t.Log(ip.Origin)
require.Equal(t, "127.0.0.1", ip.Origin)
ips := strings.Split(ip.Origin, ",")
if len(ips) == 0 {
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")
}
}
require.NotEmpty(t, ips)
}
func TestToFile(t *testing.T) {
func (h *HttplibTestSuite) TestToFile() {
t := h.T()
f := "beego_testfile"
req := Get("http://httpbin.org/ip")
req := Get("http://localhost:8080/ip")
err := req.ToFile(f)
require.NoError(t, err)
defer os.Remove(f)
b, err := ioutil.ReadFile(f)
if n := bytes.Index(b, []byte("origin")); n == -1 {
t.Fatal(err)
}
b, err := os.ReadFile(f)
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"
req := Get("http://httpbin.org/ip")
req := Get("http://localhost:8080/ip")
err := req.ToFile(f)
require.NoError(t, err)
defer os.RemoveAll("./files")
b, err := ioutil.ReadFile(f)
if n := bytes.Index(b, []byte("origin")); n == -1 {
t.Fatal(err)
}
b, err := os.ReadFile(f)
require.NoError(t, err)
n := bytes.Index(b, []byte("origin"))
require.NotEqual(t, -1, n)
}
func TestHeader(t *testing.T) {
req := Get("http://httpbin.org/headers")
func (h *HttplibTestSuite) TestHeader() {
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")
str, err := req.String()
_, err := req.String()
require.NoError(t, err)
t.Log(str)
}
// 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.AddFilters(func(next Filter) Filter {
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))
}
func TestFilterChainOrder(t *testing.T) {
func (h *HttplibTestSuite) TestFilterChainOrder() {
t := h.T()
req := Get("http://beego.vip")
req.AddFilters(func(next Filter) Filter {
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))
}
func TestHead(t *testing.T) {
func (h *HttplibTestSuite) TestHead() {
t := h.T()
req := Head("http://beego.vip")
assert.NotNil(t, req)
assert.Equal(t, "HEAD", req.req.Method)
}
func TestDelete(t *testing.T) {
func (h *HttplibTestSuite) TestDelete() {
t := h.T()
req := Delete("http://beego.vip")
assert.NotNil(t, req)
assert.Equal(t, "DELETE", req.req.Method)
}
func TestPost(t *testing.T) {
func (h *HttplibTestSuite) TestPost() {
t := h.T()
req := Post("http://beego.vip")
assert.NotNil(t, req)
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) {
req := NewBeegoRequest("http://beego.vip", "GET")
assert.NotNil(t, req)
@ -341,12 +403,6 @@ func TestBeegoHTTPRequestSetProtocolVersion(t *testing.T) {
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) {
req := Post("http://beego.vip")
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
// Or use DoNothingQueryM2Mer
// for example:
//
// post := Post{Id: 4}
// m2m := Ormer.QueryM2M(&post, "Tags")
//
// when you write test code:
// MockQueryM2MWithCtx("post", "Tags", mockM2Mer)
// "post" is the table name of model Post structure

View File

@ -50,7 +50,6 @@
// // delete
// num, err = o.Delete(&u)
// }
//
package orm
import (
@ -324,6 +323,7 @@ func (o *ormBase) QueryM2MWithCtx(_ context.Context, md interface{}, name string
// args are limit, offset int and order string.
//
// example:
//
// orm.LoadRelated(post,"Tags")
// for _,tag := range post.Tags{...}
//

View File

@ -30,6 +30,7 @@ type queryM2M struct {
// add models to origin models when creating queryM2M.
// example:
//
// m2m := orm.QueryM2M(post,"Tag")
// m2m.Add(&Tag1{},&Tag2{})
// for _,tag := range post.Tags{}

View File

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

View File

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

View File

@ -27,9 +27,11 @@ import (
// TableNaming is usually used by model
// when you custom your table name, please implement this interfaces
// for example:
//
// type User struct {
// ...
// }
//
// func (u *User) TableName() string {
// return "USER_TABLE"
// }
@ -40,9 +42,11 @@ type TableNameI interface {
// TableEngineI is usually used by model
// when you want to use specific engine, like myisam, you can implement this interface
// for example:
//
// type User struct {
// ...
// }
//
// func (u *User) TableEngine() string {
// return "myisam"
// }
@ -53,9 +57,11 @@ type TableEngineI interface {
// TableIndexI is usually used by model
// when you want to create indexes, you can implement this interface
// for example:
//
// type User struct {
// ...
// }
//
// func (u *User) TableIndex() [][]string {
// return [][]string{{"Name"}}
// }
@ -66,9 +72,11 @@ type TableIndexI interface {
// TableUniqueI is usually used by model
// when you want to create unique indexes, you can implement this interface
// for example:
//
// type User struct {
// ...
// }
//
// func (u *User) TableUnique() [][]string {
// return [][]string{{"Email"}}
// }
@ -526,6 +534,7 @@ type RawPreparer interface {
// RawSeter raw query seter
// create From Ormer.Raw
// for example:
//
// sql := fmt.Sprintf("SELECT %sid%s,%sname%s FROM %suser%s WHERE id = ?",Q,Q,Q,Q,Q,Q)
// rs := Ormer.Raw(sql, 1)
type RawSeter interface {

View File

@ -26,7 +26,6 @@
// }
//
// AddHealthCheck("database",&DatabaseCheck{})
//
package admin
// AdminCheckList holds health checker map

View File

@ -14,7 +14,9 @@
// Package config is used to parse config.
// Usage:
//
// import "github.com/beego/beego/v2/core/config"
//
// Examples.
//
// cnf, err := config.NewConfig("ini", "config.conf")
@ -266,6 +268,7 @@ func ExpandValueEnvForMap(m map[string]interface{}) map[string]interface{} {
//
// It accept value formats "${env}" , "${env||}}" , "${env||defaultValue}" , "defaultvalue".
// Examples:
//
// v1 := config.ExpandValueEnv("${GOPATH}") // return the GOPATH environment variable.
// v2 := config.ExpandValueEnv("${GOAsta||/usr/local/go}") // return the default value "/usr/local/go/".
// v3 := config.ExpandValueEnv("Astaxie") // return the value "Astaxie".

View File

@ -19,13 +19,13 @@
// go install github.com/beego/x2j.
//
// Usage:
//
// import(
// _ "github.com/beego/beego/v2/core/config/xml"
// "github.com/beego/beego/v2/core/config"
// )
//
// cnf, err := config.NewConfig("xml", "config.xml")
//
package xml
import (
@ -40,9 +40,10 @@ import (
"github.com/mitchellh/mapstructure"
"github.com/beego/x2j"
"github.com/beego/beego/v2/core/config"
"github.com/beego/beego/v2/core/logs"
"github.com/beego/x2j"
)
// Config is a xml config parser and implements Config interface.

View File

@ -14,13 +14,13 @@
// Package yaml for config provider
// Usage:
//
// import(
// _ "github.com/beego/beego/v2/core/config/yaml"
// "github.com/beego/beego/v2/core/config"
// )
//
// cnf, err := config.NewConfig("yaml", "config.yaml")
//
package yaml
import (

View File

@ -110,6 +110,7 @@ func (w *fileLogWriter) SetFormatter(f LogFormatter) {
// Init file logger with json config.
// jsonConfig like:
//
// {
// "filename":"logs/beego.log",
// "maxLines":10000,

View File

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

View File

@ -2,7 +2,7 @@
Package pagination provides utilities to setup a paginator within the
context of a http request.
Usage
# Usage
In your beego.Controller:
@ -23,7 +23,6 @@ In your beego.Controller:
this.Data["posts"] = ListPostsByOffsetAndLimit(paginator.Offset(), postsPerPage)
}
In your view templates:
{{if .paginator.HasPages}}
@ -49,6 +48,5 @@ In your view templates:
{{end}}
</ul>
{{end}}
*/
package pagination

View File

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

View File

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

View File

@ -64,6 +64,7 @@ var once sync.Once
// SetDefaultMessage set default messages
// if not set, the default messages are
//
// "Required": "Can not be empty",
// "Min": "Minimum is %d",
// "Max": "Maximum is %d",

View File

@ -30,6 +30,7 @@ var beeAdminApp *adminApp
// FilterMonitorFunc is default monitor filter when admin module is enable.
// if this func returns, admin module records qps for this request by condition of this function logic.
// usage:
//
// func MyFilterMonitor(method, requestPath string, t time.Duration, pattern string, statusCode int) bool {
// if method == "POST" {
// return false

View File

@ -19,9 +19,11 @@
// package controllers
//
// import (
//
// "github.com/beego/beego/v2"
// "github.com/beego/beego/v2/client/cache"
// "github.com/beego/beego/v2/server/web/captcha"
//
// )
//
// var cpt *captcha.Captcha
@ -45,6 +47,7 @@
//
// this.Data["Success"] = cpt.VerifyReq(this.Ctx.Request)
// }
//
// ```
//
// template usage
@ -52,8 +55,10 @@
// ```
// {{.Success}}
// <form action="/" method="post">
//
// {{create_captcha}}
// <input name="captcha" type="text">
//
// </form>
// ```
package captcha

View File

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

View File

@ -635,10 +635,12 @@ func (c *Controller) GetFile(key string) (multipart.File, *multipart.FileHeader,
// GetFiles return multi-upload files
// files, err:=c.GetFiles("myfiles")
//
// if err != nil {
// http.Error(w, err.Error(), http.StatusNoContent)
// return
// }
//
// for i, _ := range files {
// //for each fileheader, get a handle to the actual file
// file, err := files[i].Open()

View File

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

View File

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

View File

@ -15,6 +15,7 @@
// Package apiauth provides handlers to enable apiauth support.
//
// Simple Usage:
//
// import(
// "github.com/beego/beego/v2"
// "github.com/beego/beego/v2/server/web/filter/apiauth"
@ -37,7 +38,7 @@
//
// 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
//
@ -52,7 +53,6 @@
// 3. timestamp:
//
// send the request time, the format is yyyy-mm-dd HH:ii:ss
//
package apiauth
import (

View File

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

View File

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

View File

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

View File

@ -18,11 +18,13 @@
// Usage:
//
// import(
//
// "log"
// "net/http"
// "os"
//
// "github.com/beego/beego/v2/server/web/grace"
//
// )
//
// func handler(w http.ResponseWriter, r *http.Request) {

View File

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

View File

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

View File

@ -227,6 +227,7 @@ func Htmlunquote(text string) string {
}
// URLFor returns url string with another registered controller handler with params.
//
// usage:
//
// URLFor(".index")
@ -241,7 +242,6 @@ func Htmlunquote(text string) string {
// /login
// /login?next=/
// /user/John%20Doe
//
func URLFor(endpoint string, values ...interface{}) string {
return BeeApp.Handlers.URLFor(endpoint, values...)
}
@ -564,6 +564,7 @@ func ge(arg1, arg2 interface{}) (bool, error) {
// MapGet getting value from map by keys
// usage:
//
// Data["m"] = M{
// "a": 1,
// "1": map[string]float64{

View File

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

View File

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