gonet

package module
v0.0.0-...-67aac8e Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2023 License: MIT Imports: 22 Imported by: 14

README

gonet

Travis CI Software License GoDoc Coverage Status goreport

Declarative HTTP requests.

import "github.com/bingoohuang/gonet/man"

type poster struct {
	man.T `method:"POST"` // default method is POST

	// fixed url set in the tag
	AddAgent func(Agent) Result `url:"http://127.0.0.1:8888" timeout="10s"`
	// dynamic url as the argument
	Upload   func(man.URL, man.UploadFile, map[string]string) Result
	Download func(man.URL, *man.DownsloadFile) error
	GetAgent func(man.URL) Agent `method:"GET"`
}

var PostMan = func() (p poster) { man.New(&p); return }()

func main() {
    result := PostMan.AddAgent(agentAgent{Name: "bingoo"})
	// ...
}

net relative like port, http, rest.

  1. FreePort 获得系统当前自由TCP端口(没有被占用)

  2. Get/Post/Put/Patch/Delete HTTP 客户端调用

  3. TLS relatives HTTPS证书

    • 根密钥/根证书生成
    • 服务端密钥/服务器证书生成
    • 客户端密钥/客户端证书生成
    • 服务端TLSConfig(https,客户端证书校验)
    • 客户端TLSConfig(服务器端证书校验,传递客户端证书)
  4. ListLocalIfaceAddrs, ListLocalIps, ListLocalIPMap 列出本地IP及网卡名称

  5. ReverseProxy 反向代理

  6. IsLocalAddr 判断addr(ip,域名等)是否指向本机

Make certs

参见cert_test.sh

openssl genrsa -out root.key 2048
openssl req -new -nodes -x509 -days 3650 -key root.key -out root.pem -subj "/C=CN/ST=BEIJING/L=Earth/O=BJCA/OU=IT/CN=root"

openssl genrsa -out server.key 2048
openssl req -new -key server.key -out server.csr -subj "/C=CN/ST=BEIJING/L=Earth/O=BJCA/OU=IT/CN=server"
openssl x509 -req -in server.csr -CA root.pem -CAkey root.key -CAcreateserial -out server.pem -days 3650

openssl genrsa -out client.key 2048
openssl req -new -key client.key -subj "/C=CN/ST=BEIJING/L=Earth/O=BJCA/OU=IT/CN=client" -out client.csr
echo "[ssl_client]"> openssl.cnf; echo "extendedKeyUsage = clientAuth" >> openssl.cnf;
openssl x509 -req -in client.csr -CA root.pem -CAkey root.key -CAcreateserial -extfile ./openssl.cnf -out client.pem -days 3650

go server usage demo

import "github.com/bingoohuang/gonet/tlsconf"

// 传入服务端私钥文件,服务端证书文件,以及客户端根证书文件(可选 ,不传时不进行客户端证书校验)
tlsConf := tlsconf.CreateServer(serverKeyFile, serverPemFile, clientRootPemFile)
addr := ":8080"
ln, err := tls.Listen("tcp", addr, tlsConf)

route := gin.Default()
server := &http.Server{Addr: addr, Handler: route}
err := server.Serve(ln)

go client usage demo

import "github.com/bingoohuang/gonet/tlsconf"

// 传入客户端私钥文件,客户端证书文件,以及服务端根证书文件(可选 ,不传时不进行服务端证书校验)
tlsClientConf := tlsconf.CreateClient(c.ClientKey, c.ClientPem, c.RootPem)
gonet.MustGet("https://httpbin.org/get").TLSClientConfig(tlsClientConf).String()

具体客户端https证书使用案例,可以参见typhon4g

Thanks

  1. golang-tls
  2. urllib
  3. go-resty
  4. sling
  5. This demonstrates how to make client side certificates with go
  6. 带入gRPC:基于 CA 的 TLS 证书认证
  7. Better self-signed certificates
  8. Create a PKI in GoLang
  9. root CA and VerifyClientCert
  10. Golang的TLS证书
  11. 密钥、证书生成和管理总结
  12. TLS with Go
  13. Golang - Go与HTTPS
  14. A simple zero-config tool to make locally trusted development certificates with any names you'd like.
  15. Go 编程: 快速生成自签名证书与双向认证(mTLS)本地拷贝版本
  16. CFSSL从根证书,到业务侧证书一键生成
  17. A simple, modern and secure encryption tool with small explicit keys, no config options, and UNIX-style composability.
  18. RSA 的原理与实现
  19. sethgrid/pester Go (golang) http calls with retries and backoff
  20. pojozhang/sugar Declarative HTTP client for Golang
  21. Goji is a minimalistic and flexible HTTP request multiplexer for Go (golang)
  22. Full-featured, plugin-driven, extensible HTTP client toolkit for Go
  23. GoReplay is an open-source tool for capturing and replaying live HTTP traffic into a test environment
  24. mkcert A simple zero-config tool to make locally trusted development certificates with any names you'd like
  25. An easy HTTP client for Go. Inspired by the immortal Requests.

