httpcmd

package
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 7, 2026 License: MIT Imports: 37 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

simpleStore server

提供以下 API:

  • POST /filestore/{name}/add 新增一行记录

  • GET /filestore/{name}/list 获取所有记录

  • POST /jsonstore/{name}/add 新增一条记录

  • GET /jsonstore/{name}/list 获取所有记录

POST /filestore/{name}/add body:

{
    "name": "xxx",
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DecodeQueryCmd = &gcli.Command{
	Name:    "dec-query",
	Aliases: []string{"decq", "dq"},
	Desc:    "decode the http query string to structured data",
	Config: func(c *gcli.Command) {
		c.AddArg("query", "the http query string", true)
	},
	Func: func(c *gcli.Command, _ []string) error {
		str, err := apputil.ReadSource(c.Arg("query").String())
		if err != nil {
			return err
		}

		values, err := url.ParseQuery(str)
		if err != nil {
			return err
		}

		mp := make(map[string]any, len(values))
		for key, val := range values {
			if len(val) == 1 {
				mp[key] = val[0]
			} else {
				mp[key] = val
			}
		}

		show.AList("Decoded Query:", mp, func(opts *show.ListOption) {

		})
		return nil
	},
}

DecodeQueryCmd instance

View Source
var HttpCmd = &gcli.Command{
	Name: "http",

	Desc: "provide some useful tools commands",
	Subs: []*gcli.Command{
		HttpServeCmd,
		SendRequestCmd,
		SendTemplateCmd,
		TemplateInfoCmd,
		DecodeQueryCmd,
		NewEchoServerCmd(),
		NewFileServerCmd(),
		NewHookServerCmd(),
		NewOAPIServeCmd(),
		NewJSONServerCmd(),
		NewAccessCheckCmd(),
	},
	Config: func(c *gcli.Command) {

	},
}

HttpCmd command

View Source
var HttpServeCmd = &gcli.Command{
	Name:    "serve",
	Desc:    "start an http application serve",
	Aliases: []string{"server", "http-serve"},
	Config: func(c *gcli.Command) {

		c.StrOpt(&httpServeOpts.env, "env", "", app.EnvDev, "the application env name")
		c.BoolOpt(&httpServeOpts.debug, "debug", "", true, "the debug mode for run serve")
		c.StrOpt(&httpServeOpts.runtime, "runtime", "", "", "the runtime directory path")

		c.StrVar(&httpServeOpts.host, &gcli.CliOpt{
			Name:   "host",
			Shorts: []string{"h"},
			Desc:   "host for the start http serve",
			DefVal: "127.0.0.1",
		})
		c.IntVar(&httpServeOpts.port, &gcli.CliOpt{
			Name:   "port",
			Shorts: []string{"p"},
			Desc:   "port for the start http serve",
			DefVal: 18080,
		})
	},
	Func: func(c *gcli.Command, args []string) error {

		s := httpserve.New(httpServeOpts.debug)

		web.AddRoutes(s.Rux())

		s.Start()
		return nil
	},
}

HttpServeCmd Command

View Source
var SendRequestCmd = &gcli.Command{
	Name:    "send",
	Aliases: []string{"req", "curl"},
	Desc:    "send http request like curl, ide-http-client",
	Config: func(c *gcli.Command) {
		reqCmdOpts.BindProxyConfirm(c)

		c.BoolOpt2(&reqCmdOpts.json, "j,json", "set use json content type")
		c.StrOpt2(&reqCmdOpts.method, "method, m", "set the request method, default is GET", gflag.WithDefault("GET"))
		c.VarOpt2(&reqCmdOpts.headers, "header, H", `set custom headers, eg: "Content-Type: application/json"`)
		c.VarOpt2(&reqCmdOpts.query, "query, Q", "append set custom queries, eg: name=inhere")
		c.StrOpt2(&reqCmdOpts.data, "data, d", `set the request body data, eg: '{"name":"inhere"}'`)
		c.StrOpt2(&reqCmdOpts.url, "url", "set the request url")

		c.AddArg("url", "set the request url, same of --url")
	},
	Func: func(c *gcli.Command, _ []string) error {
		apiUrl := strutil.OrElse(reqCmdOpts.url, c.Arg("url").String())
		if apiUrl == "" {
			return c.NewErr("the request url is required")
		}

		hc := greq.New()

		hc.BeforeSend = func(r *http.Request) error {
			cliutil.Yellowln("REQUEST:")
			cliutil.Greenf("%s %s\n\n", r.Method, r.URL.String())
			if len(r.Header) > 0 {
				fmt.Println(httpreq.HeaderToString(r.Header))
			}
			if reqCmdOpts.data != "" {
				fmt.Println("\n\n", reqCmdOpts.data)
			}
			return nil
		}

		b := hc.Builder()
		b.SetHeaderMap(reqCmdOpts.headers.Data())

		if reqCmdOpts.json {
			b.JSONType()
			if strings.EqualFold(reqCmdOpts.method, http.MethodGet) {
				b.Method = http.MethodPost
			}
		}
		if reqCmdOpts.data != "" {
			b.AnyBody(reqCmdOpts.data)
		}
		if !reqCmdOpts.query.IsEmpty() {
			b.WithQuerySMap(reqCmdOpts.query.Data())
		}

		request, err := b.Build(reqCmdOpts.method, apiUrl)
		if err != nil {
			return err
		}

		resp, err := hc.SendRequest(request)
		if err != nil {
			return err
		}

		cliutil.Yellowln("RESPONSE:")
		if resp.IsEmptyBody() {
			fmt.Print(resp.String())
		} else {
			fmt.Println(resp.String())
		}
		return nil
	},
}

SendRequestCmd instance

View Source
var SendTemplateCmd = &gcli.Command{
	Name:    "tpl-send",
	Aliases: []string{"sendtpl", "send-tpl"},
	Desc:    "send http request by a template file or idea http-client file",
	Help: `
## Examples

{$fullCmd} -d gitlab --api api-build.json5 -e prod -v name=order

## use variable in template

{$fullCmd} -d gitlab --plug git,fs --api api-build.json5 -e prod -v group={{git.group}} -v repoName={{git.repo}}
`,
	Config: func(c *gcli.Command) {
		stOpts.BindCommonFlags(c)
		c.IntOpt2(&stOpts.timeout, "timeout, t", "sets the request timeout, unit: ms. default: 500")
		c.StrOpt2(&stOpts.envName, "env, e", "sets env name for run template")
		c.StrOpt2(&stOpts.envFile, "env-file", "custom sets env file for run template")
		c.StrOpt2(&stOpts.domain, "domain, d", "the domain or topic name")
		c.StrOpt2(&stOpts.hcFile, "http-file, hc-file, hcf", "the ide http client file name or path")
		c.StrOpt2(&stOpts.tplName, "tpl-name, api", "the API template name or file name")
		c.VarOpt2(&stOpts.plugins, "plugin,plug", "enable some plugins on exec request. allow:git,fs\ne.g. --plugin=plugin1,plugin2")
		c.VarOpt2(&stOpts.userVars, "vars, var, v", "custom sets some variables on request. format: `KEY=VALUE`")
		c.BoolOpt2(&stOpts.verbose, "verbose, vv", `show more info about request and response`)

	},
	Func: func(c *gcli.Command, _ []string) error {
		dc, err := app.HTpl.Domain(stOpts.domain)
		if err != nil {
			return err
		}

		t, err := dc.Lookup(stOpts.hcFile, stOpts.tplName)
		if err != nil {
			return err
		}

		var vs maputil.Data
		vs, err = dc.BuildVars(stOpts.envName, stOpts.envFile)
		if err != nil {
			return err
		}

		vs.LoadSMap(stOpts.userVars.Data())

		if len(stOpts.plugins) > 0 {
			wDir := c.WorkDir()
			names := stOpts.plugins.Strings()
			for _, name := range names {
				switch name {
				case "fs":
					vs.LoadSMap(map[string]string{
						"fs.dir":  fsutil.Name(wDir),
						"fs.path": wDir,
					})
				case "git":
					if gitw.IsGitDir(wDir) {
						lp := gitw.NewRepo(wDir)
						if ri := lp.FirstRemoteInfo(); ri != nil {
							vs.LoadSMap(map[string]string{
								"git.group":    ri.Group,
								"git.repo":     ri.Repo,
								"git.repoPath": ri.RepoPath(),
							})
						}
					}
				}
			}
		}

		t.SetTimeout(stOpts.timeout)

		if stOpts.verbose {
			show.AList("Request Options:", map[string]any{
				"timeout(ms)": t.Timeout,
			})

			if len(vs) > 0 {

				show.AList("Variables:", vs)
			} else {
				c.Infoln("Send template request without any variables")
			}

			t.BeforeSend = func(r *http.Request, b *bytes.Buffer) {
				cliutil.Yellowln("REQUEST:")
				cliutil.Greenf("%s %s\n\n", r.Method, r.URL.String())
				if len(r.Header) > 0 {
					fmt.Println(httpreq.HeaderToString(r.Header))
				}

				if b != nil && b.Len() > 0 {
					fmt.Println(b.String())
				}
			}
			t.AfterSend = func(resp *httpreq.Resp, err error) {
				if err != nil {
					return
				}

				cliutil.Yellowln("RESPONSE:")
				if resp.IsEmptyBody() {
					fmt.Print(resp.String())
				} else {
					fmt.Println(resp.String())
				}
			}
		}

		opt := httpreq.NewOpt()
		if err = t.Send(vs, dc.Header, opt); err != nil {
			return err
		}

		if !stOpts.verbose {
			fmt.Println(t.Resp.BodyString())
		}
		return nil
	},
}

SendTemplateCmd instance

View Source
var TemplateInfoCmd = &gcli.Command{
	Name: "tpl-info",

	Desc: "list or show loaded config and templates information",
	Config: func(c *gcli.Command) {
		c.BoolOpt2(&tiOpts.all, "list, all, a", "list all configured domains information")

		c.AddArg("domain", "show info for the domain config")
		c.AddArg("group", "show info for the group templates on domain")
		c.AddArg("name", "show template info on the domain.group")

	},
	Func: func(c *gcli.Command, _ []string) error {
		if tiOpts.all {
			c.Infoln("All Domains:")
			dump.NoLoc(app.HTpl.Domains)
			return nil
		}

		domain := c.Arg("domain").String()
		if len(domain) == 0 {
			return errorx.Raw("please input an domain name for show")
		}

		dc, err := app.HTpl.Domain(domain)
		if err != nil {
			return err
		}

		group := c.Arg("group").String()
		if len(group) == 0 {
			show.AList("Domain info", dc)
			return nil
		}

		ts, ok := dc.Templates(group)
		if !ok {
			return errorx.Rawf("the group %q is not fund on domain %q", group, domain)
		}

		name := c.Arg("name").String()
		if len(name) == 0 {
			c.Infoln("Group info:")
			stdio.WriteString(ts.String())
			return nil
		}

		t, err := ts.Lookup(name)
		if err != nil {
			return err
		}

		show.AList("Template info", t)
		return nil
	},
}

TemplateInfoCmd instance

Functions

func NewAccessCheckCmd

func NewAccessCheckCmd() *gcli.Command

NewAccessCheckCmd instance

实现批量的基于IP段的 http server 访问检测.

func NewEchoServerCmd

func NewEchoServerCmd() *gcli.Command

NewEchoServerCmd instance

func NewFileServerCmd

func NewFileServerCmd() *gcli.Command

NewFileServerCmd instance

func NewHookServerCmd

func NewHookServerCmd() *gcli.Command

NewHookServerCmd new command

func NewJSONServerCmd

func NewJSONServerCmd() *gcli.Command

NewJSONServerCmd instance

func NewOAPIServeCmd

func NewOAPIServeCmd() *gcli.Command

NewOAPIServeCmd instance

func NewSimpleStoreCmd

func NewSimpleStoreCmd() *gcli.Command

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL