Skip to content

Commit

Permalink
Merge pull request #79 from pinguo-yangbing/master
Browse files Browse the repository at this point in the history
--cmd --help
  • Loading branch information
pinguo-yangbing authored Sep 27, 2020
2 parents 9457817 + e3ad823 commit 66aaadd
Show file tree
Hide file tree
Showing 5 changed files with 144 additions and 44 deletions.
15 changes: 8 additions & 7 deletions application.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,12 @@ import (
"github.com/pinguo/pgo2/util"
)


func init() {
_ = flag.String("env", "", "set running env (optional), eg. --env=online")
_ = flag.String("cmd", "", "set running cmd (optional), eg. --cmd=/foo/bar")
_ = flag.String("base", "", "set base path (optional), eg. --base=/base/path")
_ = flag.String("cmdList", "", "Displays a list of CMD controllers used (optional), eg. --cmdList")
// 预先声明系统参数
for _,vFlag:=range globalParams{
_ = flag.String(vFlag.Name, vFlag.DefValue, vFlag.Usage)
}
}

func NewApp() *Application {
Expand Down Expand Up @@ -115,8 +116,8 @@ func (app *Application) Arg(name string) string {
return ""
}

func (app *Application) cmdList() bool {
return app.HasArg("cmdList")
func (app *Application) help() bool {
return app.HasArg("help")
}

func (app *Application) Init(osArgs []string) {
Expand All @@ -128,7 +129,7 @@ func (app *Application) Init(osArgs []string) {
}

// overwrite running mode
if cmd, has := args["cmd"]; has && len(cmd) > 0 {
if _, has := args["cmd"]; has {
app.mode = ModeCmd
}

Expand Down
2 changes: 1 addition & 1 deletion container.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ func (c *Container) Get(name string, ctx iface.IContext, params ...interface{})
obj.SetContext(ctx)
}

// call Init()
// call Prepare()
if item.pmIdx != -1 {
if im := rv.Method(item.pmIdx); im.IsValid() {
in := make([]reflect.Value, len(params))
Expand Down
132 changes: 103 additions & 29 deletions init.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package pgo2

import (
"flag"
"fmt"
"reflect"
"regexp"
"strings"
"time"
Expand All @@ -11,27 +13,28 @@ import (
)

const (
ModeWeb = "web"
ModeCmd = "cmd"
DefaultEnv = "develop"
DefaultControllerPath = "index"
DefaultActionPath = "index"
DefaultHttpAddr = "0.0.0.0:8000"
DefaultTimeout = 30 * time.Second
DefaultHeaderBytes = 1 << 20
ControllerWebPkg = "controller"
ControllerCmdPkg = "command"
ControllerWebType = "Controller"
ControllerCmdType = "Command"
ConstructMethod = "Construct"
PrepareMethod = "Prepare"
VendorPrefix = "vendor/"
VendorLength = 7
ActionPrefix = "Action"
ActionLength = 6
TraceMaxDepth = 10
MaxPlugins = 32
MaxCacheObjects = 100
ModeWeb = "web"
ModeCmd = "cmd"
DefaultEnv = "develop"
DefaultControllerPath = "index"
DefaultActionPath = "index"
DefaultHttpAddr = "0.0.0.0:8000"
DefaultTimeout = 30 * time.Second
DefaultHeaderBytes = 1 << 20
ControllerWebPkg = "controller"
ControllerCmdPkg = "command"
ControllerWebType = "Controller"
ControllerCmdType = "Command"
ConstructMethod = "Construct"
PrepareMethod = "Prepare"
VendorPrefix = "vendor/"
VendorLength = 7
ActionPrefix = "Action"
ActionLength = 6
TraceMaxDepth = 10
MaxPlugins = 32
MaxCacheObjects = 100
ParamsFlagMethodPrefix = "ParamsFlag"
)

var (
Expand All @@ -42,6 +45,12 @@ var (
logger *logs.Logger
EmptyObject struct{}
restFulActions = map[string]int{"GET": 1, "POST": 1, "PUT": 1, "DELETE": 1, "PATCH": 1, "OPTIONS": 1, "HEAD": 1}
globalParams = map[string]*flag.Flag{
"env": {Name: "env", Usage: "set running env (optional), eg. --env=online"},
"cmd": {Name: "cmd", Usage: "set running cmd (optional), eg. --cmd=/foo/bar"},
"base": {Name: "base", Usage: "set base path (optional), eg. --base=/base/path"},
"help": {Name: "help", Usage: "Displays a list of CMD controllers used (optional), eg. --help=1"},
}
)

func App(newApp ...bool) *Application {
Expand All @@ -60,7 +69,7 @@ func Run() {
App().Router().InitHandlers()
// Check config path
if err := App().Config().CheckPath(); err != nil {
cmdList()
cmdList("")
panic(err)
}
// Listen for server or start CMD
Expand Down Expand Up @@ -105,17 +114,82 @@ func GetAlias(alias string) string {
return ""
}

func cmdList() {
func cmdList(path string) {
list := App().Router().CmdHandlers()
fmt.Println("System parameters:")
fmt.Println("set running env (requested), eg. --env=online")
fmt.Println("set running cmd (optional), eg. --cmd=/foo/bar")
fmt.Println("set base path (optional), eg. --base=/base/path")
fmt.Println("Displays a list of CMD controllers used (optional), eg. --cmdList")
fmt.Println("")

flagParams := func(global bool) string {
retStr := ""
flag.VisitAll(func(vFlag *flag.Flag) {
_, hasGP := globalParams[vFlag.Name]
if global && !hasGP {
return
}

if !global && hasGP {
return
}
s := fmt.Sprintf(" \t --%s", vFlag.Name) // Two spaces before -; see next two comments.
name, usage := flag.UnquoteUsage(vFlag)
if len(name) > 0 {
s += " " + name
}

s += " \t"
s += strings.ReplaceAll(usage, "\n", "\n \t")
isZeroValue := func(vFlag *flag.Flag, value string) bool {
// Build a zero value of the flag's Value type, and see if the
// result of calling its String method equals the value passed in.
// This works unless the Value type is itself an interface type.
typ := reflect.TypeOf(vFlag.Value)
var z reflect.Value
if typ.Kind() == reflect.Ptr {
z = reflect.New(typ.Elem())
} else {
z = reflect.Zero(typ)
}
return value == z.Interface().(flag.Value).String()
}
if !isZeroValue(vFlag, vFlag.DefValue) {
s += fmt.Sprintf(" (default %v)", vFlag.DefValue)
}
retStr += s + "\n"

})

return retStr
}

fmt.Println("Global parameters:\n " + flagParams(true))

fmt.Println("The path list:")
showParams := func(path string) string {
ctx := &Context{}
rv, _, _ := App().Router().CreateController(path, ctx)
if rv.IsZero() {
return ""
}

name := ParamsFlagMethodPrefix + ctx.ActionId()
methodV := rv.MethodByName(name)
if !methodV.IsValid() {
return ""
}
methodV.Call(nil)
return flagParams(false)
}

for uri, _ := range list {
if path != "" && path != uri {
continue
}
fmt.Println(" --cmd=" + uri)

paramsStr:= showParams(uri)
if paramsStr != "" {
fmt.Println(paramsStr)
}


}
fmt.Println("")
fmt.Println("")
Expand Down
5 changes: 3 additions & 2 deletions router.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,9 +174,9 @@ func (r *Router) firstToLower(s string) string {
}

func (r *Router) setHandler(cmdType, uri, cPath, cId, aName string, aNum int) {
uri = strings.ToLower(uri)
switch cmdType {
case ControllerWebPkg:
uri = strings.ToLower(uri)
r.webHandlers[uri] = &Handler{uri: uri, cPath: cPath, cId: cId, aName: aName, aId: aNum}
case ControllerCmdPkg:
r.cmdHandlers[uri] = &Handler{uri: uri, cPath: cPath, cId: cId, aName: aName, aId: aNum}
Expand Down Expand Up @@ -242,8 +242,9 @@ func (r *Router) Resolve(path, method string) (handler *Handler, params []string
}

func (r *Router) Handler(path string) *Handler {
path = strings.ToLower(path)

if ModeWeb == App().mode {
path = strings.ToLower(path)
if handler, ok := r.webHandlers[path]; ok {
return handler
}
Expand Down
34 changes: 29 additions & 5 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -241,17 +241,18 @@ func (s *Server) Serve() {
// add server plugins
s.addServerPlugin()

if App().cmdList() {
cmdList()
return
}

// process command request
if App().Mode() == ModeCmd {
s.ServeCMD()
return
}

//
if App().help() {
cmdList("")
return
}

// process http request
if s.httpAddr == "" && s.httpsAddr == "" {
s.httpAddr = DefaultHttpAddr
Expand Down Expand Up @@ -301,6 +302,10 @@ func (s *Server) HandleRequest(ctx iface.IContext) {
// get new controller bind to this route
rv, action, params := App().Router().CreateController(path, ctx)
if !rv.IsValid() {
if s.help(rv,action,"") {
return
}

func() {
defer func() {
if err := recover(); err != nil {
Expand All @@ -312,12 +317,19 @@ func (s *Server) HandleRequest(ctx iface.IContext) {

App().Router().ErrorController(ctx, http.StatusNotFound).(iface.IErrorController).Error(http.StatusNotFound, "route not found")
}()

return
}

if s.help(rv,action,ctx.Path()) {
return
}

actionId := ctx.ActionId()
controller := rv.Interface().(iface.IController)



// fill empty string for missing param
numIn := action.Type().NumIn()
if len(params) < numIn {
Expand Down Expand Up @@ -347,6 +359,18 @@ func (s *Server) HandleRequest(ctx iface.IContext) {
action.Call(callParams)
}

func (s *Server) help(rv, action reflect.Value,path string) bool{
if !App().help() {
return false
}

cmdList(path)

return true


}

func (s *Server) handleHttp(wg *sync.WaitGroup) {
if s.httpAddr == "" {
return
Expand Down

0 comments on commit 66aaadd

Please sign in to comment.