greq

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2024 License: AGPL-3.0 Imports: 20 Imported by: 5

README

GREQ - Simple Go Request Library

GREQ is a simple request library for go with a simple API. It is designed to be simple to use, and to (as far as possible) not require a lot of documentation. The goal when writing this was as I, for the final time, got fed up with forgetting how to do a multipart request in go and having to look it up, and started adding the request library to our go function library (gofn). As it grew in complexity, I decided to split it out into its own library.

Installation

go get github.com/clysec/greq

Documentation

You can find the full documentation at https://greq.clysec.net

Usage

Simple GET Request
package main

import (
    "fmt"
    "github.com/clysec/greq"
)

func main() {
    resp, err := greq.GetRequest("https://httpbin.org/get").
        WithHeader("Accept", "application/json").
        WithQueryParams(map[string]string{"key": "value"}).
        Execute()
    
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println(resp)
    }
}
Multipart POST
package main

import (
    "fmt"
    "github.com/clysec/greq"
)

func main() {
    file, err := os.Open("file.jpg")
    if err != nil {
        fmt.Println(err)
        return
    }

    multipart, err := greq.PostRequest("https://httpbin.org/post").
        WithHeader("Accept", "application/json").
        WithMultipartFormBody([]*greq.MultipartField{
            greq.NewMultipartField("string").WithStringValue("value"),
            grew.NewMultipartField("bytes").WithBytesValue([]byte("bytes")),
            greq.NewMultipartField("file").WithReaderValue(strings.NewReader("value")).WithFilename("file.txt").WithContentType("text/plain"),
            greq.NewMultipartField("file").WithFile(file, "file.jpg")
        }).Execute()
    if err != nil {
        fmt.Println(err)
    }
}
JSON POST
package main

import (
    "fmt"
    "github.com/clysec/greq"
)

type MyType struct {
    Key string `json:"key"`
    Value string `json:"value"`
}

func main() {
    resp, err := greq.PostRequest("https://httpbin.org/post").
        WithHeader("Accept", "application/json").
        WithJSONBody(MyType{Key: "key", Value: "value"}).
        Execute()
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println(resp)
    }
}
With Basic Auth
package main

import (
    "fmt"
    "github.com/clysec/greq"
    greqauth "github.com/clysec/greq/auth"
)

type MyType struct {
    Key string `json:"key"`
    Value string `json:"value"`
}

func main() {
    resp, err := greq.PostRequest("https://httpbin.org/post").
        WithHeader("Accept", "application/json").
        WithJSONBody(MyType{Key: "key", Value: "value"}).
        WithAuth(greqauth.BasicAuth{Username: "username", Password: "password"}).
        Execute()
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println(resp)
    }
}
With Custom HTTP Client
package main

import (
    "fmt"
    "github.com/clysec/greq"
    "net/http"
)


func main() {
    client := &http.Client{
        Timeout: time.Second * 10,
    }

    resp, err := greq.PostRequest("https://httpbin.org/post").
        WithHeader("Accept", "application/json").
        WithJSONBody(MyType{Key: "key", Value: "value"}).
        WithClient(client).
        Execute()
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println(resp)
    }
}
With Client Certificate Authentication
package main

import (
    "fmt"
    "github.com/clysec/greq"
    greqauth "github.com/clysec/greq/auth"
)