Documentation

Index

Constants

View Source
const ContentType = "Content-Type"

ContentType ...

Variables

This section is empty.

Functions

func BuildURL

func BuildURL(base string, queryParams map[string]string) (string, error)

BuildURL 创建一个url

func ContentTypeHTML

func ContentTypeHTML(w http.ResponseWriter)

ContentTypeHTML ...

func ContentTypeJSON

func ContentTypeJSON(w http.ResponseWriter)

ContentTypeJSON ...

func DefaultClient

func DefaultClient() *http.Client

DefaultClient returns a default client with sensible values for slow 3G connections and above.

func DetectContentType

func DetectContentType(name string) (t string)

DetectContentType ...

func DialContextTimeout

func DialContextTimeout(rwtimeout, ctimeout time.Duration) func(ctx context.Context, network, addr string) (net.Conn, error)

DialContextTimeout implements our own dialer in order to set read and write idle timeouts.

func DialerTimeout

func DialerTimeout(rwtimeout, ctimeout time.Duration) func(network, addr string) (c net.Conn, err error)

DialerTimeout implements our own dialer in order to set read and write idle timeouts.

func DumpRequest

func DumpRequest(fn http.HandlerFunc, body bool, dumper func(error, []byte)) http.HandlerFunc

DumpRequest ...

func GzipHandlerFn

func GzipHandlerFn(fn http.HandlerFunc) http.HandlerFunc

GzipHandlerFn ...

func HTTPGet

func HTTPGet(url string) ([]byte, error)

HTTPGet 表示一次HTTP的Get调用

func HasPrefix

func HasPrefix(s string, p ...string) bool

HasPrefix tells s has any prefix of p...

func IsRelativeForward

func IsRelativeForward(statusCode int, locationHeader string) bool

IsRelativeForward tells the statusCode is 301/302 and locationHeader is relative

func IsTimeoutError

func IsTimeoutError(err error) bool

IsTimeoutError tells that the err is a timeout error.

func NewCookieJar

func NewCookieJar() *cookiejar.Jar

NewCookieJar creates a cookiejar to store cookies.

func ReadBytes

func ReadBytes(object io.ReadCloser) []byte

ReadBytes ...

func ReadString

func ReadString(object io.ReadCloser) string

ReadString ...

func RestGet

func RestGet(url string, v interface{}) error

RestGet 发起一次HTTP GET调用,并且反序列化JSON到v代表的指针中。

func RestPost

func RestPost(url string, req interface{}, rsp interface{}) ([]byte, error)

RestPost 表示一次HTTP的POST调用

func ReverseProxy

func ReverseProxy(originalPath, targetHost, targetPath string, timeout time.Duration) *httputil.ReverseProxy

ReverseProxy reverse proxy originalPath to targetHost with targetPath. And the relative forwarding is rewritten.

func ServeImage

func ServeImage(imageBytes []byte, fi os.FileInfo) func(w http.ResponseWriter, r *http.Request)

ServeImage ...

Types

type DialContextFn

type DialContextFn func(ctx context.Context, network, address string) (net.Conn, error)

DialContextFn was defined to make code more readable.

type Dialer

type Dialer func(ctx context.Context, net, addr string) (c net.Conn, err error)

Dialer defines dialer function alias

func TimeoutDialer

func TimeoutDialer(cTimeout time.Duration, rwTimeout time.Duration) Dialer

TimeoutDialer returns functions of connection dialer with timeout settings for http.Transport Dial field. https://gist.github.com/c4milo/275abc6eccbfd88ad56ca7c77947883a HTTP client with support for read and write timeouts which are missing in Go's standard library.

type DialerTimeoutBean

type DialerTimeoutBean struct {
	ReadWriteTimeout time.Duration
	ConnTimeout      time.Duration
}

DialerTimeoutBean ...

func (DialerTimeoutBean) Dial

func (d DialerTimeoutBean) Dial(network, addr string) (c net.Conn, err error)

Dial ...

func (DialerTimeoutBean) DialContext

func (d DialerTimeoutBean) DialContext(ctx context.Context, network, addr string) (c net.Conn, err error)

DialContext ...

type GzipResponseWriter

type GzipResponseWriter struct {
	io.Writer
	http.ResponseWriter
}

