1
0
mirror of https://github.com/gogf/gf.git synced 2025-04-05 11:18:50 +08:00

remove controller feature from package ghttp

This commit is contained in:
jflyfox 2021-07-30 15:15:44 +08:00
parent ef77a54c7e
commit 4267aadd78
15 changed files with 19 additions and 1117 deletions

View File

@ -8,13 +8,14 @@ package gerror
// Option is option for creating error.
type Option struct {
Error error // Wrapped error.
Stack bool // Record stack information into error.
Error error // Wrapped error if any.
Stack bool // Whether recording stack information into error.
Text string // Error text, which is created by New* functions.
Code int // Error code if necessary.
}
// NewOption creates and returns an error with Option.
// It is the senior usage for creating error, which is often used internally in framework.
func NewOption(option Option) error {
err := &Error{
error: option.Error,

View File

@ -71,17 +71,16 @@ type (
// handlerItem is the registered handler for route handling,
// including middleware and hook functions.
handlerItem struct {
Id int // Unique handler item id mark.
Name string // Handler name, which is automatically retrieved from runtime stack when registered.
Type int // Handler type: object/handler/controller/middleware/hook.
Info handlerFuncInfo // Handler function information.
InitFunc HandlerFunc // Initialization function when request enters the object (only available for object register type).
ShutFunc HandlerFunc // Shutdown function when request leaves out the object (only available for object register type).
Middleware []HandlerFunc // Bound middleware array.
CtrlInfo *handlerController // Controller information for reflect usage.
HookName string // Hook type name, only available for hook type.
Router *Router // Router object.
Source string // Registering source file `path:line`.
Id int // Unique handler item id mark.
Name string // Handler name, which is automatically retrieved from runtime stack when registered.
Type int // Handler type: object/handler/controller/middleware/hook.
Info handlerFuncInfo // Handler function information.
InitFunc HandlerFunc // Initialization function when request enters the object (only available for object register type).
ShutFunc HandlerFunc // Shutdown function when request leaves out the object (only available for object register type).
Middleware []HandlerFunc // Bound middleware array.
HookName string // Hook type name, only available for hook type.
Router *Router // Router object.
Source string // Registering source file `path:line`.
}
// handlerParsedItem is the item parsed from URL.Path.
@ -90,12 +89,6 @@ type (
Values map[string]string // Router values parsed from URL.Path.
}
// handlerController is the controller information used for reflect.
handlerController struct {
Name string // Handler method name.
Type reflect.Type // Reflect type of the controller.
}
// registeredRouteItem stores the information of the router and is used for route map.
registeredRouteItem struct {
Source string // Source file path and its line number.

View File

@ -1,13 +0,0 @@
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package ghttp
// Controller is the base struct for controller.
type Controller interface {
Init(*Request)
Shut()
}

View File

@ -59,27 +59,6 @@ func (m *middleware) Next() {
m.handlerIndex++
switch item.Handler.Type {
// Service controller.
case handlerTypeController:
m.served = true
if m.request.IsExited() {
break
}
c := reflect.New(item.Handler.CtrlInfo.Type)
niceCallFunc(func() {
c.MethodByName("Init").Call([]reflect.Value{reflect.ValueOf(m.request)})
})
if !m.request.IsExited() {
niceCallFunc(func() {
c.MethodByName(item.Handler.CtrlInfo.Name).Call(nil)
})
}
if !m.request.IsExited() {
niceCallFunc(func() {
c.MethodByName("Shut").Call(nil)
})
}
// Service object.
case handlerTypeObject:
m.served = true

View File

@ -79,45 +79,6 @@ func (d *Domain) doBindObjectRest(pattern string, obj interface{}, middleware []
}
}
func (d *Domain) BindController(pattern string, c Controller, methods ...string) {
for domain, _ := range d.domains {
d.server.BindController(pattern+"@"+domain, c, methods...)
}
}
func (d *Domain) doBindController(pattern string, c Controller, methods string, middleware []HandlerFunc, source string) {
for domain, _ := range d.domains {
d.server.doBindController(pattern+"@"+domain, c, methods, middleware, source)
}
}
func (d *Domain) BindControllerMethod(pattern string, c Controller, method string) {
for domain, _ := range d.domains {
d.server.BindControllerMethod(pattern+"@"+domain, c, method)
}
}
func (d *Domain) doBindControllerMethod(pattern string, c Controller, method string, middleware []HandlerFunc, source string) {
for domain, _ := range d.domains {
d.server.doBindControllerMethod(pattern+"@"+domain, c, method, middleware, source)
}
}
func (d *Domain) BindControllerRest(pattern string, c Controller) {
for domain, _ := range d.domains {
d.server.BindControllerRest(pattern+"@"+domain, c)
}
}
func (d *Domain) doBindControllerRest(
pattern string, c Controller,
middleware []HandlerFunc, source string,
) {
for domain, _ := range d.domains {
d.server.doBindControllerRest(pattern+"@"+domain, c, middleware, source)
}
}
func (d *Domain) BindHookHandler(pattern string, hook string, handler HandlerFunc) {
for domain, _ := range d.domains {
d.server.BindHookHandler(pattern+"@"+domain, hook, handler)

View File

@ -322,40 +322,6 @@ func (g *RouterGroup) doBindRoutersToServer(item *preBindItem) *RouterGroup {
} else {
g.domain.doBindHandler(pattern, funcInfo, g.middleware, source)
}
} else if g.isController(object) {
if len(extras) > 0 {
if g.server != nil {
if gstr.Contains(extras[0], ",") {
g.server.doBindController(
pattern, object.(Controller), extras[0], g.middleware, source,
)
} else {
g.server.doBindControllerMethod(
pattern, object.(Controller), extras[0], g.middleware, source,
)
}
} else {
if gstr.Contains(extras[0], ",") {
g.domain.doBindController(
pattern, object.(Controller), extras[0], g.middleware, source,
)
} else {
g.domain.doBindControllerMethod(
pattern, object.(Controller), extras[0], g.middleware, source,
)
}
}
} else {
if g.server != nil {
g.server.doBindController(
pattern, object.(Controller), "", g.middleware, source,
)
} else {
g.domain.doBindController(
pattern, object.(Controller), "", g.middleware, source,
)
}
}
} else {
if len(extras) > 0 {
if g.server != nil {
@ -390,22 +356,10 @@ func (g *RouterGroup) doBindRoutersToServer(item *preBindItem) *RouterGroup {
}
case "REST":
if g.isController(object) {
if g.server != nil {
g.server.doBindControllerRest(
pattern, object.(Controller), g.middleware, source,
)
} else {
g.domain.doBindControllerRest(
pattern, object.(Controller), g.middleware, source,
)
}
if g.server != nil {
g.server.doBindObjectRest(pattern, object, g.middleware, source)
} else {
if g.server != nil {
g.server.doBindObjectRest(pattern, object, g.middleware, source)
} else {
g.domain.doBindObjectRest(pattern, object, g.middleware, source)
}
g.domain.doBindObjectRest(pattern, object, g.middleware, source)
}
case "HOOK":
@ -421,27 +375,3 @@ func (g *RouterGroup) doBindRoutersToServer(item *preBindItem) *RouterGroup {
}
return g
}
// isController checks and returns whether given <value> is a controller.
// A controller should contains attributes: Request/Response/Server/Cookie/Session/View.
// Deprecated.
func (g *RouterGroup) isController(value interface{}) bool {
// Whether implements interface Controller.
if _, ok := value.(Controller); !ok {
return false
}
// Check the necessary attributes.
v := reflect.ValueOf(value)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
if v.FieldByName("Request").IsValid() &&
v.FieldByName("Response").IsValid() &&
v.FieldByName("Server").IsValid() &&
v.FieldByName("Cookie").IsValid() &&
v.FieldByName("Session").IsValid() &&
v.FieldByName("View").IsValid() {
return true
}
return false
}

View File

@ -1,238 +0,0 @@
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package ghttp
import (
"fmt"
"reflect"
"strings"
"github.com/gogf/gf/os/gfile"
"github.com/gogf/gf/text/gregex"
"github.com/gogf/gf/text/gstr"
)
// BindController registers controller to server routes with specified pattern. The controller
// needs to implement the gmvc.Controller interface. Each request of the controller bound in
// this way will initialize a new controller object for processing, corresponding to different
// request sessions.
//
// The optional parameter <method> is used to specify the method to be registered, which
// supports multiple method names, multiple methods are separated by char ',', case sensitive.
func (s *Server) BindController(pattern string, controller Controller, method ...string) {
bindMethod := ""
if len(method) > 0 {
bindMethod = method[0]
}
s.doBindController(pattern, controller, bindMethod, nil, "")
}
// BindControllerMethod registers specified method to server routes with specified pattern.
//
// The optional parameter <method> is used to specify the method to be registered, which
// does not supports multiple method names but only one, case sensitive.
func (s *Server) BindControllerMethod(pattern string, controller Controller, method string) {
s.doBindControllerMethod(pattern, controller, method, nil, "")
}
// BindControllerRest registers controller in REST API style to server with specified pattern.
// The controller needs to implement the gmvc.Controller interface. Each request of the controller
// bound in this way will initialize a new controller object for processing, corresponding to
// different request sessions.
// The method will recognize the HTTP method and do REST binding, for example:
// The method "Post" of controller will be bound to the HTTP POST method request processing,
// and the method "Delete" will be bound to the HTTP DELETE method request processing.
// Therefore, only the method corresponding to the HTTP Method will be bound, other methods will
// not automatically register the binding.
func (s *Server) BindControllerRest(pattern string, controller Controller) {
s.doBindControllerRest(pattern, controller, nil, "")
}
func (s *Server) doBindController(
pattern string, controller Controller, method string,
middleware []HandlerFunc, source string,
) {
// Convert input method to map for convenience and high performance searching.
var methodMap map[string]bool
if len(method) > 0 {
methodMap = make(map[string]bool)
for _, v := range strings.Split(method, ",") {
methodMap[strings.TrimSpace(v)] = true
}
}
domain, method, path, err := s.parsePattern(pattern)
if err != nil {
s.Logger().Fatal(err)
return
}
if strings.EqualFold(method, defaultMethod) {
pattern = s.serveHandlerKey("", path, domain)
}
// Retrieve a list of methods, create construct corresponding URI.
var (
m = make(map[string]*handlerItem)
v = reflect.ValueOf(controller)
t = v.Type()
pkgPath = t.Elem().PkgPath()
pkgName = gfile.Basename(pkgPath)
structName = t.Elem().Name()
)
for i := 0; i < v.NumMethod(); i++ {
methodName := t.Method(i).Name
if methodMap != nil && !methodMap[methodName] {
continue
}
if methodName == methodNameInit || methodName == methodNameShut || methodName == methodNameExit {
continue
}
ctlName := gstr.Replace(t.String(), fmt.Sprintf(`%s.`, pkgName), "")
if ctlName[0] == '*' {
ctlName = fmt.Sprintf(`(%s)`, ctlName)
}
if _, ok := v.Method(i).Interface().(func()); !ok {
if len(methodMap) > 0 {
// If registering with specified method, print error.
s.Logger().Errorf(
`invalid route method: %s.%s.%s defined as "%s", but "func()" is required for controller registry`,
pkgPath, ctlName, methodName, v.Method(i).Type().String(),
)
} else {
// Else, just print debug information.
s.Logger().Debugf(
`ignore route method: %s.%s.%s defined as "%s", no match "func()" for controller registry`,
pkgPath, ctlName, methodName, v.Method(i).Type().String(),
)
}
continue
}
key := s.mergeBuildInNameToPattern(pattern, structName, methodName, true)
m[key] = &handlerItem{
Name: fmt.Sprintf(`%s.%s.%s`, pkgPath, ctlName, methodName),
Type: handlerTypeController,
CtrlInfo: &handlerController{
Name: methodName,
Type: v.Elem().Type(),
},
Middleware: middleware,
Source: source,
}
// If there's "Index" method, then an additional route is automatically added
// to match the main URI, for example:
// If pattern is "/user", then "/user" and "/user/index" are both automatically
// registered.
//
// Note that if there's built-in variables in pattern, this route will not be added
// automatically.
if strings.EqualFold(methodName, "Index") && !gregex.IsMatchString(`\{\.\w+\}`, pattern) {
p := gstr.PosRI(key, "/index")
k := key[0:p] + key[p+6:]
if len(k) == 0 || k[0] == '@' {
k = "/" + k
}
m[k] = &handlerItem{
Name: fmt.Sprintf(`%s.%s.%s`, pkgPath, ctlName, methodName),
Type: handlerTypeController,
CtrlInfo: &handlerController{
Name: methodName,
Type: v.Elem().Type(),
},
Middleware: middleware,
Source: source,
}
}
}
s.bindHandlerByMap(m)
}
func (s *Server) doBindControllerMethod(
pattern string,
controller Controller,
method string,
middleware []HandlerFunc,
source string,
) {
var (
m = make(map[string]*handlerItem)
v = reflect.ValueOf(controller)
t = v.Type()
structName = t.Elem().Name()
methodName = strings.TrimSpace(method)
methodValue = v.MethodByName(methodName)
)
if !methodValue.IsValid() {
s.Logger().Fatal("invalid method name: " + methodName)
return
}
pkgPath := t.Elem().PkgPath()
pkgName := gfile.Basename(pkgPath)
ctlName := gstr.Replace(t.String(), fmt.Sprintf(`%s.`, pkgName), "")
if ctlName[0] == '*' {
ctlName = fmt.Sprintf(`(%s)`, ctlName)
}
if _, ok := methodValue.Interface().(func()); !ok {
s.Logger().Errorf(
`invalid route method: %s.%s.%s defined as "%s", but "func()" is required for controller registry`,
pkgPath, ctlName, methodName, methodValue.Type().String(),
)
return
}
key := s.mergeBuildInNameToPattern(pattern, structName, methodName, false)
m[key] = &handlerItem{
Name: fmt.Sprintf(`%s.%s.%s`, pkgPath, ctlName, methodName),
Type: handlerTypeController,
CtrlInfo: &handlerController{
Name: methodName,
Type: v.Elem().Type(),
},
Middleware: middleware,
Source: source,
}
s.bindHandlerByMap(m)
}
func (s *Server) doBindControllerRest(
pattern string, controller Controller,
middleware []HandlerFunc, source string,
) {
var (
m = make(map[string]*handlerItem)
v = reflect.ValueOf(controller)
t = v.Type()
pkgPath = t.Elem().PkgPath()
structName = t.Elem().Name()
)
for i := 0; i < v.NumMethod(); i++ {
methodName := t.Method(i).Name
if _, ok := methodsMap[strings.ToUpper(methodName)]; !ok {
continue
}
pkgName := gfile.Basename(pkgPath)
ctlName := gstr.Replace(t.String(), fmt.Sprintf(`%s.`, pkgName), "")
if ctlName[0] == '*' {
ctlName = fmt.Sprintf(`(%s)`, ctlName)
}
if _, ok := v.Method(i).Interface().(func()); !ok {
s.Logger().Errorf(
`invalid route method: %s.%s.%s defined as "%s", but "func()" is required for controller registry`,
pkgPath, ctlName, methodName, v.Method(i).Type().String(),
)
return
}
key := s.mergeBuildInNameToPattern(methodName+":"+pattern, structName, methodName, false)
m[key] = &handlerItem{
Name: fmt.Sprintf(`%s.%s.%s`, pkgPath, ctlName, methodName),
Type: handlerTypeController,
CtrlInfo: &handlerController{
Name: methodName,
Type: v.Elem().Type(),
},
Middleware: middleware,
Source: source,
}
}
s.bindHandlerByMap(m)
}

View File

@ -145,10 +145,7 @@ func (s *Server) doBindObject(pattern string, object interface{}, method string,
s.bindHandlerByMap(m)
}
func (s *Server) doBindObjectMethod(
pattern string, object interface{}, method string,
middleware []HandlerFunc, source string,
) {
func (s *Server) doBindObjectMethod(pattern string, object interface{}, method string, middleware []HandlerFunc, source string) {
var (
m = make(map[string]*handlerItem)
v = reflect.ValueOf(object)

View File

@ -1,93 +0,0 @@
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package ghttp_test
import (
"fmt"
"testing"
"time"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/frame/gmvc"
"github.com/gogf/gf/net/ghttp"
"github.com/gogf/gf/test/gtest"
)
type ControllerRest struct {
gmvc.Controller
}
func (c *ControllerRest) Init(r *ghttp.Request) {
c.Controller.Init(r)
c.Response.Write("1")
}
func (c *ControllerRest) Shut() {
c.Response.Write("2")
}
func (c *ControllerRest) Get() {
c.Response.Write("Controller Get")
}
func (c *ControllerRest) Put() {
c.Response.Write("Controller Put")
}
func (c *ControllerRest) Post() {
c.Response.Write("Controller Post")
}
func (c *ControllerRest) Delete() {
c.Response.Write("Controller Delete")
}
func (c *ControllerRest) Head() {
c.Response.Header().Set("head-ok", "1")
}
// 控制器注册测试
func Test_Router_ControllerRest(t *testing.T) {
p, _ := ports.PopRand()
s := g.Server(p)
s.BindControllerRest("/", new(ControllerRest))
s.BindControllerRest("/{.struct}/{.method}", new(ControllerRest))
s.SetPort(p)
s.SetDumpRouterMap(false)
s.Start()
defer s.Shutdown()
time.Sleep(100 * time.Millisecond)
gtest.C(t, func(t *gtest.T) {
client := g.Client()
client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p))
t.Assert(client.GetContent("/"), "1Controller Get2")
t.Assert(client.PutContent("/"), "1Controller Put2")
t.Assert(client.PostContent("/"), "1Controller Post2")
t.Assert(client.DeleteContent("/"), "1Controller Delete2")
resp1, err := client.Head("/")
if err == nil {
defer resp1.Close()
}
t.Assert(err, nil)
t.Assert(resp1.Header.Get("head-ok"), "1")
t.Assert(client.GetContent("/controller-rest/get"), "1Controller Get2")
t.Assert(client.PutContent("/controller-rest/put"), "1Controller Put2")
t.Assert(client.PostContent("/controller-rest/post"), "1Controller Post2")
t.Assert(client.DeleteContent("/controller-rest/delete"), "1Controller Delete2")
resp2, err := client.Head("/controller-rest/head")
if err == nil {
defer resp2.Close()
}
t.Assert(err, nil)
t.Assert(resp2.Header.Get("head-ok"), "1")
t.Assert(client.GetContent("/none-exist"), "Not Found")
})
}

View File

@ -1,128 +0,0 @@
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package ghttp_test
import (
"fmt"
"testing"
"time"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/frame/gmvc"
"github.com/gogf/gf/net/ghttp"
"github.com/gogf/gf/test/gtest"
)
// 控制器
type Controller struct {
gmvc.Controller
}
func (c *Controller) Init(r *ghttp.Request) {
c.Controller.Init(r)
c.Response.Write("1")
}
func (c *Controller) Shut() {
c.Response.Write("2")
}
func (c *Controller) Index() {
c.Response.Write("Controller Index")
}
func (c *Controller) Show() {
c.Response.Write("Controller Show")
}
func (c *Controller) Info() {
c.Response.Write("Controller Info")
}
func Test_Router_Controller1(t *testing.T) {
p, _ := ports.PopRand()
s := g.Server(p)
s.BindController("/", new(Controller))
s.BindController("/{.struct}/{.method}", new(Controller))
s.SetPort(p)
s.SetDumpRouterMap(false)
s.Start()
defer s.Shutdown()
time.Sleep(100 * time.Millisecond)
gtest.C(t, func(t *gtest.T) {
client := g.Client()
client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p))
t.Assert(client.GetContent("/"), "1Controller Index2")
t.Assert(client.GetContent("/init"), "Not Found")
t.Assert(client.GetContent("/shut"), "Not Found")
t.Assert(client.GetContent("/index"), "1Controller Index2")
t.Assert(client.GetContent("/show"), "1Controller Show2")
t.Assert(client.GetContent("/controller"), "Not Found")
t.Assert(client.GetContent("/controller/init"), "Not Found")
t.Assert(client.GetContent("/controller/shut"), "Not Found")
t.Assert(client.GetContent("/controller/index"), "1Controller Index2")
t.Assert(client.GetContent("/controller/show"), "1Controller Show2")
t.Assert(client.GetContent("/none-exist"), "Not Found")
})
}
func Test_Router_Controller2(t *testing.T) {
p, _ := ports.PopRand()
s := g.Server(p)
s.BindController("/controller", new(Controller), "Show, Info")
s.SetPort(p)
s.SetDumpRouterMap(false)
s.Start()
defer s.Shutdown()
time.Sleep(100 * time.Millisecond)
gtest.C(t, func(t *gtest.T) {
client := g.Client()
client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p))
t.Assert(client.GetContent("/"), "Not Found")
t.Assert(client.GetContent("/controller"), "Not Found")
t.Assert(client.GetContent("/controller/init"), "Not Found")
t.Assert(client.GetContent("/controller/shut"), "Not Found")
t.Assert(client.GetContent("/controller/index"), "Not Found")
t.Assert(client.GetContent("/controller/show"), "1Controller Show2")
t.Assert(client.GetContent("/controller/info"), "1Controller Info2")
t.Assert(client.GetContent("/none-exist"), "Not Found")
})
}
func Test_Router_ControllerMethod(t *testing.T) {
p, _ := ports.PopRand()
s := g.Server(p)
s.BindControllerMethod("/controller-info", new(Controller), "Info")
s.SetPort(p)
s.SetDumpRouterMap(false)
s.Start()
defer s.Shutdown()
time.Sleep(100 * time.Millisecond)
gtest.C(t, func(t *gtest.T) {
client := g.Client()
client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p))
t.Assert(client.GetContent("/"), "Not Found")
t.Assert(client.GetContent("/controller"), "Not Found")
t.Assert(client.GetContent("/controller/init"), "Not Found")
t.Assert(client.GetContent("/controller/shut"), "Not Found")
t.Assert(client.GetContent("/controller/index"), "Not Found")
t.Assert(client.GetContent("/controller/show"), "Not Found")
t.Assert(client.GetContent("/controller/info"), "Not Found")
t.Assert(client.GetContent("/controller-info"), "1Controller Info2")
t.Assert(client.GetContent("/none-exist"), "Not Found")
})
}

View File

@ -1,127 +0,0 @@
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package ghttp_test
import (
"fmt"
"testing"
"time"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/frame/gmvc"
"github.com/gogf/gf/net/ghttp"
"github.com/gogf/gf/test/gtest"
)
type DomainControllerRest struct {
gmvc.Controller
}
func (c *DomainControllerRest) Init(r *ghttp.Request) {
c.Controller.Init(r)
c.Response.Write("1")
}
func (c *DomainControllerRest) Shut() {
c.Response.Write("2")
}
func (c *DomainControllerRest) Get() {
c.Response.Write("Controller Get")
}
func (c *DomainControllerRest) Put() {
c.Response.Write("Controller Put")
}
func (c *DomainControllerRest) Post() {
c.Response.Write("Controller Post")
}
func (c *DomainControllerRest) Delete() {
c.Response.Write("Controller Delete")
}
func (c *DomainControllerRest) Patch() {
c.Response.Write("Controller Patch")
}
func (c *DomainControllerRest) Options() {
c.Response.Write("Controller Options")
}
func (c *DomainControllerRest) Head() {
c.Response.Header().Set("head-ok", "1")
}
// 控制器注册测试
func Test_Router_DomainControllerRest(t *testing.T) {
p, _ := ports.PopRand()
s := g.Server(p)
d := s.Domain("localhost, local")
d.BindControllerRest("/", new(DomainControllerRest))
s.SetPort(p)
s.SetDumpRouterMap(false)
s.Start()
defer s.Shutdown()
time.Sleep(100 * time.Millisecond)
gtest.C(t, func(t *gtest.T) {
client := g.Client()
client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p))
t.Assert(client.GetContent("/"), "Not Found")
t.Assert(client.PutContent("/"), "Not Found")
t.Assert(client.PostContent("/"), "Not Found")
t.Assert(client.DeleteContent("/"), "Not Found")
t.Assert(client.PatchContent("/"), "Not Found")
t.Assert(client.OptionsContent("/"), "Not Found")
resp1, err := client.Head("/")
if err == nil {
defer resp1.Close()
}
t.Assert(err, nil)
t.Assert(resp1.Header.Get("head-ok"), "")
t.Assert(client.GetContent("/none-exist"), "Not Found")
})
gtest.C(t, func(t *gtest.T) {
client := g.Client()
client.SetPrefix(fmt.Sprintf("http://localhost:%d", p))
t.Assert(client.GetContent("/"), "1Controller Get2")
t.Assert(client.PutContent("/"), "1Controller Put2")
t.Assert(client.PostContent("/"), "1Controller Post2")
t.Assert(client.DeleteContent("/"), "1Controller Delete2")
t.Assert(client.PatchContent("/"), "1Controller Patch2")
t.Assert(client.OptionsContent("/"), "1Controller Options2")
resp1, err := client.Head("/")
if err == nil {
defer resp1.Close()
}
t.Assert(err, nil)
t.Assert(resp1.Header.Get("head-ok"), "1")
t.Assert(client.GetContent("/none-exist"), "Not Found")
})
gtest.C(t, func(t *gtest.T) {
client := g.Client()
client.SetPrefix(fmt.Sprintf("http://local:%d", p))
t.Assert(client.GetContent("/"), "1Controller Get2")
t.Assert(client.PutContent("/"), "1Controller Put2")
t.Assert(client.PostContent("/"), "1Controller Post2")
t.Assert(client.DeleteContent("/"), "1Controller Delete2")
t.Assert(client.PatchContent("/"), "1Controller Patch2")
t.Assert(client.OptionsContent("/"), "1Controller Options2")
resp1, err := client.Head("/")
if err == nil {
defer resp1.Close()
}
t.Assert(err, nil)
t.Assert(resp1.Header.Get("head-ok"), "1")
t.Assert(client.GetContent("/none-exist"), "Not Found")
})
}

View File

@ -1,200 +0,0 @@
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package ghttp_test
import (
"fmt"
"testing"
"time"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/frame/gmvc"
"github.com/gogf/gf/net/ghttp"
"github.com/gogf/gf/test/gtest"
)
type DomainController struct {
gmvc.Controller
}
func (c *DomainController) Init(r *ghttp.Request) {
c.Controller.Init(r)
c.Response.Write("1")
}
func (c *DomainController) Shut() {
c.Response.Write("2")
}
func (c *DomainController) Index() {
c.Response.Write("Controller Index")
}
func (c *DomainController) Show() {
c.Response.Write("Controller Show")
}
func (c *DomainController) Info() {
c.Response.Write("Controller Info")
}
func Test_Router_DomainController1(t *testing.T) {
p, _ := ports.PopRand()
s := g.Server(p)
s.Domain("localhost, local").BindController("/", new(DomainController))
s.SetPort(p)
s.SetDumpRouterMap(false)
s.Start()
defer s.Shutdown()
time.Sleep(100 * time.Millisecond)
gtest.C(t, func(t *gtest.T) {
client := g.Client()
client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p))
t.Assert(client.GetContent("/"), "Not Found")
t.Assert(client.GetContent("/init"), "Not Found")
t.Assert(client.GetContent("/shut"), "Not Found")
t.Assert(client.GetContent("/index"), "Not Found")
t.Assert(client.GetContent("/show"), "Not Found")
t.Assert(client.GetContent("/info"), "Not Found")
t.Assert(client.GetContent("/none-exist"), "Not Found")
})
gtest.C(t, func(t *gtest.T) {
client := g.Client()
client.SetPrefix(fmt.Sprintf("http://localhost:%d", p))
t.Assert(client.GetContent("/"), "1Controller Index2")
t.Assert(client.GetContent("/init"), "Not Found")
t.Assert(client.GetContent("/shut"), "Not Found")
t.Assert(client.GetContent("/index"), "1Controller Index2")
t.Assert(client.GetContent("/show"), "1Controller Show2")
t.Assert(client.GetContent("/info"), "1Controller Info2")
t.Assert(client.GetContent("/none-exist"), "Not Found")
})
gtest.C(t, func(t *gtest.T) {
client := g.Client()
client.SetPrefix(fmt.Sprintf("http://local:%d", p))
t.Assert(client.GetContent("/"), "1Controller Index2")
t.Assert(client.GetContent("/init"), "Not Found")
t.Assert(client.GetContent("/shut"), "Not Found")
t.Assert(client.GetContent("/index"), "1Controller Index2")
t.Assert(client.GetContent("/show"), "1Controller Show2")
t.Assert(client.GetContent("/info"), "1Controller Info2")
t.Assert(client.GetContent("/none-exist"), "Not Found")
})
}
func Test_Router_DomainController2(t *testing.T) {
p, _ := ports.PopRand()
s := g.Server(p)
s.Domain("localhost, local").BindController("/controller", new(DomainController), "Show, Info")
s.SetPort(p)
s.SetDumpRouterMap(false)
s.Start()
defer s.Shutdown()
time.Sleep(100 * time.Millisecond)
gtest.C(t, func(t *gtest.T) {
client := g.Client()
client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p))
t.Assert(client.GetContent("/"), "Not Found")
t.Assert(client.GetContent("/controller"), "Not Found")
t.Assert(client.GetContent("/controller/init"), "Not Found")
t.Assert(client.GetContent("/controller/shut"), "Not Found")
t.Assert(client.GetContent("/controller/index"), "Not Found")
t.Assert(client.GetContent("/controller/show"), "Not Found")
t.Assert(client.GetContent("/controller/info"), "Not Found")
t.Assert(client.GetContent("/none-exist"), "Not Found")
})
gtest.C(t, func(t *gtest.T) {
client := g.Client()
client.SetPrefix(fmt.Sprintf("http://localhost:%d", p))
t.Assert(client.GetContent("/"), "Not Found")
t.Assert(client.GetContent("/controller"), "Not Found")
t.Assert(client.GetContent("/controller/init"), "Not Found")
t.Assert(client.GetContent("/controller/shut"), "Not Found")
t.Assert(client.GetContent("/controller/index"), "Not Found")
t.Assert(client.GetContent("/controller/show"), "1Controller Show2")
t.Assert(client.GetContent("/controller/info"), "1Controller Info2")
t.Assert(client.GetContent("/none-exist"), "Not Found")
})
gtest.C(t, func(t *gtest.T) {
client := g.Client()
client.SetPrefix(fmt.Sprintf("http://local:%d", p))
t.Assert(client.GetContent("/"), "Not Found")
t.Assert(client.GetContent("/controller"), "Not Found")
t.Assert(client.GetContent("/controller/init"), "Not Found")
t.Assert(client.GetContent("/controller/shut"), "Not Found")
t.Assert(client.GetContent("/controller/index"), "Not Found")
t.Assert(client.GetContent("/controller/show"), "1Controller Show2")
t.Assert(client.GetContent("/controller/info"), "1Controller Info2")
t.Assert(client.GetContent("/none-exist"), "Not Found")
})
}
func Test_Router_DomainControllerMethod(t *testing.T) {
p, _ := ports.PopRand()
s := g.Server(p)
s.Domain("localhost, local").BindControllerMethod("/controller-info", new(DomainController), "Info")
s.SetPort(p)
s.SetDumpRouterMap(false)
s.Start()
defer s.Shutdown()
time.Sleep(100 * time.Millisecond)
gtest.C(t, func(t *gtest.T) {
client := g.Client()
client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p))
t.Assert(client.GetContent("/"), "Not Found")
t.Assert(client.GetContent("/controller"), "Not Found")
t.Assert(client.GetContent("/controller/init"), "Not Found")
t.Assert(client.GetContent("/controller/shut"), "Not Found")
t.Assert(client.GetContent("/controller/index"), "Not Found")
t.Assert(client.GetContent("/controller/show"), "Not Found")
t.Assert(client.GetContent("/controller/info"), "Not Found")
t.Assert(client.GetContent("/controller-info"), "Not Found")
t.Assert(client.GetContent("/none-exist"), "Not Found")
})
gtest.C(t, func(t *gtest.T) {
client := g.Client()
client.SetPrefix(fmt.Sprintf("http://localhost:%d", p))
t.Assert(client.GetContent("/"), "Not Found")
t.Assert(client.GetContent("/controller"), "Not Found")
t.Assert(client.GetContent("/controller/init"), "Not Found")
t.Assert(client.GetContent("/controller/shut"), "Not Found")
t.Assert(client.GetContent("/controller/index"), "Not Found")
t.Assert(client.GetContent("/controller/show"), "Not Found")
t.Assert(client.GetContent("/controller/info"), "Not Found")
t.Assert(client.GetContent("/controller-info"), "1Controller Info2")
t.Assert(client.GetContent("/none-exist"), "Not Found")
})
gtest.C(t, func(t *gtest.T) {
client := g.Client()
client.SetPrefix(fmt.Sprintf("http://local:%d", p))
t.Assert(client.GetContent("/"), "Not Found")
t.Assert(client.GetContent("/controller"), "Not Found")
t.Assert(client.GetContent("/controller/init"), "Not Found")
t.Assert(client.GetContent("/controller/shut"), "Not Found")
t.Assert(client.GetContent("/controller/index"), "Not Found")
t.Assert(client.GetContent("/controller/show"), "Not Found")
t.Assert(client.GetContent("/controller/info"), "Not Found")
t.Assert(client.GetContent("/controller-info"), "1Controller Info2")
t.Assert(client.GetContent("/none-exist"), "Not Found")
})
}