func main() {
    clientCert := greqauth.ClientCert{
        InsecureSkipVerify: true
    }.FromX509("cert.pem", "key.pem")


    resp, err := greq.GetRequest("https://httpbin.org/get").
        WithHeader("Accept", "application/json").
        WithAuth().
        Execute()
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Authorization added in v0.2.1

type Authorization interface {
	Prepare() error
	Apply(addHeaderFunc func(key, value string), setTransportFunc func(transport http.RoundTripper)) error
}

type AwsSignatureAuth added in v0.2.1

type AwsSignatureAuth struct {
	AccessKey    string
	SecretKey    string
	Region       string
	ServiceName  string
	SessionToken string
}

func (*AwsSignatureAuth) Apply added in v0.2.1

func (a *AwsSignatureAuth) Apply(addHeaderFunc func(key, value string), setTransportFunc func(transport http.RoundTripper)) error

func (*AwsSignatureAuth) Prepare added in v0.2.1

func (a *AwsSignatureAuth) Prepare() error

type BasicAuth added in v0.2.1

type BasicAuth struct {
	Username string
	Password string
}

Sets the Authorization header with a Basic Auth token

func (*BasicAuth) Apply added in v0.2.1

func (ba *BasicAuth) Apply(addHeaderFunc func(key, value string), setTransportFunc func(transport http.RoundTripper)) error

func (*BasicAuth) Prepare added in v0.2.1

func (ba *BasicAuth) Prepare() error

type BearerAuth added in v0.2.1

type BearerAuth struct {
	Token  string
	Prefix string
}

Sets the Authorization header with a Bearer Auth token The default prefix is Bearer

func (*BearerAuth) Apply added in v0.2.1

func (ha *BearerAuth) Apply(addHeaderFunc func(key, value string), setTransportFunc func(transport http.RoundTripper)) error

func (*BearerAuth) Prepare added in v0.2.1

func (ha *BearerAuth) Prepare() error

type ClientCertificateAuth added in v0.2.1

type ClientCertificateAuth struct {
	ClientCertificate  tls.Certificate
	CaCertificates     *x509.CertPool
	InsecureSkipVerify bool
}

func NewClientCertificateAuth added in v0.2.1

func NewClientCertificateAuth() *ClientCertificateAuth

func (ClientCertificateAuth) Apply added in v0.2.1

func (ca ClientCertificateAuth) Apply(addHeaderFunc func(key, value string), setTransportFunc func(transport http.RoundTripper)) error

func (*ClientCertificateAuth) FromPKCS12 added in v0.2.1

func (ca *ClientCertificateAuth) FromPKCS12(pkcs12File, password string) *ClientCertificateAuth

func (*ClientCertificateAuth) FromPKCS12Bytes added in v0.2.1

func (ca *ClientCertificateAuth) FromPKCS12Bytes(pkcs12Data []byte, password string) *ClientCertificateAuth

func (*ClientCertificateAuth) FromX509 added in v0.2.1

func (ca *ClientCertificateAuth) FromX509(certFile, keyFile string) *ClientCertificateAuth

func (*ClientCertificateAuth) FromX509Bytes added in v0.2.1

func (ca *ClientCertificateAuth) FromX509Bytes(cert, key []byte) *ClientCertificateAuth

func (ClientCertificateAuth) Prepare added in v0.2.1

func (ca ClientCertificateAuth) Prepare() error

func (*ClientCertificateAuth) WithCaCertificates added in v0.2.1

func (ca *ClientCertificateAuth) WithCaCertificates(caCertificates *x509.CertPool) *ClientCertificateAuth

func (*ClientCertificateAuth) WithInsecureSkipVerify added in v0.2.1

func (ca *ClientCertificateAuth) WithInsecureSkipVerify(insecureSkipVerify bool) *ClientCertificateAuth

type GRequest

type GRequest struct {
	Url    string
	Method Method
	// contains filtered or unexported fields
}

The HTTP Request to be made

func DeleteRequest

func DeleteRequest(url string) *GRequest

func GetRequest

func GetRequest(url string) *GRequest

func NewRequest

func NewRequest(method Method, url string) *GRequest

func PatchRequest

func PatchRequest(url string) *GRequest

func PostRequest

func PostRequest(url string) *GRequest

func PutRequest

func PutRequest(url string) *GRequest

func (*GRequest) Execute

func (g *GRequest) Execute() (*GResponse, error)

TODO: Proxy from environment TODO: Timeout(s) TODO: Redirects TODO: Force attempt HTTP/2

func (*GRequest) TlsSetNovalidate added in v0.2.1

func (g *GRequest) TlsSetNovalidate() *GRequest

Ignore TLS Certificate Errors

func (*GRequest) Validate

func (g *GRequest) Validate() error

Validate the request to ensure no errors have popped up during creation

func (*GRequest) WithAuth

func (g *GRequest) WithAuth(auth Authorization) *GRequest

// Add authentication to the request // An Authorization type can be passed to multiple requests, // which is useful in the case of Oauth2 or other token-based requests // that can re-use the same token for multiple requests

func (*GRequest) WithByteBody

func (g *GRequest) WithByteBody(body []byte) *GRequest

Add a body to the request in the form of a byte slice

func (*GRequest) WithClient

func (g *GRequest) WithClient(client *http.Client) *GRequest

Add a custom HTTP client to the request This is optional, and a HTTP client will be automatically created if one is not provided. WithClient needs to be called first, it will panic if called after any other functions that have already set or modified the client

func (*GRequest) WithHeader

func (g *GRequest) WithHeader(key string, value interface{}) *GRequest

Add a header to the request Headers are added before the body functions, meaning if you add a content-type header and then add a form body, the request header will be overridden. You can manually include a content-type header in the call to all functions that modify the header.

func (*GRequest) WithHeaders

func (g *GRequest) WithHeaders(headers map[string]interface{}) *GRequest

Add multiple headers to the request Any string-like object can be passed as a value, and it will be converted to a string automatically

func (*GRequest) WithJSONBody

func (g *GRequest) WithJSONBody(body interface{}, contentType *string) *GRequest

Add a JSON body to the request Accepts an interface{} that will be marshalled into JSON, or a string or string-like object with pre-marshalled JSON

func (*GRequest) WithMultipartFormBody

func (g *GRequest) WithMultipartFormBody(body []*MultipartField) *GRequest

Add a multipart form body to the request Accepts a list of multipart fields

func (*GRequest) WithQueryParam added in v0.2.1

func (g *GRequest) WithQueryParam(key, value string) *GRequest

func (*GRequest) WithQueryParams

func (g *GRequest) WithQueryParams(params interface{}) *GRequest

Add query parameters to the request

func (*GRequest) WithReaderBody

func (g *GRequest) WithReaderBody(body io.Reader) *GRequest

Add a body to the request in the form of a reader

func (*GRequest) WithStringBody

func (g *GRequest) WithStringBody(body string) *GRequest

Add a body to the request in the form of a string

func (*GRequest) WithUrlencodedFormBody

func (g *GRequest) WithUrlencodedFormBody(body interface{}, contentType *string) *GRequest

Add a application/x-www-form-urlencoded body Accepts the following types: - map[string]string - map[string][]string - map[string][]byte - map[string]interface{} where interface can be a string-like, numeric, string slice or boolean type - url.Values

func (*GRequest) WithXMLBody

func (g *GRequest) WithXMLBody(body interface{}, contentType *string) *GRequest

Adds an XML body to the request Accepts an interface{} that will be marshalled into XML, or a string or string-like object with pre-marshalled XML

type GResponse

type GResponse struct {
	StatusCode int
	Headers    map[string][]string
	Response   *http.Response
	// contains filtered or unexported fields
}

The HTTP Response for the request

func (*GResponse) BodyBytes

func (r *GResponse) BodyBytes() ([]byte, error)

func (*GResponse) BodyReader

func (r *GResponse) BodyReader() (*io.ReadCloser, error)

func (*GResponse) BodyString

func (r *GResponse) BodyString() (string, error)

func (*GResponse) BodyUnmarshalJson

func (r *GResponse) BodyUnmarshalJson(v interface{}) error

func (*GResponse) BodyUnmarshalXml

func (r *GResponse) BodyUnmarshalXml(v interface{}) error

func (*GResponse) Close

func (r *GResponse) Close()

type HeaderAuth added in v0.2.1

type HeaderAuth struct {
	Key   string
	Value string
}

Add an arbitrary header to the request

func (*HeaderAuth) Apply added in v0.2.1

func (ha *HeaderAuth) Apply(addHeaderFunc func(key, value string), setTransportFunc func(transport http.RoundTripper)) error

func (*HeaderAuth) Prepare added in v0.2.1

func (ha *HeaderAuth) Prepare() error

type JwtAlgorithm added in v0.2.1

type JwtAlgorithm string
const (
	HS256 JwtAlgorithm = "HS256"
	HS384 JwtAlgorithm = "HS384"
	HS512 JwtAlgorithm = "HS512"
	RS256 JwtAlgorithm = "RS256"
	RS384 JwtAlgorithm = "RS384"
	RS512 JwtAlgorithm = "RS512"
	PS256 JwtAlgorithm = "PS256"
	PS384 JwtAlgorithm = "PS384"
	PS512 JwtAlgorithm = "PS512"
	ES256 JwtAlgorithm = "ES256"
	ES384 JwtAlgorithm = "ES384"
	ES512 JwtAlgorithm = "ES512"
)

type JwtAuth added in v0.2.1

type JwtAuth struct {
	Algorithm         JwtAlgorithm           `json:"algorithm"`
	Secret            interface{}            `json:"jwtSecret"`
	Payload           jwt.Claims             `json:"payload"`
	AdditionalHeaders map[string]interface{} `json:"additionalHeaders"`

	HeaderPrefix string `json:"headerPrefix"`
	// contains filtered or unexported fields
}

func (*JwtAuth) Apply added in v0.2.1

func (ja *JwtAuth) Apply(addHeaderFunc func(key, value string), setTransportFunc func(transport http.RoundTripper)) error

func (*JwtAuth) Prepare added in v0.2.1

func (ja *JwtAuth) Prepare() error

type Method

type Method string

The HTTP Method to use for the requeswt

const (
	GET    Method = "GET"
	POST   Method = "POST"
	PUT    Method = "PUT"
	PATCH  Method = "PATCH"
	DELETE Method = "DELETE"
)

type MultipartField

type MultipartField struct {
	Key string
	// contains filtered or unexported fields
}

func MultipartFieldsFromMap

func MultipartFieldsFromMap(m map[string]interface{}) ([]*MultipartField, error)

func NewMultipartField

func NewMultipartField(key string) *MultipartField

func (*MultipartField) AddToWriter

func (m *MultipartField) AddToWriter(w *multipart.Writer) error

func (*MultipartField) WithBytesValue

func (m *MultipartField) WithBytesValue(value []byte) *MultipartField

func (*MultipartField) WithContentType

func (m *MultipartField) WithContentType(contentType string) *MultipartField

func (*MultipartField) WithFilename

func (m *MultipartField) WithFilename(filename string) *MultipartField

func (*MultipartField) WithPipe

func (m *MultipartField) WithPipe(pipe *io.PipeReader) *MultipartField

func (*MultipartField) WithReaderValue

func (m *MultipartField) WithReaderValue(value io.Reader) *MultipartField

func (*MultipartField) WithStringValue

func (m *MultipartField) WithStringValue(value string) *MultipartField

type NTLMAuth added in v0.2.1

type NTLMAuth struct {
	Username string
	Password string

	ForceHttp11        bool
	InsecureSkipVerify bool
}

func (*NTLMAuth) Apply added in v0.2.1

func (na *NTLMAuth) Apply(addHeaderFunc func(key, value string), setTransportFunc func(transport http.RoundTripper)) error

func (*NTLMAuth) Prepare added in v0.2.1

func (na *NTLMAuth) Prepare() error

type Oauth2Auth added in v0.2.1

type Oauth2Auth struct {
	AuthType Oauth2AuthType `json:"auth_type"`

	ClientID          string `json:"client_id"`
	ClientSecret      string `json:"client_secret"`
	CredentialsInBody bool   `json:"credentials_in_body"`

	RedirectURL string   `json:"redirect_url"`
	Scopes      []string `json:"scopes"`

	DiscoveryUrl string `json:"discovery_url"`

	AuthorizationUrl string `json:"authorization_url"`
	TokenUrl         string `json:"token_url"`
	UserinfoUrl      string `json:"userinfo_url"`

	AdditionalBodyFields map[string]string `json:"additional_body_fields"`
	// contains filtered or unexported fields
}

func (*Oauth2Auth) Apply added in v0.2.1

func (oa *Oauth2Auth) Apply(addHeaderFunc func(key, value string), setTransportFunc func(transport http.RoundTripper)) error

func (*Oauth2Auth) Prepare added in v0.2.1

func (oa *Oauth2Auth) Prepare() error

func (*Oauth2Auth) Token added in v0.2.1

func (oa *Oauth2Auth) Token() *Oauth2Token

func (*Oauth2Auth) TokenExpired added in v0.2.1

func (oa *Oauth2Auth) TokenExpired() bool

type Oauth2AuthType added in v0.2.1

type Oauth2AuthType string
const (
	AuthorizationCode   Oauth2AuthType = "authorization_code"
	PasswordCredentials Oauth2AuthType = "password"
	ClientCredentials   Oauth2AuthType = "client_credentials"
	DeviceCode          Oauth2AuthType = "device_code"
)

type Oauth2Token added in v0.2.1

type Oauth2Token struct {
	AccessToken  string `json:"access_token"`
	TokenType    string `json:"token_type"`
	ExpiresAt    int    `json:"expires_at"`
	RefreshToken string `json:"refresh_token"`
	Scope        string `json:"scope"`
	ExpiresIn    int    `json:"expires_in"`
}

type OidcDiscovery added in v0.2.1

type OidcDiscovery struct {
	Issuer                 string   `json:"issuer"`
	AuthorizationEndpoint  string   `json:"authorization_endpoint"`
	TokenEndpoint          string   `json:"token_endpoint"`
	UserinfoEndpoint       string   `json:"userinfo_endpoint"`
	JwksUri                string   `json:"jwks_uri"`
	RegistrationEndpoint   string   `json:"registration_endpoint"`
	IntrospectionEndpoint  string   `json:"introspection_endpoint"`
	EndSessionEndpoint     string   `json:"end_session_endpoint"`
	CheckSessionIframe     string   `json:"check_session_iframe"`
	GrantTypesSupported    []string `json:"grant_types_supported"`
	ResponseTypesSupported []string `json:"response_types_supported"`
	ClaimsSupported        []string `json:"claims_supported"`
	ScopesSupported        []string `json:"scopes_supported"`
}

func (*OidcDiscovery) IsClaimSupported added in v0.2.1

func (od *OidcDiscovery) IsClaimSupported(claim string) bool

func (*OidcDiscovery) IsGrantTypeSupported added in v0.2.1

func (od *OidcDiscovery) IsGrantTypeSupported(grantType string) bool

func (*OidcDiscovery) IsResponseTypeSupported added in v0.2.1

func (od *OidcDiscovery) IsResponseTypeSupported(responseType string) bool

func (*OidcDiscovery) IsScopeSupported added in v0.2.1

func (od *OidcDiscovery) IsScopeSupported(scope string) bool

Jump to

Keyboard shortcuts

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