GzipResponseWriter ...

func (GzipResponseWriter) Write

func (w GzipResponseWriter) Write(b []byte) (int, error)

Write ...

type HTTPReq

type HTTPReq struct {
	// contains filtered or unexported fields
}

HTTPReq provides more useful methods for requesting one URL than http.Request.

func Delete

func Delete(url string) (*HTTPReq, error)

Delete returns *HTTPReq with DELETE Method.

func Get

func Get(url string) (*HTTPReq, error)

Get returns *HTTPReq with GET Method.

func Head(url string) (*HTTPReq, error)

Head returns *HTTPReq with HEAD Method.

func MustDelete

func MustDelete(url string) *HTTPReq

MustDelete returns *HTTPReq with DELETE Method.

func MustGet

func MustGet(url string) *HTTPReq

MustGet returns *HTTPReq with GET Method.

func MustHead

func MustHead(url string) *HTTPReq

MustHead returns *HTTPReq with Head Method.

func MustPatch

func MustPatch(url string) *HTTPReq

MustPatch returns *HTTPReq with Patch Method.

func MustPost

func MustPost(url string) *HTTPReq

MustPost returns *HTTPReq with POST Method.

func MustPut

func MustPut(url string) *HTTPReq

MustPut returns *HTTPReq with PUT Method.

func Patch

func Patch(url string) (*HTTPReq, error)

Patch returns *HTTPReq with PATCH Method.

func Post

func Post(url string) (*HTTPReq, error)

Post returns *HTTPReq with POST Method.

func Put

func Put(url string) (*HTTPReq, error)

Put returns *HTTPReq with PUT Method.

func (*HTTPReq) BasicAuth

func (b *HTTPReq) BasicAuth(username, password string) *HTTPReq

BasicAuth sets the request's Authorization header to use HTTP Basic Authentication with the provided username and password.

func (*HTTPReq) Body

func (b *HTTPReq) Body(data interface{}) *HTTPReq

Body adds request raw body. it supports string and []byte.

func (*HTTPReq) Bytes

func (b *HTTPReq) Bytes() ([]byte, error)

Bytes returns the body []byte in response. it calls Response inner.

func (*HTTPReq) Cookie

func (b *HTTPReq) Cookie(cookie *http.Cookie) *HTTPReq

Cookie add cookie into request.

func (*HTTPReq) CookieJar

func (b *HTTPReq) CookieJar(jar *cookiejar.Jar) *HTTPReq

CookieJar sets enable/disable cookiejar

func (*HTTPReq) Debug

func (b *HTTPReq) Debug(isdebug bool) *HTTPReq

Debug sets show debug or not when executing request.

func (*HTTPReq) DumpBody

func (b *HTTPReq) DumpBody(isdump bool) *HTTPReq

DumpBody ...

func (*HTTPReq) DumpRequest

func (b *HTTPReq) DumpRequest() []byte

DumpRequest returns the DumpRequest

func (*HTTPReq) DumpRequestString

func (b *HTTPReq) DumpRequestString() string

DumpRequestString returns the DumpRequest string

func (*HTTPReq) EnableCookie

func (b *HTTPReq) EnableCookie(enable bool) *HTTPReq

EnableCookie sets enable/disable cookiejar

func (*HTTPReq) Header

func (b *HTTPReq) Header(key, value string) *HTTPReq

Header add header item string in request.

func (*HTTPReq) Host

func (b *HTTPReq) Host(host string) *HTTPReq

Host Set HOST

func (*HTTPReq) JSONBody

func (b *HTTPReq) JSONBody(obj interface{}) error

JSONBody adds request raw body encoding by JSON.

func (*HTTPReq) Param

func (b *HTTPReq) Param(key, value string) *HTTPReq

Param adds query param in to request. params build query string as ?key1=value1&key2=value2...

func (*HTTPReq) PostFile

func (b *HTTPReq) PostFile(formName, filename string) *HTTPReq

PostFile ...

func (*HTTPReq) ProtocolVersion

func (b *HTTPReq) ProtocolVersion(vers string) *HTTPReq

ProtocolVersion set the protocol version for incoming requests. Client requests always use HTTP/1.1.

func (*HTTPReq) Proxy

func (b *HTTPReq) Proxy(proxy func(*http.Request) (*url.URL, error)) *HTTPReq

Proxy set http proxy example:

func(req *http.Request) (*URL.URL, error) {
	u, _ := URL.ParseRequestURI("http://127.0.0.1:8118")
	return u, nil
}

func (*HTTPReq) ReadResponseBody