View File

@ -13,52 +13,10 @@ import (
"time"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/frame/gmvc"
"github.com/gogf/gf/net/ghttp"
"github.com/gogf/gf/test/gtest"
)
type GroupCtlRest struct {
gmvc.Controller
}
func (c *GroupCtlRest) Init(r *ghttp.Request) {
c.Controller.Init(r)
c.Response.Write("1")
}
func (c *GroupCtlRest) Shut() {
c.Response.Write("2")
}
func (c *GroupCtlRest) Get() {
c.Response.Write("Controller Get")
}
func (c *GroupCtlRest) Put() {
c.Response.Write("Controller Put")
}
func (c *GroupCtlRest) Post() {
c.Response.Write("Controller Post")
}
func (c *GroupCtlRest) Delete() {
c.Response.Write("Controller Delete")
}
func (c *GroupCtlRest) Patch() {
c.Response.Write("Controller Patch")
}
func (c *GroupCtlRest) Options() {
c.Response.Write("Controller Options")
}
func (c *GroupCtlRest) Head() {
c.Response.Header().Set("head-ok", "1")
}
type GroupObjRest struct{}
func (o *GroupObjRest) Init(r *ghttp.Request) {
@ -101,11 +59,8 @@ func Test_Router_GroupRest1(t *testing.T) {
p, _ := ports.PopRand()
s := g.Server(p)
group := s.Group("/api")
ctl := new(GroupCtlRest)
obj := new(GroupObjRest)
group.REST("/ctl", ctl)
group.REST("/obj", obj)
group.REST("/{.struct}/{.method}", ctl)
group.REST("/{.struct}/{.method}", obj)
s.SetPort(p)
s.SetDumpRouterMap(false)
@ -117,19 +72,6 @@ func Test_Router_GroupRest1(t *testing.T) {
client := g.Client()
client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p))
t.Assert(client.GetContent("/api/ctl"), "1Controller Get2")
t.Assert(client.PutContent("/api/ctl"), "1Controller Put2")
t.Assert(client.PostContent("/api/ctl"), "1Controller Post2")
t.Assert(client.DeleteContent("/api/ctl"), "1Controller Delete2")
t.Assert(client.PatchContent("/api/ctl"), "1Controller Patch2")
t.Assert(client.OptionsContent("/api/ctl"), "1Controller Options2")
resp1, err := client.Head("/api/ctl")
if err == nil {
defer resp1.Close()
}
t.Assert(err, nil)
t.Assert(resp1.Header.Get("head-ok"), "1")
t.Assert(client.GetContent("/api/obj"), "1Object Get2")
t.Assert(client.PutContent("/api/obj"), "1Object Put2")
t.Assert(client.PostContent("/api/obj"), "1Object Post2")
@ -143,20 +85,6 @@ func Test_Router_GroupRest1(t *testing.T) {
t.Assert(err, nil)
t.Assert(resp2.Header.Get("head-ok"), "1")
t.Assert(client.GetContent("/api/group-ctl-rest"), "Not Found")
t.Assert(client.GetContent("/api/group-ctl-rest/get"), "1Controller Get2")
t.Assert(client.PutContent("/api/group-ctl-rest/put"), "1Controller Put2")
t.Assert(client.PostContent("/api/group-ctl-rest/post"), "1Controller Post2")
t.Assert(client.DeleteContent("/api/group-ctl-rest/delete"), "1Controller Delete2")
t.Assert(client.PatchContent("/api/group-ctl-rest/patch"), "1Controller Patch2")
t.Assert(client.OptionsContent("/api/group-ctl-rest/options"), "1Controller Options2")
resp3, err := client.Head("/api/group-ctl-rest/head")
if err == nil {
defer resp3.Close()
}
t.Assert(err, nil)
t.Assert(resp3.Header.Get("head-ok"), "1")
t.Assert(client.GetContent("/api/group-obj-rest"), "Not Found")
t.Assert(client.GetContent("/api/group-obj-rest/get"), "1Object Get2")
t.Assert(client.PutContent("/api/group-obj-rest/put"), "1Object Put2")
@ -177,11 +105,8 @@ func Test_Router_GroupRest2(t *testing.T) {
p, _ := ports.PopRand()
s := g.Server(p)
s.Group("/api", func(group *ghttp.RouterGroup) {
ctl := new(GroupCtlRest)
obj := new(GroupObjRest)
group.REST("/ctl", ctl)
group.REST("/obj", obj)
group.REST("/{.struct}/{.method}", ctl)
group.REST("/{.struct}/{.method}", obj)
})
s.SetPort(p)
@ -194,19 +119,6 @@ func Test_Router_GroupRest2(t *testing.T) {
client := g.Client()
client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p))
t.Assert(client.GetContent("/api/ctl"), "1Controller Get2")
t.Assert(client.PutContent("/api/ctl"), "1Controller Put2")
t.Assert(client.PostContent("/api/ctl"), "1Controller Post2")
t.Assert(client.DeleteContent("/api/ctl"), "1Controller Delete2")
t.Assert(client.PatchContent("/api/ctl"), "1Controller Patch2")
t.Assert(client.OptionsContent("/api/ctl"), "1Controller Options2")
resp1, err := client.Head("/api/ctl")
if err == nil {
defer resp1.Close()
}
t.Assert(err, nil)
t.Assert(resp1.Header.Get("head-ok"), "1")
t.Assert(client.GetContent("/api/obj"), "1Object Get2")
t.Assert(client.PutContent("/api/obj"), "1Object Put2")
t.Assert(client.PostContent("/api/obj"), "1Object Post2")
@ -220,20 +132,6 @@ func Test_Router_GroupRest2(t *testing.T) {
t.Assert(err, nil)
t.Assert(resp2.Header.Get("head-ok"), "1")
t.Assert(client.GetContent("/api/group-ctl-rest"), "Not Found")
t.Assert(client.GetContent("/api/group-ctl-rest/get"), "1Controller Get2")
t.Assert(client.PutContent("/api/group-ctl-rest/put"), "1Controller Put2")
t.Assert(client.PostContent("/api/group-ctl-rest/post"), "1Controller Post2")
t.Assert(client.DeleteContent("/api/group-ctl-rest/delete"), "1Controller Delete2")
t.Assert(client.PatchContent("/api/group-ctl-rest/patch"), "1Controller Patch2")
t.Assert(client.OptionsContent("/api/group-ctl-rest/options"), "1Controller Options2")
resp3, err := client.Head("/api/group-ctl-rest/head")
if err == nil {
defer resp3.Close()
}
t.Assert(err, nil)
t.Assert(resp3.Header.Get("head-ok"), "1")
t.Assert(client.GetContent("/api/group-obj-rest"), "Not Found")
t.Assert(client.GetContent("/api/group-obj-rest/get"), "1Object Get2")
t.Assert(client.PutContent("/api/group-obj-rest/put"), "1Object Put2")

View File

@ -12,7 +12,6 @@ import (
"time"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/frame/gmvc"
"github.com/gogf/gf/net/ghttp"
"github.com/gogf/gf/test/gtest"
)
@ -40,32 +39,6 @@ func (o *GroupObject) Delete(r *ghttp.Request) {
r.Response.Write("Object Delete")
}
// 控制器
type GroupController struct {
gmvc.Controller
}
func (c *GroupController) Init(r *ghttp.Request) {
c.Controller.Init(r)
c.Response.Write("1")
}
func (c *GroupController) Shut() {
c.Response.Write("2")
}
func (c *GroupController) Index() {
c.Response.Write("Controller Index")
}
func (c *GroupController) Show() {
c.Response.Write("Controller Show")
}
func (c *GroupController) Post() {
c.Response.Write("Controller Post")
}
func Handler(r *ghttp.Request) {
r.Response.Write("Handler")
}
@ -74,13 +47,9 @@ func Test_Router_GroupBasic1(t *testing.T) {
p, _ := ports.PopRand()
s := g.Server(p)
obj := new(GroupObject)
ctl := new(GroupController)
// 分组路由方法注册
group := s.Group("/api")
group.ALL("/handler", Handler)
group.ALL("/ctl", ctl)
group.GET("/ctl/my-show", ctl, "Show")
group.REST("/ctl/rest", ctl)
group.ALL("/obj", obj)
group.GET("/obj/my-show", obj, "Show")
group.REST("/obj/rest", obj)
@ -96,14 +65,6 @@ func Test_Router_GroupBasic1(t *testing.T) {
t.Assert(client.GetContent("/api/handler"), "Handler")
t.Assert(client.GetContent("/api/ctl"), "1Controller Index2")
t.Assert(client.GetContent("/api/ctl/"), "1Controller Index2")
t.Assert(client.GetContent("/api/ctl/index"), "1Controller Index2")
t.Assert(client.GetContent("/api/ctl/my-show"), "1Controller Show2")
t.Assert(client.GetContent("/api/ctl/post"), "1Controller Post2")
t.Assert(client.GetContent("/api/ctl/show"), "1Controller Show2")
t.Assert(client.PostContent("/api/ctl/rest"), "1Controller Post2")
t.Assert(client.GetContent("/api/obj"), "1Object Index2")
t.Assert(client.GetContent("/api/obj/"), "1Object Index2")
t.Assert(client.GetContent("/api/obj/index"), "1Object Index2")
@ -121,13 +82,9 @@ func Test_Router_GroupBasic2(t *testing.T) {
p, _ := ports.PopRand()
s := g.Server(p)
obj := new(GroupObject)
ctl := new(GroupController)
// 分组路由批量注册
s.Group("/api").Bind([]g.Slice{
{"ALL", "/handler", Handler},
{"ALL", "/ctl", ctl},
{"GET", "/ctl/my-show", ctl, "Show"},
{"REST", "/ctl/rest", ctl},
{"ALL", "/obj", obj},
{"GET", "/obj/my-show", obj, "Show"},
{"REST", "/obj/rest", obj},
@ -144,11 +101,6 @@ func Test_Router_GroupBasic2(t *testing.T) {
t.Assert(client.GetContent("/api/handler"), "Handler")
t.Assert(client.GetContent("/api/ctl/my-show"), "1Controller Show2")
t.Assert(client.GetContent("/api/ctl/post"), "1Controller Post2")
t.Assert(client.GetContent("/api/ctl/show"), "1Controller Show2")
t.Assert(client.PostContent("/api/ctl/rest"), "1Controller Post2")
t.Assert(client.GetContent("/api/obj/delete"), "1Object Delete2")
t.Assert(client.GetContent("/api/obj/my-show"), "1Object Show2")
t.Assert(client.GetContent("/api/obj/show"), "1Object Show2")
@ -163,10 +115,8 @@ func Test_Router_GroupBuildInVar(t *testing.T) {
p, _ := ports.PopRand()
s := g.Server(p)
obj := new(GroupObject)
ctl := new(GroupController)
// 分组路由方法注册
group := s.Group("/api")
group.ALL("/{.struct}/{.method}", ctl)
group.ALL("/{.struct}/{.method}", obj)
s.SetPort(p)
s.SetDumpRouterMap(false)
@ -178,10 +128,6 @@ func Test_Router_GroupBuildInVar(t *testing.T) {
client := g.Client()
client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p))
t.Assert(client.GetContent("/api/group-controller/index"), "1Controller Index2")
t.Assert(client.GetContent("/api/group-controller/post"), "1Controller Post2")
t.Assert(client.GetContent("/api/group-controller/show"), "1Controller Show2")
t.Assert(client.GetContent("/api/group-object/index"), "1Object Index2")
t.Assert(client.GetContent("/api/group-object/delete"), "1Object Delete2")
t.Assert(client.GetContent("/api/group-object/show"), "1Object Show2")
@ -191,14 +137,12 @@ func Test_Router_GroupBuildInVar(t *testing.T) {
})
}
func Test_Router_Group_Mthods(t *testing.T) {
func Test_Router_Group_Methods(t *testing.T) {
p, _ := ports.PopRand()
s := g.Server(p)
obj := new(GroupObject)
ctl := new(GroupController)
group := s.Group("/")
group.ALL("/obj", obj, "Show, Delete")
group.ALL("/ctl", ctl, "Show, Post")
s.SetPort(p)
s.SetDumpRouterMap(false)
s.Start()
@ -208,8 +152,6 @@ func Test_Router_Group_Mthods(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
client := g.Client()
client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p))
t.Assert(client.GetContent("/ctl/show"), "1Controller Show2")
t.Assert(client.GetContent("/ctl/post"), "1Controller Post2")
t.Assert(client.GetContent("/obj/show"), "1Object Show2")
t.Assert(client.GetContent("/obj/delete"), "1Object Delete2")
})

View File

@ -77,6 +77,6 @@ func Test_Router_Handler_Extended_Handler_WithObject(t *testing.T) {
client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p))
t.Assert(client.GetContent("/test?age=18&name=john"), `{"code":0,"message":"","data":{"Id":1,"Age":18,"Name":"john"}}`)
t.Assert(client.GetContent("/test/error"), `{"code":-1,"message":"error","data":null}`)
t.Assert(client.GetContent("/test/error"), `{"code":50,"message":"error","data":null}`)
})
}