pcurl

package module
v0.0.10 Latest Latest
Warning

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

Go to latest
Published: Apr 23, 2024 License: Apache-2.0 Imports: 10 Imported by: 6

README

pcurl

Go codecov

pcurl是解析curl表达式的库

feature

  • 支持-X; --request,作用设置GET或POST的选项
  • 支持-H; --header选项,curl中用于设置http header的选项
  • 支持-d; --data选项,作用设置http body
  • 支持--data-raw选项,curl用于设置http body
  • 支持-F --form选项,用作设置formdata
  • 支持--url选项,curl中设置url,一般不会设置这个选项
  • 支持--compressed选项
  • 支持-k, --insecure选项
  • 支持-G, --get选项
  • 支持-i, --include选项
  • 支持--data-urlencode选项
  • 支持内嵌到你的结构体里面,让你的cmd秒变curl

内容

quick start

package main

import (
    "fmt"
    "github.com/antlabs/pcurl"
    //"github.com/guonaihong/gout"
    "io"
    "io/ioutil"
    "net/http"
)

func main() {
    req, err := pcurl.ParseAndRequest(`curl -X POST -d 'hello world' www.qq.com`)
    if err != nil {
        fmt.Printf("err:%s\n", err)
        return
    }

    resp, err := http.DefaultClient.Do(req)
    n, err := io.Copy(ioutil.Discard, resp.Body)
    fmt.Println(err, "resp.size = ", n)

    /*
        resp := ""
        err = gout.New().SetRequest(req).BindBody(&resp).Do()

        fmt.Println(err, "resp.size = ", len(resp))
    */
}

json

package main

import (
    "fmt"
    "github.com/antlabs/pcurl"
    "io"
    "net/http"
    "os"
)

func main() {
    req, err := pcurl.ParseAndRequest(`curl -XPOST -d '{"hello":"world"}' 127.0.0.1:1234`)
    if err != nil {
        fmt.Printf("err:%s\n", err)
        return
    }   

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        fmt.Printf("err:%s\n", err)
        return
    }   
    defer resp.Body.Close()

    io.Copy(os.Stdout, resp.Body)
}

form data

package main

import (
    "fmt"
    "github.com/antlabs/pcurl"
    "io"
    "net/http"
    "os"
)

func main() {
    req, err := pcurl.ParseAndRequest(`curl -XPOST -F mode=A -F text='Good morning' 127.0.0.1:1234`)
    if err != nil {
        fmt.Printf("err:%s\n", err)
        return
    }   

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        fmt.Printf("err:%s\n", err)
        return
    }   
    defer resp.Body.Close()

    io.Copy(os.Stdout, resp.Body)
}

dump to json

package main

import (
    "fmt"
    "github.com/antlabs/pcurl"
    "io"
    "net/http"
    "os"
)

