httpcmd

package
v0.0.0-...-9c55465 Latest Latest
Warning

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

Go to latest
Published: Apr 10, 2024 License: MIT Imports: 29 Imported by: 0

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)
		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(),
	},
	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: 8080,
		})
	},
	Func: func(c *gcli.Command, args []string) error {

		s := httpserve.New()
		r := s.Rux()
		r.Use(handlers.PanicsHandler())

		if httpServeOpts.debug {
			r.Use(handlers.RequestLogger())
		}

		web.AddRoutes(r)

		r.Listen("127.0.0.1:18080")

		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) {
		reqOpts.BindProxyConfirm(c)

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

		c.AddArg("url", "the url to send request", true)
	},
	Func: func(c *gcli.Command, _ []string) error {
		hc := greq.New()
		hc.DefaultMethod(reqOpts.method)

		hc.BeforeSend = func(r *http.Request) {
			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))
			}
		}

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

		if reqOpts.json {
			b.JSONType()
		}
		if reqOpts.data != "" {
			b.AnyBody(reqOpts.data)
		}
		if !reqOpts.query.IsEmpty() {
			b.WithQuerySMap(reqOpts.query.Data())
		}

		reqOpts := greq.NewOpt()
		apiUrl := c.Arg("url").String()
		resp, err := hc.SendWithOpt(apiUrl, reqOpts)
		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 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 NewOAPIServeCmd

func NewOAPIServeCmd() *gcli.Command

NewOAPIServeCmd instance

Types

This section is empty.

Jump to

Keyboard shortcuts

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