func (b *HTTPReq) ReadResponseBody(resp *http.Response) ([]byte, error)

ReadResponseBody ...

func (*HTTPReq) Response

func (b *HTTPReq) Response() (*http.Response, error)

Response executes request client gets response manually.

func (*HTTPReq) SendOut

func (b *HTTPReq) SendOut() (*http.Response, error)

SendOut ...

func (*HTTPReq) String

func (b *HTTPReq) String() (string, error)

String returns the body string in response. it calls Response inner.

func (*HTTPReq) TLSClientConfig

func (b *HTTPReq) TLSClientConfig(config *tls.Config) *HTTPReq

TLSClientConfig sets tls connection configurations if visiting https URL.

func (*HTTPReq) Timeout

func (b *HTTPReq) Timeout(connectTimeout, readWriteTimeout time.Duration) *HTTPReq

Timeout sets connect time out and read-write time out for Request.

func (*HTTPReq) ToFile

func (b *HTTPReq) ToFile(filename string) error

ToFile saves the body data in response to one file. it calls Response inner.

func (*HTTPReq) ToJSON

func (b *HTTPReq) ToJSON(v interface{}) error

ToJSON returns the map that marshals from the body bytes as json in response . it calls Response inner.

func (*HTTPReq) ToXML

func (b *HTTPReq) ToXML(v interface{}) error

ToXML returns the map that marshals from the body bytes as xml in response . it calls Response inner.

func (*HTTPReq) Transport

func (b *HTTPReq) Transport(transport http.RoundTripper) *HTTPReq

Transport set transport to

func (*HTTPReq) UserAgent

func (b *HTTPReq) UserAgent(useragent string) *HTTPReq

UserAgent sets User-Agent header field

type ReqOption

type ReqOption struct {
	ShowDebug        bool
	EnableCookie     bool
	Gzip             bool
	DumpBody         bool
	UserAgent        string
	ConnectTimeout   time.Duration
	ReadWriteTimeout time.Duration
	TLSClientConfig  *tls.Config
	CookieJar        *cookiejar.Jar
	Proxy            func(*http.Request) (*url.URL, error)
	Transport        http.RoundTripper
}

ReqOption ...

func NewReqOption

func NewReqOption() *ReqOption

NewReqOption creates a default settings

func (*ReqOption) Delete

func (s *ReqOption) Delete(url string) (*HTTPReq, error)

Delete returns *HTTPReq with DELETE Method.

func (*ReqOption) Get

func (s *ReqOption) Get(url string) (*HTTPReq, error)

Get returns *HTTPReq with GET Method.

func (*ReqOption) Head

func (s *ReqOption) Head(url string) (*HTTPReq, error)

Head returns *HTTPReq with HEAD Method.

func (*ReqOption) MustDelete

func (s *ReqOption) MustDelete(url string) *HTTPReq

MustDelete returns *HTTPReq with DELETE Method.

func (*ReqOption) MustGet

func (s *ReqOption) MustGet(url string) *HTTPReq

MustGet returns *HTTPReq with GET Method.

func (*ReqOption) MustHead

func (s *ReqOption) MustHead(url string) *HTTPReq

MustHead returns *HTTPReq with Head Method.

func (*ReqOption) MustPatch

func (s *ReqOption) MustPatch(url string) *HTTPReq

MustPatch returns *HTTPReq with Patch Method.

func (*ReqOption) MustPost

func (s *ReqOption) MustPost(url string) *HTTPReq

MustPost returns *HTTPReq with POST Method.

func (*ReqOption) MustPut

func (s *ReqOption) MustPut(url string) *HTTPReq

MustPut returns *HTTPReq with PUT Method.

func (*ReqOption) Patch

func (s *ReqOption) Patch(url string) (*HTTPReq, error)

Patch returns *HTTPReq with PATCH Method.

func (*ReqOption) Post

func (s *ReqOption) Post(url string) (*HTTPReq, error)

Post returns *HTTPReq with POST Method.

func (*ReqOption) Put

func (s *ReqOption) Put(url string) (*HTTPReq, error)

Put returns *HTTPReq with PUT Method.

func (*ReqOption) Req

func (s *ReqOption) Req(rawURL, method string) (*HTTPReq, error)

Req return *HTTPReq with specific Method

func (*ReqOption) RestGet

func (s *ReqOption) RestGet(url string, v interface{}) error

RestGet 发起一次HTTP GET调用,并且反序列化JSON到v代表的指针中。

func (*ReqOption) RestPostFn

func (s *ReqOption) RestPostFn(url string, req interface{}, rsp interface{}, fn func(*HTTPReq)) ([]byte, error)

RestPostFn ...

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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