func main() {
    all, err := pcurl.ParseAndJSON(`curl https://api.openai.com/v1/completions -H 'Content-Type: application/json' -H 'Authorization: Bearer YOUR_API_KEY' -d '{ "model": "text-davinci-003", "prompt": "Say this is a test", "max_tokens": 7, "temperature": 0 }'`)
	fmt.Printf("%s\n", all)
/*
{
  "url": "https://api.openai.com/v1/completions",
  "encode": {
    "body": "json"
  },
  "body": {
    "max_tokens": 7,
    "model": "text-davinci-003",
    "prompt": "Say this is a test",
    "temperature": 0
  },
  "header": [
    "Content-Type: application/json",
    "Authorization: Bearer YOUR_API_KEY"
  ]
}
}
*/

dump struct

package main

import (
    "fmt"
    "github.com/antlabs/pcurl"
    "io"
    "net/http"
    "os"
)

func main() {
    all, err := pcurl.ParseAndObj(`curl https://api.openai.com/v1/completions -H 'Content-Type: application/json' -H 'Authorization: Bearer YOUR_API_KEY' -d '{ "model": "text-davinci-003", "prompt": "Say this is a test", "max_tokens": 7, "temperature": 0 }'`)

	fmt.Printf("%s\n", all)
/*
&pcurl.Req{Method:"POST", URL:"https://api.openai.com/v1/completions", Encode:pcurl.Encode{Body:"json"}, Body:map[string]interface {}{"max_tokens":7, "model":"text-davinci-003", "prompt":"Say this is a test", "temperature":0}, Header:[]string{"Content-Type: application/json", "Authorization: Bearer YOUR_API_KEY"}}
*/

继承pcurl的选项(curl)--让你的cmd秒变curl

自定义的Gen命令继续pcurl所有特性,在此基础加些自定义选项。

type Gen struct {
    //curl选项
	pcurl.Curl

    //自定义选项
	Connections string        `clop:"-c; --connections" usage:"Connections to keep open"`
	Duration    time.Duration `clop:"--duration" usage:"Duration of test"`
	Thread      int           `clop:"-t; --threads" usage:"Number of threads to use"`
	Latency     string        `clop:"--latency" usage:"Print latency statistics"`
	Timeout     time.Duration `clop:"--timeout" usage:"Socket/request timeout"`
}

func main() {
	g := &Gen{}

	clop.Bind(&g)

    // pcurl包里面提供
	req, err := g.SetClopAndRequest(clop.CommandLine)
	if err != nil {
		panic(err.Error())
	}

    // 已经拿到http.Request对象
    // 如果是标准库直接通过Do()方法发送
    // 如果是裸socket,可以通过http.DumpRequestOut先转成[]byte再发送到服务端
    fmt.Printf("%p\n", req)
}

Documentation

Overview

Copyright [2020-2021] [guonaihong] Apache 2.0

Copyright [2020-2021] [guonaihong] Apache 2.0

Copyright [2020-2021] [guonaihong] Apache 2.0

Index

Constants

View Source
const (
	EncodeWWWForm = "www-form"
	EncodeJSON    = "json"
	EncodeYAML    = "yaml"
)

Variables

View Source
var (
	ErrSingleQuotes = errors.New("unquoted single quote")
	ErrDoubleQuotes = errors.New("unquoted double quote")
	ErrUnknown      = errors.New("pcurl:GetArgsToken:unknown error")
)
View Source
var ErrUnknownEncode = errors.New("Unknown encoder")

Functions

func GetArgsToken

func GetArgsToken(curlString string) (curl []string, err error)

TODO 考虑转义 TODO 各种换行符号

func ParseAndJSON added in v0.0.8

func ParseAndJSON(curl string) (jsonBytes []byte, err error)

func ParseAndRequest

func ParseAndRequest(curl string) (*http.Request, error)

解析curl字符串形式表达式,并返回*http.Request

Types

type Curl

type Curl struct {
	Method        string   `clop:"-X; --request" usage:"Specify request command to use"`
	Get           bool     `clop:"-G; --get" usage:"Put the post data in the URL and use GET"`
	Header        []string `clop:"-H; --header" usage:"Pass custom header(s) to server"`
	Data          string   `clop:"-d; --data"   usage:"HTTP POST data"`
	DataRaw       string   `clop:"--data-raw" usage:"HTTP POST data, '@' allowed"`
	Form          []string `clop:"-F; --form" usage:"Specify multipart MIME data"`
	URL2          string   `clop:"args=url2" usage:"url2"`
	URL           string   `clop:"--url" usage:"URL to work with"`
	Location      bool     `clop:"-L; --location" usage:"Follow redirects"` //TODO
	DataUrlencode []string `clop:"--data-urlencode" usage:"HTTP POST data url encoded"`

	Compressed bool `clop:"--compressed" usage:"Request compressed response"`
	// 在响应包里面打印http header, 仅做字段赋值
	Include  bool `` /* 193-byte string literal not displayed */
	Insecure bool `clop:"-k; --insecure" usage:"Allow insecure server connections when using SSL"`
	Err      error
	// contains filtered or unexported fields
}

Curl结构体

func ParseSlice

func ParseSlice(curl []string) *Curl

ParseSlice和ParseString的区别,ParseSlice里面保存解析好的curl表达式

func ParseString

func ParseString(curl string) *Curl

ParseString是链式API结构, 如果要拿*http.Request,后接Request()即可

func (*Curl) Request

func (c *Curl) Request() (req *http.Request, err error)

func (*Curl) SetClopAndRequest added in v0.0.7

func (c *Curl) SetClopAndRequest(clop2 *clop.Clop) (*http.Request, error)

内嵌Curl结构体至cmd里面使用,让你的cmd秒变为curl

type Encode added in v0.0.8

type Encode struct {
	// x-www-form-urlencoded
	Body string `json:"body,omitempty" yaml:"body"`
}

type Req added in v0.0.8

type Req struct {
	Method string   `json:"method,omitempty" yaml:"method"`
	URL    string   `json:"url,omitempty" yaml:"url"`
	Encode Encode   `json:"encode,omitempty" yaml:"encode"`
	Body   any      `json:"body,omitempty" yaml:"body"`
	Header []string `json:"header,omitempty" yaml:"header"`
}

func ParseAndObj added in v0.0.8

func ParseAndObj(curl string) (r *Req, err error)

解析curl字符串形式表达式,并返回结构体

type Sign

type Sign int
const (
	Unused       Sign = iota
	DoubleQuotes      //双引号
	SingleQuotes      //单引号
	WordEnd
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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