lowhttp

package
v1.3.5-beta4 Latest Latest
Warning

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

Go to latest
Published: Aug 8, 2024 License: AGPL-3.0 Imports: 64 Imported by: 4

Documentation

Overview

Ref: https://github.com/gobwas/ws

The MIT License (MIT)

Copyright (c) 2017-2021 Sergey Kamardin <gobwas@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Ref: https://github.com/nhooyr/websocket/

Copyright (c) 2023 Anmol Sethi <hi@nhooyr.io>

Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

Index

Constants

View Source
const (
	CRLF       = "\r\n"
	DoubleCRLF = "\r\n\r\n"
)
View Source
const (
	FINALBIT               = 1 << 7
	RSV1BIT                = 1 << 6
	RSV2BIT                = 1 << 5
	RSV3BIT                = 1 << 4
	MASKBIT                = 1 << 7
	UNRSV1BIT              = 0b10111111
	RESET_MESSAGE_TYPE_BIT = 0b11110000
	FRAME_TYPE_BIT         = 0b00001111
	TWO_BYTE_BIT           = 0b01111110
	EIGHT_BYTE_BIT         = 0b01111111

	TWO_BYTE_SIZE  = 65535
	SEVEN_BIT_SIZE = 125 // 根据websocket协议,126和127分别代表用后续两个字节/八个字节表示长度,所以这里只能用125

	DEFAULT_TEXT_MESSAGE_FISRT_BYTE = 0b10000001

	DEFAULT_CLOSE_MESSAGE_FIRST_BYTE = 0b10001000

	TextMessage     = 1
	BinaryMessage   = 2
	CloseMessage    = 8
	PingMessage     = 9
	PongMessage     = 10
	ContinueMessage = 0
)
View Source
const (
	CloseNormalClosure           = 1000
	CloseGoingAway               = 1001
	CloseProtocolError           = 1002
	CloseUnsupportedData         = 1003
	CloseNoStatusReceived        = 1005
	CloseAbnormalClosure         = 1006
	CloseInvalidFramePayloadData = 1007
	ClosePolicyViolation         = 1008
	CloseMessageTooBig           = 1009
	CloseMandatoryExtension      = 1010
	CloseInternalServerErr       = 1011
	CloseServiceRestart          = 1012
	CloseTryAgainLater           = 1013
	CloseTLSHandshake            = 1015
)

Close codes defined in RFC 6455, section 11.7.

View Source
const CookieTimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"

CookieTimeFormat is the time format to use when generating times in HTTP headers. It is like time.RFC1123 but hard-codes GMT as the time zone. The time being formatted must be in UTC for Format to generate the correct format.

For parsing this time format, see ParseTime.

Variables

View Source
var (
	H2 = "h2"
	H1 = "http/1.1"
)
View Source
var (
	ReadHTTPRequestFromBytes        = utils.ReadHTTPRequestFromBytes
	ReadHTTPRequestFromBufioReader  = utils.ReadHTTPRequestFromBufioReader
	ReadHTTPResponseFromBytes       = utils.ReadHTTPResponseFromBytes
	ReadHTTPResponseFromBufioReader = utils.ReadHTTPResponseFromBufioReader
)
View Source
var CookiejarPool sync.Map
View Source
var (
	DefaultLowHttpConnPool = &LowHttpConnPool{
		maxIdleConn:        100,
		maxIdleConnPerHost: 2,
		connCount:          0,
		idleConnTimeout:    90 * time.Second,
		idleConn:           make(map[string][]*persistConn),
		keepAliveTimeout:   30 * time.Second,
	}
)

Functions

func AddConnectionClosed

func AddConnectionClosed(raw []byte) []byte

func AddOrUpgradeCookie

func AddOrUpgradeCookie(raw []byte, value string) ([]byte, error)

func AppendAllHTTPPacketQueryParam added in v1.3.0

func AppendAllHTTPPacketQueryParam(packet []byte, Params map[string][]string) []byte

func AppendHTTPPacketCookie added in v1.2.3

func AppendHTTPPacketCookie(packet []byte, key string, value any) []byte

AppendHTTPPacketCookie 是一个辅助函数,用于改变请求报文,添加Cookie请求头中的值 Example: ``` poc.AppendHTTPPacketCookie(poc.BasicRequest(), "aaa", "bbb") // 添加cookie键值对aaa:bbb ```

func AppendHTTPPacketFormEncoded added in v1.2.4

func AppendHTTPPacketFormEncoded(packet []byte, key, value string) []byte

AppendHTTPPacketFormEncoded 是一个辅助函数,用于改变请求报文,添加请求体中的表单 Example: ``` poc.AppendHTTPPacketFormEncoded(`POST /post HTTP/1.1 Host: pie.dev Content-Type: multipart/form-data; boundary=------------------------OFHnlKtUimimGcXvRSxgCZlIMAyDkuqsxeppbIFm Content-Length: 203

--------------------------OFHnlKtUimimGcXvRSxgCZlIMAyDkuqsxeppbIFm Content-Disposition: form-data; name="aaa"

bbb --------------------------OFHnlKtUimimGcXvRSxgCZlIMAyDkuqsxeppbIFm--`, "ccc", "ddd") // 添加POST请求表单,其中ccc为键,ddd为值 ```

func AppendHTTPPacketHeader added in v1.2.3

func AppendHTTPPacketHeader(packet []byte, headerKey string, headerValue any) []byte

AppendHTTPPacketHeader 是一个辅助函数,用于改变请求报文,添加请求头 Example: ``` poc.AppendHTTPPacketHeader(poc.BasicRequest(), "AAA", "BBB") // 添加AAA请求头的值为BBB ```

func AppendHTTPPacketHeaderIfNotExist added in v1.3.0

func AppendHTTPPacketHeaderIfNotExist(packet []byte, headerKey string, headerValue any) []byte

func AppendHTTPPacketPath added in v1.2.3

func AppendHTTPPacketPath(packet []byte, p string) []byte

AppendHTTPPacketPath 是一个辅助函数,用于改变请求报文,在现有请求路径后添加请求路径 Example: ``` poc.AppendHTTPPacketPath(`GET /docs HTTP/1.1 Host: yaklang.com `, "/api/poc")) // 向 example.com 发起请求,实际上请求路径改为/docs/api/poc ```

func AppendHTTPPacketPostParam added in v1.2.3

func AppendHTTPPacketPostParam(packet []byte, key, value string) []byte

AppendHTTPPacketPostParam 是一个辅助函数,用于改变请求报文,添加POST请求参数 Example: ``` poc.AppendHTTPPacketPostParam(poc.BasicRequest(), "a", "b") // 向 pie.dev 发起请求,添加POST请求参数a,值为b ```

func AppendHTTPPacketQueryParam added in v1.2.3

func AppendHTTPPacketQueryParam(packet []byte, key, value string) []byte

AppendHTTPPacketQueryParam 是一个辅助函数,用于改变请求报文,添加GET请求参数 Example: ``` poc.AppendHTTPPacketQueryParam(poc.BasicRequest(), "a", "b") // 添加GET请求参数a,值为b ```

func AppendHTTPPacketUploadFile added in v1.2.4

func AppendHTTPPacketUploadFile(packet []byte, fieldName, fileName string, fileContent interface{}, contentType ...string) []byte

AppendHTTPPacketUploadFile 是一个辅助函数,用于改变请求报文,添加请求体中的上传的文件,其中第一个参数为原始请求报文,第二个参数为表单名,第三个参数为文件名,第四个参数为文件内容,第五个参数是可选参数,为文件类型(Content-Type) Example: ``` _, raw, _ = poc.ParseUrlToHTTPRequestRaw("POST", "https://pie.dev/post") poc.AppendHTTPPacketUploadFile(raw, "file", "phpinfo.php", "<?php phpinfo(); ?>", "image/jpeg")) // 添加POST请求表单,其文件名为phpinfo.php,内容为<?php phpinfo(); ?>,文件类型为image/jpeg ```

func AppendHeaderToHTTPPacket

func AppendHeaderToHTTPPacket(raw []byte, line string) []byte

func BasicRequest added in v1.2.7

func BasicRequest() []byte

BasicRequest 返回一个基本的 HTTP 请求,用于测试,它实际上返回一个b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n" Example: ``` poc.BasicRequest() // b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n" ```

func BasicResponse added in v1.3.0

func BasicResponse() []byte

BasicResponse 返回一个基本的 HTTP 响应,用于测试,它实际上返回一个b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n" Example: ``` poc.BasicResponse() // b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n" ```

func BuildLegacyProxyRequest added in v1.2.8

func BuildLegacyProxyRequest(req []byte) ([]byte, error)

func ComputeWebsocketAcceptKey

func ComputeWebsocketAcceptKey(websocketKey string) string

func ContentEncodingDecode

func ContentEncodingDecode(contentEncoding string, bodyRaw []byte) (finalResult []byte, fixed bool)

func ConvertHTTPRequestToFuzzTag

func ConvertHTTPRequestToFuzzTag(i []byte) []byte

func CookieSafeFriendly added in v1.3.3

func CookieSafeFriendly(vs string) string

CookieSafeFriendly 友好显示

func CookieSafeQuoteString added in v1.2.2

func CookieSafeQuoteString(i string) string

func CookieSafeString added in v1.3.3

func CookieSafeString(i string) string

CookieSafeString disableAutoEncode 的模式下,不会对 cookie 进行自动编码 但是对于不允许的字符,会编码

func CookieSafeUnquoteString added in v1.2.2

func CookieSafeUnquoteString(i string) string

func CookieToNative added in v1.3.3

func CookieToNative(cookies []*http.Cookie) string

func CookiesToRaw added in v1.3.3

func CookiesToRaw(cookies []*http.Cookie) string

func CookiesToString

func CookiesToString(cookies []*http.Cookie) string

func CopyRequest

func CopyRequest(r *http.Request) *http.Request

func CurlToHTTPRequest

func CurlToHTTPRequest(i string) ([]byte, error)

func DebugEchoServer added in v1.2.3

func DebugEchoServer() (string, int)

func DebugEchoServerContext added in v1.2.3

func DebugEchoServerContext(ctx context.Context) (string, int)

func DeleteHTTPPacketCookie added in v1.2.3

func DeleteHTTPPacketCookie(packet []byte, key string) []byte

DeleteHTTPPacketCookie 是一个辅助函数,用于改变请求报文,删除Cookie中的值 Example: ``` poc.DeleteHTTPPacketCookie(`GET /get HTTP/1.1 Content-Type: application/json Cookie: aaa=bbb; ccc=ddd Host: pie.dev

`, "aaa") // 删除Cookie中的aaa ```

func DeleteHTTPPacketForm added in v1.2.4

func DeleteHTTPPacketForm(packet []byte, key string) []byte

DeleteHTTPPacketForm 是一个辅助函数,用于改变请求报文,删除POST请求表单 Example: ``` poc.DeleteHTTPPacketForm(`POST /post HTTP/1.1 Host: pie.dev Content-Type: multipart/form-data; boundary=------------------------OFHnlKtUimimGcXvRSxgCZlIMAyDkuqsxeppbIFm Content-Length: 308

--------------------------OFHnlKtUimimGcXvRSxgCZlIMAyDkuqsxeppbIFm Content-Disposition: form-data; name="aaa"

bbb --------------------------OFHnlKtUimimGcXvRSxgCZlIMAyDkuqsxeppbIFm Content-Disposition: form-data; name="ccc"

ddd --------------------------OFHnlKtUimimGcXvRSxgCZlIMAyDkuqsxeppbIFm--`, "aaa") // 删除POST请求表单aaa ```

func DeleteHTTPPacketHeader added in v1.2.3

func DeleteHTTPPacketHeader(packet []byte, headerKey string) []byte

DeleteHTTPPacketHeader 是一个辅助函数,用于改变请求报文,删除请求头 Example: ``` poc.DeleteHTTPPacketHeader(`GET /get HTTP/1.1 Content-Type: application/json AAA: BBB Host: pie.dev

`, "AAA") // 删除AAA请求头 ```

func DeleteHTTPPacketPostParam added in v1.2.3

func DeleteHTTPPacketPostParam(packet []byte, key string) []byte

DeleteHTTPPacketPostParam 是一个辅助函数,用于改变请求报文,删除POST请求参数 Example: ``` poc.DeleteHTTPPacketPostParam(`POST /post HTTP/1.1 Content-Type: application/json Content-Length: 7 Host: pie.dev

a=b&c=d`, "a") // 删除POST请求参数a ```

func DeleteHTTPPacketQueryParam added in v1.2.3

func DeleteHTTPPacketQueryParam(packet []byte, key string) []byte

DeleteHTTPPacketQueryParam 是一个辅助函数,用于改变请求报文,删除GET请求参数 Example: ``` poc.DeleteHTTPPacketQueryParam(`GET /get?a=b&c=d HTTP/1.1 Content-Type: application/json Host: pie.dev

`, "a") // 删除GET请求参数a ```

func DeletePacketEncoding added in v1.2.5

func DeletePacketEncoding(raw []byte) []byte

func ExtractBodyFromHTTPResponseRaw

func ExtractBodyFromHTTPResponseRaw(res []byte) ([]byte, error)

ExtractBodyFromHTTPResponseRaw 从原始 HTTP 响应报文中提取 body Example: ``` body, err = str.ExtractBodyFromHTTPResponseRaw(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok") // body = b"ok" ```

func ExtractBoundaryFromBody

func ExtractBoundaryFromBody(raw interface{}) string

func ExtractCookieJarFromHTTPResponse

func ExtractCookieJarFromHTTPResponse(rawResponse []byte) []*http.Cookie

func ExtractStatusCodeFromResponse

func ExtractStatusCodeFromResponse(raw []byte) int

func ExtractURLFromHTTPRequest

func ExtractURLFromHTTPRequest(r *http.Request, https bool) (*url.URL, error)

ExtractURLFromHTTPRequest 从 HTTP 请求结构体中提取 URL,返回URL结构体与错误 Example: ``` v, err = http.Raw("GET / HTTP/1.1\r\nHost: www.yaklang.com\r\n\r\n") url, err = str.ExtractURLFromHTTPRequest(v, false) ```

func ExtractURLFromHTTPRequestRaw

func ExtractURLFromHTTPRequestRaw(req []byte, isHttps bool) (*url.URL, error)

ExtractURLFromHTTPRequestRaw 从原始 HTTP 请求报文中提取 URL,返回URL结构体与错误 Example: ``` url, err := str.ExtractURLFromHTTPRequestRaw(b"GET / HTTP/1.1\r\nHost: www.yaklang.com\r\n\r\n", false) ```

func ExtractURLStringFromHTTPRequest added in v1.3.1

func ExtractURLStringFromHTTPRequest(req any, isHttps bool) (string, error)

ExtractURLStringFromHTTPRequestRaw parse url string

func ExtractWebsocketURLFromHTTPRequest

func ExtractWebsocketURLFromHTTPRequest(req *http.Request) (bool, string)

func FixHTTPPacketCRLF

func FixHTTPPacketCRLF(raw []byte, noFixLength bool) []byte

FixHTTPPacketCRLF 修复一个HTTP报文的CRLF问题(正常的报文每行末尾为\r\n,但是某些报文可能是有\n),如果noFixLength为true,则不会修复Content-Length,否则会尝试修复Content-Length Example: ``` poc.FixHTTPPacketCRLF(`POST / HTTP/1.1 Host: example.com Content-Length: 11

hello world`, false) ```

func FixHTTPRequest added in v1.2.6

func FixHTTPRequest(raw []byte) []byte

FixHTTPRequest 尝试对传入的HTTP请求报文进行修复,并返回修复后的请求 Example: ``` str.FixHTTPRequest(b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n") ```

func FixHTTPResponse

func FixHTTPResponse(raw []byte) (rsp []byte, body []byte, _ error)

FixHTTPResponse 尝试对传入的响应进行修复,并返回修复后的响应,响应体和错误 Example: ``` fixedResponse, body, err = str.FixHTTPResponse(b"HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=gbk\r\n\r\n<html>你好</html>") ```

func FixMultipartBody

func FixMultipartBody(i []byte) (boundary string, fixedBody []byte)

func FixMultipartBodyLegacy added in v1.3.3

func FixMultipartBodyLegacy(i []byte) (string, []byte)

状态机

func FixRequestHostAndPort added in v1.2.3

func FixRequestHostAndPort(r *http.Request)

func FixURLScheme

func FixURLScheme(u string) string

func ForceStringToUrl added in v1.2.8

func ForceStringToUrl(i string) *url.URL

func GetAllHTTPRequestPostParams added in v1.2.3

func GetAllHTTPRequestPostParams(packet []byte) (params map[string]string)

GetAllHTTPPacketPostParams 是一个辅助函数,用于获取请求报文中的所有POST请求参数,其返回值为map[string]string,其中键为参数名,值为参数值 Example: ``` poc.GetAllHTTPPacketPostParams(`POST /post HTTP/1.1 Content-Type: application/json COntent-Length: 7 Host: pie.dev

a=b&c=d`) // 获取所有POST请求参数 ```

func GetAllHTTPRequestQueryParams added in v1.2.3

func GetAllHTTPRequestQueryParams(packet []byte) (params map[string]string)

GetAllHTTPPacketQueryParams 是一个辅助函数,用于获取请求报文中的所有GET请求参数,其返回值为map[string]string,其中键为参数名,值为参数值 Example: ``` poc.GetAllHTTPPacketQueryParams(`GET /get?a=b&c=d HTTP/1.1 Content-Type: application/json Host: pie.dev

`) // 获取所有GET请求参数 ```

func GetClosePayloadFromCloseCode

func GetClosePayloadFromCloseCode(closeCode int) []byte

func GetCookiejar

func GetCookiejar(session interface{}) http.CookieJar

func GetDigestAuthorizationFromRequest added in v1.2.8

func GetDigestAuthorizationFromRequest(raw []byte, authorization, username, password string) (string, error)

func GetDigestAuthorizationFromRequestEx added in v1.2.8

func GetDigestAuthorizationFromRequestEx(method, url, body, authorization, username, password string, useCompleteURL bool) (*DigestRequest, *DigestAuthorization, error)

func GetFullHTTPRequestPostParams added in v1.3.3

func GetFullHTTPRequestPostParams(packet []byte) (params map[string][]string)

func GetFullHTTPRequestQueryParams added in v1.3.3

func GetFullHTTPRequestQueryParams(packet []byte) (params map[string][]string)

func GetHTTPPacketBody added in v1.2.3

func GetHTTPPacketBody(packet []byte) (body []byte)

GetHTTPPacketBody 是一个辅助函数,用于获取请求报文中的请求体,其返回值为bytes Example: ``` poc.GetHTTPPacketBody(`POST /post HTTP/1.1 Content-Type: application/json COntent-Length: 7 Host: pie.dev

a=b&c=d`) // 获取请求头,这里为b"a=b&c=d" ```

func GetHTTPPacketContentType added in v1.2.3

func GetHTTPPacketContentType(packet []byte) (contentType string)

GetHTTPPacketContentType 是一个辅助函数,用于获取请求报文中的Content-Type请求头,其返回值为string Example: ``` poc.GetHTTPPacketContentType(`POST /post HTTP/1.1 Content-Type: application/json COntent-Length: 7 Host: pie.dev

a=b&c=d`) // 获取Content-Type请求头 ```

func GetHTTPPacketCookie added in v1.2.3

func GetHTTPPacketCookie(packet []byte, key string) (cookieValue string)

GetHTTPPacketCookie 是一个辅助函数,用于获取请求报文中Cookie值,其返回值为string Example: ``` poc.GetHTTPPacketCookie(`GET /get HTTP/1.1 Content-Type: application/json Cookie: a=b; c=d Host: pie.dev

`, "a") // 获取键名为a的Cookie值,这里会返回"b" ```

func GetHTTPPacketCookieFirst added in v1.2.3

func GetHTTPPacketCookieFirst(packet []byte, key string) (cookieValue string)

GetHTTPPacketCookieFirst 是一个辅助函数,用于获取请求报文中Cookie值,其返回值为string Example: ``` poc.GetHTTPPacketCookieFirst(`GET /get HTTP/1.1 Content-Type: application/json Cookie: a=b; c=d Host: pie.dev

`, "a") // 获取键名为a的Cookie值,这里会返回"b" ```

func GetHTTPPacketCookieValues added in v1.2.3

func GetHTTPPacketCookieValues(packet []byte, key string) (cookieValues []string)

GetHTTPPacketCookieValues 是一个辅助函数,用于获取请求报文中Cookie值,其返回值为[]string,这是因为Cookie可能存在多个相同键名的值 Example: ``` poc.GetHTTPPacketCookieValues(`GET /get HTTP/1.1 Content-Type: application/json Cookie: a=b; a=c Host: pie.dev

`, "a") // 获取键名为a的Cookie值,这里会返回["b", "c"] ```

func GetHTTPPacketCookies added in v1.2.3

func GetHTTPPacketCookies(packet []byte) (cookies map[string]string)

GetHTTPPacketCookies 是一个辅助函数,用于获取请求报文中所有Cookie值,其返回值为map[string]string Example: ``` poc.GetHTTPPacketCookies(`GET /get HTTP/1.1 Content-Type: application/json Cookie: a=b; c=d Host: pie.dev

`) // 获取所有Cookie值,这里会返回{"a":"b", "c":"d"} ```

func GetHTTPPacketCookiesFull added in v1.2.3

func GetHTTPPacketCookiesFull(packet []byte) (cookies map[string][]string)

GetHTTPPacketCookiesFull 是一个辅助函数,用于获取请求报文中所有Cookie值,其返回值为map[string][]string,这是因为Cookie可能存在多个相同键名的值 Example: ``` poc.GetHTTPPacketCookiesFull(`GET /get HTTP/1.1 Content-Type: application/json Cookie: a=b; a=c; c=d Host: pie.dev

`) // 获取所有Cookie值,这里会返回{"a":["b", "c"], "c":["d"]} ```

func GetHTTPPacketFirstLine added in v1.2.4

func GetHTTPPacketFirstLine(packet []byte) (string, string, string)

GetHTTPPacketFirstLine 是一个辅助函数,用于获取 HTTP 报文中第一行的值,其返回值为string,string,string 在请求报文中,其三个返回值分别为:请求方法,请求URI,协议版本 在响应报文中,其三个返回值分别为:协议版本,状态码,状态码描述 Example: ``` poc.GetHTTPPacketFirstLine(`GET /get HTTP/1.1 Content-Type: application/json Cookie: a=b; a=c; c=d Host: pie.dev

`) // 获取请求方法,请求URI,协议版本,这里会返回"GET", "/get", "HTTP/1.1" ```

func GetHTTPPacketHeader added in v1.2.3

func GetHTTPPacketHeader(packet []byte, key string) (header string)

GetHTTPPacketHeader 是一个辅助函数,用于获取请求报文中指定的请求头,其返回值为string Example: ``` poc.GetHTTPPacketHeader(`GET /get HTTP/1.1 Content-Type: application/json Cookie: a=b; a=c; c=d Host: pie.dev

`, "Content-Type") // 获取Content-Type请求头,这里会返回"application/json" ```

func GetHTTPPacketHeaders added in v1.2.3

func GetHTTPPacketHeaders(packet []byte) (headers map[string]string)

GetHTTPPacketHeaders 是一个辅助函数,用于获取请求报文中所有请求头,其返回值为map[string]string Example: ``` poc.GetHTTPPacketHeaders(`GET /get HTTP/1.1 Content-Type: application/json Cookie: a=b; a=c; c=d Host: pie.dev

`) // 获取所有请求头,这里会返回{"Content-Type": "application/json", "Cookie": "a=b; a=c; c=d", "Host": "pie.dev"} ```

func GetHTTPPacketHeadersFull added in v1.2.3

func GetHTTPPacketHeadersFull(packet []byte) (headers map[string][]string)

GetHTTPPacketHeadersFull 是一个辅助函数,用于获取请求报文中所有请求头,其返回值为map[string][]string,这是因为请求头可能存在多个相同键名的值 Example: ``` poc.GetHTTPPacketHeadersFull(`GET /get HTTP/1.1 Content-Type: application/json Cookie: a=b; a=c; c=d Cookie: e=f Host: pie.dev

`) // 获取所有请求头,这里会返回{"Content-Type": ["application/json"], "Cookie": []"a=b; a=c; c=d", "e=f"], "Host": ["pie.dev"]} ```

func GetHTTPPacketJSONPath added in v1.2.3

func GetHTTPPacketJSONPath(packet []byte, key string) any

func GetHTTPPacketJSONValue added in v1.2.3

func GetHTTPPacketJSONValue(packet []byte, key string) any

func GetHTTPRequestMethod added in v1.2.9

func GetHTTPRequestMethod(packet []byte) (method string)

GetHTTPRequestMethod 是一个辅助函数,用于获取请求报文中的请求方法,其返回值为string Example: ``` poc.GetHTTPRequestMethod(`GET /get HTTP/1.1 Content-Type: application/json Cookie: a=b; a=c; c=d Host: pie.dev

`) // 获取请求方法,这里会返回"GET" ```

func GetHTTPRequestPath added in v1.2.9

func GetHTTPRequestPath(packet []byte) (path string)

GetHTTPRequestPath 是一个辅助函数,用于获取响应报文中的路径,返回值是 string,包含 query Example: ``` poc.GetHTTPRequestPath("GET /a/bc.html?a=1 HTTP/1.1\r\nHost: www.example.com\r\n\r\n") // /a/bc.html?a=1 ```

func GetHTTPRequestPathWithoutQuery added in v1.2.9

func GetHTTPRequestPathWithoutQuery(packet []byte) (path string)

GetHTTPRequestPathWithoutQuery 是一个辅助函数,用于获取响应报文中的路径,返回值是 string,不包含 query Example: ``` poc.GetHTTPRequestPathWithoutQuery("GET /a/bc.html?a=1 HTTP/1.1\r\nHost: www.example.com\r\n\r\n") // /a/bc.html ```

func GetHTTPRequestPostParam added in v1.2.3

func GetHTTPRequestPostParam(packet []byte, key string) (paramValue string)

GetHTTPPacketPostParam 是一个辅助函数,用于获取请求报文中指定的POST请求参数,其返回值为string Example: ``` poc.GetHTTPPacketPostParam(`POST /post HTTP/1.1 Content-Type: application/json COntent-Length: 7 Host: pie.dev

a=b&c=d`, "a") // 获取POST请求参数a的值 ```

func GetHTTPRequestPostParamFull added in v1.2.3

func GetHTTPRequestPostParamFull(packet []byte, key string) []string

func GetHTTPRequestQueryParam added in v1.2.3

func GetHTTPRequestQueryParam(packet []byte, key string) (paramValue string)

GetHTTPPacketQueryParam 是一个辅助函数,用于获取请求报文中指定的GET请求参数,其返回值为string Example: ``` poc.GetHTTPPacketQueryParam(`GET /get?a=b&c=d HTTP/1.1 Content-Type: application/json Host: pie.dev

`, "a") // 获取GET请求参数a的值 ```

func GetHTTPRequestQueryParamFull added in v1.2.3

func GetHTTPRequestQueryParamFull(packet []byte, key string) (ret []string)

func GetHostsFilePath

func GetHostsFilePath() string

func GetParamsFromBody added in v1.3.0

func GetParamsFromBody(contentType string, body []byte) (params map[string][]string, useRaw bool, err error)

func GetRedirectFromHTTPResponse

func GetRedirectFromHTTPResponse(rawResponse []byte, jsRedirect bool) (result string)

func GetStatusCodeFromResponse added in v1.2.3

func GetStatusCodeFromResponse(packet []byte) (statusCode int)

GetStatusCodeFromResponse 是一个辅助函数,用于获取响应报文中的状态码,其返回值为int Example: ``` poc.GetStatusCodeFromResponse(`HTTP/1.1 200 OK Content-Length: 5

hello`) // 获取响应报文中的状态码,这里会返回200 ```

func GetSystemEtcHosts

func GetSystemEtcHosts() map[string]string

func GetSystemHostByName

func GetSystemHostByName(domain string) (string, bool)

func GetUrlFromHTTPRequest added in v1.2.9

func GetUrlFromHTTPRequest(scheme string, packet []byte) (url string)

GetUrlFromHTTPRequest 是一个辅助函数,用于获取请求报文中的URL,其返回值为string Example: ``` poc.GetUrlFromHTTPRequest("https", `GET /get HTTP/1.1 Content-Type: application/json Host: pie.dev

`) // 获取URL,这里会返回"https://pie.dev/get" ```

func HTTP2RequestToHTTP

func HTTP2RequestToHTTP(framer *http2.Framer) ([]byte, error)

func HTTP2ResponseToHTTP

func HTTP2ResponseToHTTP(frame *http2.Frame) ([]byte, error)

func HTTPPacketForceChunked

func HTTPPacketForceChunked(raw []byte) []byte

HTTPPacketForceChunked 将一个HTTP报文的body强制转换为chunked编码 Example: ``` poc.HTTPPacketForceChunked(`POST / HTTP/1.1 Host: example.com Content-Length: 11

hello world`) ```

func HTTPRequestToHTTP2

func HTTPRequestToHTTP2(schema string, host string, conn net.Conn, raw []byte, noFixContentLength bool) ([]byte, error)

func IGetHTTPInsHeader added in v1.3.0

func IGetHTTPInsHeader(headers http.Header, headerKey string) []string

func IGetHeader added in v1.3.0

func IGetHeader(packet interface{}, headerKey string) []string

func IsChunkedHeaderLine added in v1.2.3

func IsChunkedHeaderLine(line string) bool

func IsControlMessage

func IsControlMessage(opcode int) bool

func IsHeader added in v1.2.4

func IsHeader(headerLine, wantHeader string) bool

func IsHtmlOrXmlMIMEType

func IsHtmlOrXmlMIMEType(s string) bool

func IsJavaScriptMIMEType

func IsJavaScriptMIMEType(s string) bool

func IsJsonMIMEType

func IsJsonMIMEType(s string) bool

func IsMultipartFormDataRequest

func IsMultipartFormDataRequest(req []byte) bool

func IsPrint

func IsPrint(s string) bool

func IsResp added in v1.2.4

func IsResp(raw any) (isHTTPResponse bool)

IsResp 判断传入的数据是否为 HTTP 响应报文 Example: ``` poc.IsResp(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok") // true ```

func IsRespFast added in v1.3.2

func IsRespFast(raw any) (isHTTPResponse bool)

func IsTextPlainMIMEType

func IsTextPlainMIMEType(s string) bool

func IsValidUTF8WithRemind

func IsValidUTF8WithRemind(p []byte) (valid bool, remindSize int)

func MergeCookies

func MergeCookies(cookies ...*http.Cookie) string

func MergeUrlFromHTTPRequest

func MergeUrlFromHTTPRequest(rawRequest []byte, target string, isHttps bool) (newURL string)

MergeUrlFromHTTPRequest 将传入的 target 与 原始 HTTP 请求报文中的 URL 进行合并,并返回合并后的 URL Example: ``` url = str.MergeUrlFromHTTPRequest(b"GET /z HTTP/1.1\r\nHost: www.yaklang.com\r\n\r\n", "/a/b", true) // url = "https://www.yaklang.com/z/a/b" ```

func NewRequestPacketFromMethod added in v1.2.6

func NewRequestPacketFromMethod(method string, targetURL string, originRequest []byte, originReqIns *http.Request, https bool, cookies ...*http.Cookie) []byte

func NewWriter

func NewWriter(w io.Writer, ctor func(io.Writer) Compressor) *msgWriter

NewWriter returns a new Writer.

func ParseBytesToHTTPResponse

func ParseBytesToHTTPResponse(res []byte) (rspInst *http.Response, err error)

ParseBytesToHTTPResponse 将字节数组解析为 HTTP 响应 Example: ``` res, err := str.ParseBytesToHTTPResponse(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok") ```

func ParseBytesToHttpRequest

func ParseBytesToHttpRequest(raw []byte) (reqInst *http.Request, err error)

ParseBytesToHTTPRequest 将字节数组解析为 HTTP 请求 Example: ``` req, err := str.ParseBytesToHTTPRequest(b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n") ```

func ParseCookie

func ParseCookie(key, raw string) []*http.Cookie

ParseCookie parse 请求包中的 Cookie 字符串

func ParseMultiPartFormWithCallback added in v1.3.3

func ParseMultiPartFormWithCallback(req []byte, callback func(part *multipart.Part)) (err error)

ParseMultiPartFormWithCallback 是一个辅助函数,用于尝试解析请求报文体中的表单并进行回调 Example: ``` poc.ParseMultiPartFormWithCallback(`POST /post HTTP/1.1 Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW Host: pie.dev

------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="a"

1 ------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="b"

2 ------WebKitFormBoundary7MA4YWxkTrZu0gW--`, func(part) { content = string(io.ReadAll(part)~) println(part.FileName(), part.FormName(), content) }) ```

func ParseStringToHTTPResponse

func ParseStringToHTTPResponse(res string) (*http.Response, error)

ParseStringToHTTPResponse 将字符串解析为 HTTP 响应 Example: ``` res, err := str.ParseStringToHTTPResponse("HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok") ```

func ParseStringToHttpRequest

func ParseStringToHttpRequest(raw string) (*http.Request, error)

ParseStringToHTTPRequest 将字符串解析为 HTTP 请求 Example: ``` req, err = str.ParseStringToHTTPRequest("GET / HTTP/1.1\r\nHost: example.com\r\n\r\n") ```

func ParseUrlToHttpRequestRaw

func ParseUrlToHttpRequestRaw(method string, i interface{}) (isHttps bool, req []byte, err error)

ParseUrlToHTTPRequestRaw 将URL解析为原始 HTTP 请求报文,返回是否为 HTTPS,原始请求报文与错误 Example: ``` ishttps, raw, err = poc.ParseUrlToHTTPRequestRaw("GET", "https://yaklang.com") ```

func ReadHTTPPacketBodySize

func ReadHTTPPacketBodySize(raw []byte) (cl int, chunked bool)

func RegisterSaveHTTPFlowHandler

func RegisterSaveHTTPFlowHandler(h saveHTTPFlowHandler)

func RemoveCEHeaders

func RemoveCEHeaders(headerBytes []byte) []byte

func RemoveZeroContentLengthHTTPHeader

func RemoveZeroContentLengthHTTPHeader(raw []byte) []byte

func ReplaceAllHTTPPacketHeaders added in v1.3.1

func ReplaceAllHTTPPacketHeaders(packet []byte, headers map[string]string) []byte

ReplaceAllHTTPPacketHeaders 是一个辅助函数,用于改变请求报文,修改所有请求头 Example: ``` poc.ReplaceAllHTTPPacketHeaders(poc.BasicRequest(), {"AAA": "BBB"}) // 修改所有请求头,这里没有AAA请求头,所以会增加该请求头 ```

func ReplaceAllHTTPPacketPostParams added in v1.2.4

func ReplaceAllHTTPPacketPostParams(packet []byte, values map[string]string) []byte

ReplaceAllHTTPPacketPostParams 是一个辅助函数,用于改变请求报文,修改所有 POST 请求参数,如果不存在则会增加,其接收一个 map[string]string 类型的参数,其中 key 为 POST 请求参数名,value 为 POST 请求参数值 Example: ``` _, raw, _ = poc.ParseUrlToHTTPRequestRaw("POST", "https://pie.dev/post") poc.ReplaceAllHTTPPacketPostParams(raw, {"a":"b", "c":"d"}) // 添加POST请求参数a,值为b,POST请求参数c,值为d ```

func ReplaceAllHTTPPacketPostParamsWithoutEscape added in v1.3.1

func ReplaceAllHTTPPacketPostParamsWithoutEscape(packet []byte, values map[string]string) []byte

ReplaceAllHTTPPacketPostParamsWithoutEscape 是一个辅助函数,用于改变请求报文,修改所有 POST 请求参数,如果不存在则会增加,其接收一个 map[string]string 类型的参数,其中 key 为 POST 请求参数名,value 为 POST 请求参数值 与 poc.ReplaceAllHTTPPacketPostParams 类似,但是不会将参数值进行转义

Example: ``` _, raw, _ = poc.ParseUrlToHTTPRequestRaw("POST", "https://pie.dev/post") poc.ReplaceAllHTTPPacketPostParamsWithoutEscape(raw, {"a":"b", "c":"d"}) // 添加POST请求参数a,值为b,POST请求参数c,值为d ```

func ReplaceAllHTTPPacketQueryParams added in v1.2.4

func ReplaceAllHTTPPacketQueryParams(packet []byte, values map[string]string) []byte

ReplaceAllHTTPPacketQueryParams 是一个辅助函数,用于改变请求报文,修改所有 GET 请求参数,如果不存在则会增加,其接收一个 map[string]string 类型的参数,其中 key 为请求参数名,value 为请求参数值 Example: ``` poc.ReplaceAllHTTPPacketQueryParams(poc.BasicRequest(), {"a":"b", "c":"d"}) // 添加GET请求参数a,值为b,添加GET请求参数c,值为d ```

func ReplaceAllHTTPPacketQueryParamsWithoutEscape added in v1.3.1

func ReplaceAllHTTPPacketQueryParamsWithoutEscape(packet []byte, values map[string]string) []byte

ReplaceAllHTTPPacketQueryParamsWithoutEscape 是一个辅助函数,用于改变请求报文,修改所有 GET 请求参数,如果不存在则会增加,其接收一个 map[string]string 类型的参数,其中 key 为请求参数名,value 为请求参数值 与 poc.ReplaceAllHTTPPacketQueryParams 类似,但是不会将参数值进行转义 Example: ``` poc.ReplaceAllHTTPPacketQueryParamsWithoutEscape(poc.BasicRequest(), {"a":"b", "c":"d"}) // 添加GET请求参数a,值为b,添加GET请求参数c,值为d ```

func ReplaceFullHTTPPacketPostParamsWithoutEscape added in v1.3.3

func ReplaceFullHTTPPacketPostParamsWithoutEscape(packet []byte, values map[string][]string) []byte

func ReplaceFullHTTPPacketQueryParamsWithoutEscape added in v1.3.3

func ReplaceFullHTTPPacketQueryParamsWithoutEscape(packet []byte, values map[string][]string) []byte

func ReplaceHTTPPacketBasicAuth added in v1.2.4

func ReplaceHTTPPacketBasicAuth(packet []byte, username, password string) []byte

ReplaceHTTPPacketBasicAuth 是一个辅助函数,用于改变请求报文,修改Authorization请求头为基础认证的密文,如果不存在则会增加,实际上是ReplaceHTTPPacketHeader("Authorization", codec.EncodeBase64(username + ":" + password))的简写 Example: ``` _, raw, _ = poc.ParseUrlToHTTPRequestRaw("GET", "https://pie.dev/basic-auth/admin/password") poc.ReplaceHTTPPacketBasicAuth(raw, "admin", "password") // 修改Authorization请求头 ```

func ReplaceHTTPPacketBody

func ReplaceHTTPPacketBody(raw []byte, body []byte, chunk bool) (newHTTPRequest []byte)

ReplaceBody 将原始 HTTP 请求报文中的 body 替换为指定的 body,并指定是否为 chunked,返回新的 HTTP 请求报文 Example: ``` poc.ReplaceBody(`POST / HTTP/1.1 Host: example.com Content-Length: 11

hello world`, "hello yak", false) ```

func ReplaceHTTPPacketBodyEx

func ReplaceHTTPPacketBodyEx(raw []byte, body []byte, chunk bool, forceCL bool) []byte

func ReplaceHTTPPacketBodyFast added in v1.2.3

func ReplaceHTTPPacketBodyFast(packet []byte, body []byte) []byte

ReplaceHTTPPacketBody 是一个辅助函数,用于改变 HTTP 报文,修改 HTTP 报文主体内容,第一个参数为原始 HTTP 报文,第二个参数为修改的报文主体内容 Example: ``` poc.ReplaceHTTPPacketBody(poc.BasicRequest(), "a=b") // 修改请求体内容为a=b ```

func ReplaceHTTPPacketBodyRaw

func ReplaceHTTPPacketBodyRaw(raw []byte, body []byte, fixCL bool) []byte

func ReplaceHTTPPacketCookie added in v1.2.3

func ReplaceHTTPPacketCookie(packet []byte, key string, value any) []byte

ReplaceHTTPPacketCookie 是一个辅助函数,用于改变请求报文,修改Cookie请求头中的值,如果不存在则会增加 Example: ``` poc.ReplaceHTTPPacketCookie(poc.BasicRequest(), "aaa", "bbb") // 修改cookie值,由于这里没有aaa的cookie值,所以会增加 ```

func ReplaceHTTPPacketCookies added in v1.3.2

func ReplaceHTTPPacketCookies(packet []byte, m any) []byte

ReplaceHTTPPacketCookies 是一个辅助函数,用于改变请求报文,修改Cookie请求头 Example: ``` poc.ReplaceHTTPPacketCookies(poc.BasicRequest(), {"aaa":"bbb", "ccc":"ddd"}) // 修改cookie值为aaa=bbb;ccc=ddd ```

func ReplaceHTTPPacketFirstLine added in v1.2.3

func ReplaceHTTPPacketFirstLine(packet []byte, firstLine string) []byte

ReplaceHTTPPacketFirstLine 是一个辅助,用于改变请求报文,修改第一行(即请求方法,请求路径,协议版本) Example: ``` poc.ReplaceHTTPPacketFirstLine(`GET / HTTP/1.1 Host: Example.com `, "GET /test HTTP/1.1")) // 向 example.com 发起请求,修改请求报文的第一行,请求/test路径 ```

func ReplaceHTTPPacketFormEncoded added in v1.3.2

func ReplaceHTTPPacketFormEncoded(packet []byte, key, value string) []byte

ReplaceHTTPPacketFormEncoded 是一个辅助函数,用于改变请求报文,替换请求体中的表单,如果不存在则会增加 Example: ``` poc.ReplaceHTTPPacketFormEncoded(`POST /post HTTP/1.1 Host: pie.dev Content-Type: multipart/form-data; boundary=------------------------OFHnlKtUimimGcXvRSxgCZlIMAyDkuqsxeppbIFm Content-Length: 203

--------------------------OFHnlKtUimimGcXvRSxgCZlIMAyDkuqsxeppbIFm Content-Disposition: form-data; name="aaa"

bbb --------------------------OFHnlKtUimimGcXvRSxgCZlIMAyDkuqsxeppbIFm--`, "ccc", "ddd") // 替换POST请求表单,其中ccc为键,ddd为值 ```

func ReplaceHTTPPacketHeader added in v1.2.3

func ReplaceHTTPPacketHeader(packet []byte, headerKey string, headerValue any) []byte

ReplaceHTTPPacketHeader 是一个辅助函数,用于改变请求报文,修改请求头,如果不存在则会增加 Example: ``` poc.ReplaceHTTPPacketHeader(poc.BasicRequest(),"AAA", "BBB") // 修改AAA请求头的值为BBB,这里没有AAA请求头,所以会增加该请求头 ```

func ReplaceHTTPPacketHost added in v1.2.4

func ReplaceHTTPPacketHost(packet []byte, host string) []byte

ReplaceHTTPPacketHost 是一个辅助函数,用于改变请求报文,修改Host请求头,如果不存在则会增加,实际上是ReplaceHTTPPacketHeader("Host", host)的简写 Example: ``` _, raw, _ = poc.ParseUrlToHTTPRequestRaw("GET", "https://yaklang.com") poc.ReplaceHTTPPacketHost(raw, "www.yaklang.com") // 修改Host请求头的值为 www.yaklang.com ```

func ReplaceHTTPPacketJsonBody

func ReplaceHTTPPacketJsonBody(packet []byte, jsonMap map[string]interface{}) []byte

ReplaceHTTPPacketJsonBody 是一个辅助函数,用于改变 HTTP 报文,修改 HTTP 报文主体内容( json 格式),第一个参数为原始 HTTP 报文,第二个参数为修改的报文主体内容( map 对象) Example: ``` poc.ReplaceHTTPPacketJsonBody(poc.BasicRequest(), {"a":"b"}) // 修改请求体内容为{"a":"b"} ```

func ReplaceHTTPPacketMethod added in v1.2.4

func ReplaceHTTPPacketMethod(packet []byte, newMethod string) []byte

ReplaceHTTPPacketMethod 是一个辅助函数,用于改变请求报文,修改请求方法 Example: ``` poc.ReplaceHTTPPacketMethod(poc.BasicRequest(), "OPTIONS") // 修改请求方法为OPTIONS ```

func ReplaceHTTPPacketPath added in v1.2.3

func ReplaceHTTPPacketPath(packet []byte, p string) []byte

ReplaceHTTPPacketPath 是一个辅助函数,用于改变请求报文,修改请求路径 Example: ``` poc.ReplaceHTTPPacketPath(poc.BasicRequest(), "/get") // 修改请求路径为/get ```

func ReplaceHTTPPacketPathWithoutEncoding added in v1.3.3

func ReplaceHTTPPacketPathWithoutEncoding(packet []byte, p string) []byte

func ReplaceHTTPPacketPostParam added in v1.2.3

func ReplaceHTTPPacketPostParam(packet []byte, key, value string) []byte

ReplaceHTTPPacketPostParam 是一个辅助函数,用于改变请求报文,修改POST请求参数,如果不存在则会增加 Example: ``` _, raw, _ = poc.ParseUrlToHTTPRequestRaw("POST", "https://pie.dev/post") poc.ReplaceHTTPPacketPostParam(raw, "a", "b") // 添加POST请求参数a,值为b ```

func ReplaceHTTPPacketQueryParam added in v1.2.3

func ReplaceHTTPPacketQueryParam(packet []byte, key, value string) []byte

ReplaceHTTPPacketQueryParam 是一个辅助函数,用于改变请求报文,修改GET请求参数,如果不存在则会增加 Example: ``` _, raw, _ = poc.ParseUrlToHTTPRequestRaw("GET", "https://pie.dev/get") poc.ReplaceHTTPPacketQueryParam(raw, "a", "b") // 添加GET请求参数a,值为b ```

func ReplaceHTTPPacketQueryParamRaw added in v1.3.0

func ReplaceHTTPPacketQueryParamRaw(packet []byte, rawQuery string) []byte

func ReplaceHTTPPacketQueryParamWithoutEncoding added in v1.2.8

func ReplaceHTTPPacketQueryParamWithoutEncoding(packet []byte, key, value string) []byte

func ReplaceHTTPPacketUploadFile added in v1.3.2

func ReplaceHTTPPacketUploadFile(packet []byte, fieldName, fileName string, fileContent interface{}, contentType ...string) []byte

ReplaceHTTPPacketUploadFile 是一个辅助函数,用于改变请求报文,替换请求体中的上传的文件,其中第一个参数为原始请求报文,第二个参数为表单名,第三个参数为文件名,第四个参数为文件内容,第五个参数是可选参数,为文件类型(Content-Type),如果表单名不存在则会增加 Example: ``` _, raw, _ = poc.ParseUrlToHTTPRequestRaw("POST", "https://pie.dev/post") poc.ReplaceHTTPPacketUploadFile(raw, "file", "phpinfo.php", "<?php phpinfo(); ?>", "image/jpeg")) // 添加POST请求表单,其文件名为phpinfo.php,内容为<?php phpinfo(); ?>,文件类型为image/jpeg ```

func ReplaceMIMEType

func ReplaceMIMEType(headerBytes []byte, mimeType string) []byte

func SaveLowHTTPResponse added in v1.3.3

func SaveLowHTTPResponse(r *LowhttpResponse)

func ServeHTTP2Connection added in v1.2.9

func ServeHTTP2Connection(conn net.Conn, handler func(header []byte, body io.ReadCloser) ([]byte, io.ReadCloser, error)) error

func SetHTTPPacketUrl added in v1.2.7

func SetHTTPPacketUrl(packet []byte, rawURL string) []byte

func ShouldSendReqContentLength

func ShouldSendReqContentLength(method string, contentLength int64) bool

ShouldSendReqContentLength reports whether the http2.Transport should send a "content-length" request header. This logic is basically a copy of the net/http transferWriter.shouldSendContentLength. The contentLength is the corrected contentLength (so 0 means actually 0, not unknown). -1 means unknown.

func SplitHTTPHeader

func SplitHTTPHeader(i string) (string, string)

func SplitHTTPHeadersAndBodyFromPacket

func SplitHTTPHeadersAndBodyFromPacket(raw []byte, hook ...func(line string)) (headers string, body []byte)

SplitHTTPHeadersAndBodyFromPacket 将传入的 HTTP 报文分割为 headers 和 body,如果传入了hook,则会在每次读取到一行 header 时调用 hook Example: ``` headers, body = str.SplitHTTPHeadersAndBodyFromPacket(b"GET / HTTP/1.1\r\nHost: www.yaklang.com\r\n\r\n") ```

func SplitHTTPHeadersAndBodyFromPacketEx

func SplitHTTPHeadersAndBodyFromPacketEx(raw []byte, mf func(method string, requestUri string, proto string) error, hook ...func(line string)) (string, []byte)

func SplitHTTPPacket added in v1.2.3

func SplitHTTPPacket(
	raw []byte,
	reqFirstLine func(method string, requestUri string, proto string) error,
	rspFirstLine func(proto string, code int, codeMsg string) error,
	hook ...func(line string) string,
) (string, []byte)

SplitHTTPPacket split http packet to headers and body reqFirstLine: method, requestUri, proto: error for empty result rspFirstLine: proto, code, codeMsg: error for empty result hook: hook func

func SplitHTTPPacketFast added in v1.2.3

func SplitHTTPPacketFast(raw any) (string, []byte)

func SplitKV

func SplitKV(i string) (string, string)

func ToLower

func ToLower(s string) (lower string, ok bool)

func ToUnquoteFuzzTag

func ToUnquoteFuzzTag(i []byte) string

func TrimLeftHTTPPacket

func TrimLeftHTTPPacket(raw []byte) []byte

func TrimRightHTTPPacket

func TrimRightHTTPPacket(raw []byte) []byte

func TrimSpaceHTTPPacket

func TrimSpaceHTTPPacket(raw []byte) []byte

func UrlToGetRequestPacket

func UrlToGetRequestPacket(u string, originRequest []byte, originRequestHttps bool, cookies ...*http.Cookie) []byte

func UrlToHTTPRequest added in v1.2.8

func UrlToHTTPRequest(text string) ([]byte, error)

func UrlToRequestPacket added in v1.2.3

func UrlToRequestPacket(method string, u string, originRequest []byte, originRequestHttps bool, cookies ...*http.Cookie) []byte

func UrlToRequestPacketEx

func UrlToRequestPacketEx(method string, targetURL string, originRequest []byte, https bool, statusCode int, cookies ...*http.Cookie) ([]byte, error)

func ValidCookieValue added in v1.3.3

func ValidCookieValue(value string) bool

ValidCookieValue 判断是否存在不允许的字符,

Types

type Authentication added in v1.2.8

type Authentication interface {
	Authenticate(conn net.Conn, config *LowhttpExecConfig) ([]byte, error)
}

func GetAuth added in v1.2.8

func GetAuth(authHeader string, username string, password string) Authentication

func GetHttpAuth added in v1.2.9

func GetHttpAuth(authHeader string, opt *LowhttpExecConfig) Authentication

type BasicAuthentication added in v1.2.8

type BasicAuthentication struct {
	Username string
	Password string
}

func (*BasicAuthentication) Authenticate added in v1.2.8

func (ba *BasicAuthentication) Authenticate(conn net.Conn, config *LowhttpExecConfig) ([]byte, error)

type CompressionMode

type CompressionMode uint8
const (
	DisableCompression CompressionMode = 1 + iota
	EnableCompression
	CompressionContextTakeover
	NoCompressionContextTakeover
)

type Compressor

type Compressor interface {
	io.Writer
	Flush() error
}

Compressor is an interface holding deflate compression implementation.

type CurlCommand added in v1.2.3

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

CurlCommand contains exec.Command compatible slice + helpers

func GetCurlCommand added in v1.2.3

func GetCurlCommand(isHttps bool, req []byte) (*CurlCommand, error)

GetCurlCommand returns a CurlCommand corresponding to an http.Request

func (*CurlCommand) String added in v1.2.3

func (c *CurlCommand) String() string

String returns a ready to copy/paste command

type CustomAuthClient added in v1.2.9

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

func (*CustomAuthClient) Authenticate added in v1.2.9

func (ca *CustomAuthClient) Authenticate(conn net.Conn, config *LowhttpExecConfig) ([]byte, error)

type DigestAuthentication added in v1.2.8

type DigestAuthentication struct {
	// DigestAuthentication的相关属性
	Username string
	Password string
}

func (*DigestAuthentication) Authenticate added in v1.2.8

func (da *DigestAuthentication) Authenticate(conn net.Conn, config *LowhttpExecConfig) ([]byte, error)

type DigestAuthorization added in v1.2.8

type DigestAuthorization struct {
	Algorithm string // unquoted
	Cnonce    string // quoted
	Nc        int    // unquoted
	Nonce     string // quoted
	Opaque    string // quoted
	Qop       string // unquoted
	Realm     string // quoted
	Response  string // quoted
	URI       string // quoted
	Userhash  bool   // quoted
	Username  string // quoted
	Username_ string // quoted
}

func (*DigestAuthorization) RefreshAuthorization added in v1.2.8

func (ah *DigestAuthorization) RefreshAuthorization(dr *DigestRequest) (*DigestAuthorization, error)

func (*DigestAuthorization) RefreshAuthorizationWithoutConce added in v1.2.8

func (ah *DigestAuthorization) RefreshAuthorizationWithoutConce(dr *DigestRequest) (*DigestAuthorization, error)

func (*DigestAuthorization) String added in v1.2.8

func (ah *DigestAuthorization) String() string

type DigestRequest added in v1.2.8

type DigestRequest struct {
	Body     string
	Method   string
	Password string
	URI      string
	Username string
	Auth     *DigestAuthorization
	Wa       *wwwAuthenticate
	CertVal  bool
	// contains filtered or unexported fields
}

func NewDigestRequest added in v1.2.8

func NewDigestRequest(username, password, method, uri, body string, useCompleteURL bool) *DigestRequest

NewDigestRequest creates a new DigestRequest object

func (*DigestRequest) UpdateRequest added in v1.2.8

func (dr *DigestRequest) UpdateRequest(username, password, method, uri, body string, useCompleteURL bool) *DigestRequest

func (*DigestRequest) UpdateRequestWithUsernameAndPassword added in v1.2.8

func (dr *DigestRequest) UpdateRequestWithUsernameAndPassword(username, password string) *DigestRequest

type Frame

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

func (*Frame) Bytes

func (f *Frame) Bytes() ([]byte, []byte)

func (*Frame) FIN

func (f *Frame) FIN() bool

func (*Frame) GetCloseCode

func (f *Frame) GetCloseCode() int

func (*Frame) GetData added in v1.3.1

func (f *Frame) GetData() []byte

func (*Frame) GetFirstByte added in v1.3.1

func (f *Frame) GetFirstByte() byte

func (*Frame) GetMask added in v1.3.1

func (f *Frame) GetMask() bool

func (*Frame) GetMaskingKey

func (f *Frame) GetMaskingKey() []byte

func (*Frame) GetPayload added in v1.3.1

func (f *Frame) GetPayload() []byte

func (*Frame) GetRaw added in v1.3.1

func (f *Frame) GetRaw() []byte

func (*Frame) HasRsv

func (f *Frame) HasRsv() bool

func (*Frame) IsControl

func (f *Frame) IsControl() bool

func (*Frame) IsReservedType

func (f *Frame) IsReservedType() bool

func (*Frame) IsValidCloseCode

func (f *Frame) IsValidCloseCode() bool

func (*Frame) RSV1

func (f *Frame) RSV1() bool

func (*Frame) RSV2

func (f *Frame) RSV2() bool

func (*Frame) RSV3

func (f *Frame) RSV3() bool

func (*Frame) SetData added in v1.3.1

func (f *Frame) SetData(d []byte)

func (*Frame) SetMaskingKey

func (f *Frame) SetMaskingKey(r []byte)

func (*Frame) SetOpcode

func (f *Frame) SetOpcode(opcode int)

func (*Frame) SetRSV1

func (f *Frame) SetRSV1()

func (*Frame) Show

func (f *Frame) Show()

func (*Frame) Type

func (f *Frame) Type() int

func (*Frame) UnsetRSV1

func (f *Frame) UnsetRSV1()

type FrameReader

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

func NewFrameReader

func NewFrameReader(r io.Reader, isDeflate bool) *FrameReader

func NewFrameReaderFromBufio

func NewFrameReaderFromBufio(r *bufio.Reader, isDeflate bool) *FrameReader

func (*FrameReader) ReadFrame

func (fr *FrameReader) ReadFrame() (frame *Frame, err error)

func (*FrameReader) SetWebsocketClient

func (fr *FrameReader) SetWebsocketClient(c *WebsocketClient)

type FrameWriter

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

func NewFrameWriter

func NewFrameWriter(w io.Writer, isDeflate bool) *FrameWriter

func NewFrameWriterFromBufio

func NewFrameWriterFromBufio(w *bufio.Writer, isDeflate bool) *FrameWriter

func (*FrameWriter) Flush

func (fw *FrameWriter) Flush() error

func (*FrameWriter) SetWebsocketClient

func (fw *FrameWriter) SetWebsocketClient(c *WebsocketClient)

func (*FrameWriter) WriteBinary

func (fw *FrameWriter) WriteBinary(data []byte, mask bool) (err error)

func (*FrameWriter) WriteDirect

func (fw *FrameWriter) WriteDirect(fin bool, flate bool, opcode int, mask bool, data []byte) (n int, err error)

func (*FrameWriter) WriteEx

func (fw *FrameWriter) WriteEx(data []byte, opcode int, mask bool) error

客户端发送数据时需要设置mask为true

func (*FrameWriter) WriteFrame

func (fw *FrameWriter) WriteFrame(f *Frame, opcodes ...int) (err error)

func (*FrameWriter) WritePong

func (fw *FrameWriter) WritePong(data []byte, mask bool) (err error)

func (*FrameWriter) WriteRaw

func (fw *FrameWriter) WriteRaw(raw []byte) (err error)

func (*FrameWriter) WriteText

func (fw *FrameWriter) WriteText(data []byte, mask bool) (err error)

type HttpParamPositionType

type HttpParamPositionType string
var (
	PosMethod              HttpParamPositionType = "method"
	PosBody                HttpParamPositionType = "body"
	PosGetQuery            HttpParamPositionType = "get-query"
	PosGetQueryBase64      HttpParamPositionType = "get-query-base64"
	PosGetQueryJson        HttpParamPositionType = "get-query-json"
	PosGetQueryBase64Json  HttpParamPositionType = "get-query-base64-json"
	PosPath                HttpParamPositionType = "path"
	PosHeader              HttpParamPositionType = "header"
	PosPostQuery           HttpParamPositionType = "post-query"
	PosPostXML             HttpParamPositionType = "post-xml"
	PosPostQueryBase64     HttpParamPositionType = "post-query-base64"
	PosPostQueryJson       HttpParamPositionType = "post-query-json"
	PosPostQueryBase64Json HttpParamPositionType = "post-query-base64-json"
	PosPostJson            HttpParamPositionType = "post-json"
	PosCookie              HttpParamPositionType = "cookie"
	PosCookieBase64        HttpParamPositionType = "cookie-base64"
	PosCookieJson          HttpParamPositionType = "cookie-json"
	PosCookieBase64Json    HttpParamPositionType = "cookie-base64-json"
	PosPathAppend          HttpParamPositionType = "path-append"
	PosPathBlock           HttpParamPositionType = "path-block"
)

type LowHttpConnPool added in v1.3.0

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

func NewDefaultHttpConnPool added in v1.3.0

func NewDefaultHttpConnPool() *LowHttpConnPool

type LowhttpExecConfig

type LowhttpExecConfig struct {
	Host                             string
	Port                             int
	Packet                           []byte
	VerifyCertificate                bool
	Https                            bool
	ResponseCallback                 func(response *LowhttpResponse)
	Http2                            bool
	GmTLS                            bool
	OverrideEnableSystemProxyFromEnv bool
	EnableSystemProxyFromEnv         bool
	ConnectTimeout                   time.Duration
	Timeout                          time.Duration
	RedirectTimes                    int
	RetryTimes                       int
	RetryInStatusCode                []int
	RetryNotInStatusCode             []int
	RetryWaitTime                    time.Duration
	RetryMaxWaitTime                 time.Duration
	JsRedirect                       bool
	Proxy                            []string
	ForceLegacyProxy                 bool
	NoFixContentLength               bool
	RedirectHandler                  func(bool, []byte, []byte) bool
	Session                          interface{}
	BeforeDoRequest                  func([]byte) []byte
	Ctx                              context.Context
	SaveHTTPFlow                     bool
	SaveHTTPFlowHandler              func(*LowhttpResponse)
	RequestSource                    string
	EtcHosts                         map[string]string
	DNSServers                       []string
	RuntimeId                        string
	FromPlugin                       string
	WithConnPool                     bool
	ConnPool                         *LowHttpConnPool
	NativeHTTPRequestInstance        *http.Request
	Username                         string
	Password                         string

	// DefaultBufferSize means unexpected situation's buffer size
	DefaultBufferSize int

	// MaxContentLength: too large content-length will be ignored(truncated)
	EnableMaxContentLength bool
	MaxContentLength       int

	DNSNoCache bool

	// BodyStreamReaderHandler is a callback function to handle the body stream reader
	BodyStreamReaderHandler func(responseHeader []byte, closer io.ReadCloser)

	// SNI
	SNI string

	// payloads (web fuzzer)
	Payloads []string

	RandomJA3FingerPrint bool
	ClientHelloSpec      *utls.ClientHelloSpec
}

func NewLowhttpOption

func NewLowhttpOption() *LowhttpExecConfig

NewLowhttpOption create a new LowhttpExecConfig

type LowhttpOpt

type LowhttpOpt func(o *LowhttpExecConfig)

func ConnPool added in v1.2.7

func ConnPool(p *LowHttpConnPool) LowhttpOpt

func WithBeforeDoRequest

func WithBeforeDoRequest(h func([]byte) []byte) LowhttpOpt

func WithBodyStreamReaderHandler added in v1.3.2

func WithBodyStreamReaderHandler(t func([]byte, io.ReadCloser)) LowhttpOpt

func WithClientHelloSpec

func WithClientHelloSpec(spec *utls.ClientHelloSpec) LowhttpOpt

func WithConnPool added in v1.2.7

func WithConnPool(b bool) LowhttpOpt

func WithConnectTimeout added in v1.3.1

func WithConnectTimeout(timeout time.Duration) LowhttpOpt

func WithConnectTimeoutFloat added in v1.3.1

func WithConnectTimeoutFloat(i float64) LowhttpOpt

func WithContext

func WithContext(ctx context.Context) LowhttpOpt

func WithDNSNoCache added in v1.3.0

func WithDNSNoCache(b bool) LowhttpOpt

WithDNSNoCache is not effective

func WithDNSServers

func WithDNSServers(servers []string) LowhttpOpt

func WithDefaultBufferSize added in v1.2.8

func WithDefaultBufferSize(size int) LowhttpOpt

func WithETCHosts

func WithETCHosts(hosts map[string]string) LowhttpOpt

func WithEnableSystemProxyFromEnv added in v1.2.8

func WithEnableSystemProxyFromEnv(b bool) LowhttpOpt

func WithForceLegacyProxy added in v1.2.8

func WithForceLegacyProxy(b bool) LowhttpOpt

func WithFromPlugin added in v1.2.3

func WithFromPlugin(fromPlugin string) LowhttpOpt

func WithGmTLS added in v1.2.2

func WithGmTLS(b bool) LowhttpOpt

func WithHost

func WithHost(host string) LowhttpOpt

func WithHttp2

func WithHttp2(Http2 bool) LowhttpOpt

func WithHttps

func WithHttps(https bool) LowhttpOpt

func WithJsRedirect

func WithJsRedirect(jsRedirect bool) LowhttpOpt

func WithMaxContentLength added in v1.2.8

func WithMaxContentLength(m int) LowhttpOpt

func WithNativeHTTPRequestInstance added in v1.2.8

func WithNativeHTTPRequestInstance(req *http.Request) LowhttpOpt

func WithNoFixContentLength

func WithNoFixContentLength(noFixContentLength bool) LowhttpOpt

func WithPacketBytes added in v1.2.4

func WithPacketBytes(packet []byte) LowhttpOpt

func WithPassword added in v1.2.8

func WithPassword(password string) LowhttpOpt

func WithPayloads added in v1.3.3

func WithPayloads(payloads []string) LowhttpOpt

func WithPort

func WithPort(port int) LowhttpOpt

func WithProxy

func WithProxy(proxy ...string) LowhttpOpt

func WithProxyGetter added in v1.3.1

func WithProxyGetter(getter func() []string) LowhttpOpt

func WithRandomJA3FingerPrint

func WithRandomJA3FingerPrint(b bool) LowhttpOpt

func WithRedirectHandler

func WithRedirectHandler(redirectHandler func(bool, []byte, []byte) bool) LowhttpOpt

func WithRedirectTimes

func WithRedirectTimes(redirectTimes int) LowhttpOpt

func WithRequest added in v1.2.4

func WithRequest(packet any) LowhttpOpt

func WithResponseCallback added in v1.2.4

func WithResponseCallback(h func(i *LowhttpResponse)) LowhttpOpt

func WithRetryInStatusCode

func WithRetryInStatusCode(sc []int) LowhttpOpt

func WithRetryMaxWaitTime

func WithRetryMaxWaitTime(retryMaxWaitTime time.Duration) LowhttpOpt

func WithRetryNotInStatusCode

func WithRetryNotInStatusCode(sc []int) LowhttpOpt

func WithRetryTimes

func WithRetryTimes(retryTimes int) LowhttpOpt

func WithRetryWaitTime

func WithRetryWaitTime(retryWaitTime time.Duration) LowhttpOpt

func WithRuntimeId added in v1.2.3

func WithRuntimeId(runtimeId string) LowhttpOpt

func WithSNI added in v1.3.1

func WithSNI(sni string) LowhttpOpt

func WithSaveHTTPFlow

func WithSaveHTTPFlow(b bool) LowhttpOpt

func WithSaveHTTPFlowHandler

func WithSaveHTTPFlowHandler(f func(*LowhttpResponse)) LowhttpOpt

func WithSession

func WithSession(session interface{}) LowhttpOpt

func WithSource

func WithSource(s string) LowhttpOpt

func WithTimeout

func WithTimeout(timeout time.Duration) LowhttpOpt

func WithTimeoutFloat added in v1.2.4

func WithTimeoutFloat(i float64) LowhttpOpt

func WithUsername added in v1.2.8

func WithUsername(username string) LowhttpOpt

func WithVerifyCertificate added in v1.2.4

func WithVerifyCertificate(b bool) LowhttpOpt

type LowhttpResponse

type LowhttpResponse struct {
	RawPacket              []byte
	BareResponse           []byte
	RedirectRawPackets     []*RedirectFlow
	PortIsOpen             bool
	TraceInfo              *LowhttpTraceInfo
	Url                    string
	RemoteAddr             string
	Proxy                  string
	Https                  bool
	Http2                  bool
	RawRequest             []byte
	Source                 string // 请求源
	RuntimeId              string
	FromPlugin             string
	MultiResponse          bool
	MultiResponseInstances []*http.Response
	RequestInstance        *http.Request

	// if TooLarge, the database will drop some response data
	TooLarge         bool
	TooLargeLimit    int64
	ResponseBodySize int64

	// !deprecated
	// HiddenIndex associate between http_flows and web_fuzzer_response table
	HiddenIndex string

	// payloads (web fuzzer)
	Payloads []string
}

func HTTP added in v1.2.4

func HTTP(opts ...LowhttpOpt) (*LowhttpResponse, error)

func HTTPWithoutRedirect added in v1.2.4

func HTTPWithoutRedirect(opts ...LowhttpOpt) (*LowhttpResponse, error)

HTTPWithoutRedirect SendHttpRequestWithRawPacketWithOpt

func (*LowhttpResponse) GetBody added in v1.3.2

func (l *LowhttpResponse) GetBody() []byte

func (*LowhttpResponse) GetDurationFloat

func (l *LowhttpResponse) GetDurationFloat() float64

func (*LowhttpResponse) GetStatusCode

func (l *LowhttpResponse) GetStatusCode() int

type LowhttpTraceInfo

type LowhttpTraceInfo struct {
	AvailableDNSServers []string
	// DNS 完整请求时间
	DNSTime time.Duration
	// 获取一个连接的耗时
	ConnTime time.Duration
	// 服务器处理耗时,计算从连接建立到客户端收到第一个字节的时间间隔
	ServerTime time.Duration
	// 完整请求的耗时
	TotalTime time.Duration
}

func (*LowhttpTraceInfo) GetServerDurationMS

func (l *LowhttpTraceInfo) GetServerDurationMS() int64

type NtlmAuthentication added in v1.2.8

type NtlmAuthentication struct {
	Username string
	Password string
	Domain   string
}

func (*NtlmAuthentication) Authenticate added in v1.2.8

func (na *NtlmAuthentication) Authenticate(conn net.Conn, config *LowhttpExecConfig) ([]byte, error)

type QueryOption

type QueryOption func(q *QueryParams)

func WithDisableAutoEncode

func WithDisableAutoEncode(b bool) QueryOption

func WithFriendlyDisplay

func WithFriendlyDisplay(b bool) QueryOption

func WithPosition

func WithPosition(p HttpParamPositionType) QueryOption

type QueryParamItem added in v1.2.8

type QueryParamItem struct {
	NoAutoEncode    bool
	Raw             string
	Key             string
	Value, ValueRaw string
	Position        HttpParamPositionType
}

func (*QueryParamItem) Encode added in v1.2.8

func (item *QueryParamItem) Encode() string

type QueryParams added in v1.2.8

type QueryParams struct {
	NoAutoEncode bool

	Position HttpParamPositionType
	Items    []*QueryParamItem
	// contains filtered or unexported fields
}

func ExtractQueryFromRequestURI added in v1.2.8

func ExtractQueryFromRequestURI(i string) *QueryParams

func NewQueryParams added in v1.2.8

func NewQueryParams() *QueryParams

func ParseQueryParams added in v1.2.8

func ParseQueryParams(s string, options ...QueryOption) *QueryParams

func (*QueryParams) Add added in v1.2.8

func (q *QueryParams) Add(key, val string)

func (*QueryParams) AppendRaw added in v1.2.8

func (q *QueryParams) AppendRaw(raw string)

func (*QueryParams) Clear added in v1.3.1

func (q *QueryParams) Clear()

func (*QueryParams) Del added in v1.2.8

func (q *QueryParams) Del(key string)

func (*QueryParams) DisableAutoEncode added in v1.2.8

func (q *QueryParams) DisableAutoEncode(b bool) *QueryParams

func (*QueryParams) Encode added in v1.2.8

func (q *QueryParams) Encode() string

func (*QueryParams) EncodeByPos

func (q *QueryParams) EncodeByPos(pos HttpParamPositionType) string

func (*QueryParams) Get added in v1.2.8

func (q *QueryParams) Get(key string) string

func (*QueryParams) GetAll added in v1.2.8

func (q *QueryParams) GetAll(key string) []string

func (*QueryParams) GetLast added in v1.2.8

func (q *QueryParams) GetLast(key string) string

func (*QueryParams) Have added in v1.2.8

func (q *QueryParams) Have(key string) bool

func (*QueryParams) IsEmpty added in v1.3.3

func (q *QueryParams) IsEmpty() bool

func (*QueryParams) Remove added in v1.2.8

func (q *QueryParams) Remove(key string)

func (*QueryParams) Set added in v1.2.8

func (q *QueryParams) Set(key, val string)

func (*QueryParams) SetFriendlyDisplay added in v1.3.3

func (q *QueryParams) SetFriendlyDisplay(b bool) *QueryParams

func (*QueryParams) SetPosition

func (q *QueryParams) SetPosition(p HttpParamPositionType) *QueryParams

type RedirectFlow added in v1.2.4

type RedirectFlow struct {
	IsHttps    bool
	Request    []byte
	Response   []byte
	RespRecord *LowhttpResponse
}

type WebHookServer

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

func NewWebHookServer

func NewWebHookServer(port int, cb func(data interface{})) *WebHookServer

func NewWebHookServerEx

func NewWebHookServerEx(port int, cb func(data interface{})) *WebHookServer

func (*WebHookServer) Addr

func (w *WebHookServer) Addr() string

func (*WebHookServer) Shutdown

func (w *WebHookServer) Shutdown()

func (*WebHookServer) Start

func (w *WebHookServer) Start()

type WebsocketClient

type WebsocketClient struct {
	Request             []byte
	Response            []byte
	ResponseInstance    *http.Response
	FromServerOnce      *sync.Once
	FromServerHandler   func([]byte)
	FromServerHandlerEx func(*WebsocketClient, []byte, []*Frame)
	AllFrameHandler     func(*WebsocketClient, *Frame, []byte, func())
	DisableReassembly   bool
	Extensions          *WebsocketExtensions
	Context             context.Context
	// contains filtered or unexported fields
}

func NewWebsocketClient

func NewWebsocketClient(packet []byte, opt ...WebsocketClientOpt) (*WebsocketClient, error)

func NewWebsocketClientIns

func NewWebsocketClientIns(conn net.Conn, fr *FrameReader, fw *FrameWriter, ext *WebsocketExtensions, opts ...WebsocketClientOpt) *WebsocketClient

func (*WebsocketClient) Close

func (c *WebsocketClient) Close() error

func (*WebsocketClient) HasExtensions

func (c *WebsocketClient) HasExtensions() bool

func (*WebsocketClient) StartFromServer

func (c *WebsocketClient) StartFromServer()

func (*WebsocketClient) Stop

func (c *WebsocketClient) Stop()

func (*WebsocketClient) Wait

func (c *WebsocketClient) Wait()

func (*WebsocketClient) Write

func (c *WebsocketClient) Write(r []byte) error

func (*WebsocketClient) WriteBinary

func (c *WebsocketClient) WriteBinary(r []byte) error

func (*WebsocketClient) WriteClose added in v1.2.4

func (c *WebsocketClient) WriteClose() error

func (*WebsocketClient) WriteCloseEx

func (c *WebsocketClient) WriteCloseEx(closeCode int, message string) error

func (*WebsocketClient) WriteDirect

func (c *WebsocketClient) WriteDirect(fin, flate bool, opcode int, mask bool, data []byte) error

func (*WebsocketClient) WriteEx

func (c *WebsocketClient) WriteEx(r []byte, frameTyp int) error

func (*WebsocketClient) WritePong

func (c *WebsocketClient) WritePong(r []byte, masked bool) error

func (*WebsocketClient) WriteText

func (c *WebsocketClient) WriteText(r []byte) error

type WebsocketClientConfig

type WebsocketClientConfig struct {
	Proxy                  string
	TotalTimeout           time.Duration
	TLS                    bool
	FromServerHandler      func([]byte)
	UpgradeResponseHandler func(*http.Response, []byte, *WebsocketExtensions, error) []byte
	FromServerHandlerEx    func(*WebsocketClient, []byte, []*Frame)
	AllFrameHandler        func(*WebsocketClient, *Frame, []byte, func())
	DisableReassembly      bool
	Context                context.Context

	// Host Port
	Host string
	Port int
	// contains filtered or unexported fields
}

type WebsocketClientOpt

type WebsocketClientOpt func(config *WebsocketClientConfig)

func WithWebsocketAllFrameHandler

func WithWebsocketAllFrameHandler(f func(*WebsocketClient, *Frame, []byte, func())) WebsocketClientOpt

func WithWebsocketCompress

func WithWebsocketCompress(b bool) WebsocketClientOpt

func WithWebsocketCompressionContextTakeover

func WithWebsocketCompressionContextTakeover(b bool) WebsocketClientOpt

func WithWebsocketDisableReassembly

func WithWebsocketDisableReassembly(b bool) WebsocketClientOpt

func WithWebsocketFromServerHandler

func WithWebsocketFromServerHandler(f func([]byte)) WebsocketClientOpt

func WithWebsocketFromServerHandlerEx

func WithWebsocketFromServerHandlerEx(f func(*WebsocketClient, []byte, []*Frame)) WebsocketClientOpt

func WithWebsocketHost

func WithWebsocketHost(t string) WebsocketClientOpt

func WithWebsocketPort

func WithWebsocketPort(t int) WebsocketClientOpt

func WithWebsocketProxy

func WithWebsocketProxy(t string) WebsocketClientOpt

func WithWebsocketServerMode

func WithWebsocketServerMode(b bool) WebsocketClientOpt

func WithWebsocketStrictMode

func WithWebsocketStrictMode(b bool) WebsocketClientOpt

func WithWebsocketTLS

func WithWebsocketTLS(t bool) WebsocketClientOpt

func WithWebsocketTotalTimeout

func WithWebsocketTotalTimeout(t float64) WebsocketClientOpt

func WithWebsocketUpgradeResponseHandler

func WithWebsocketUpgradeResponseHandler(f func(*http.Response, []byte, *WebsocketExtensions, error) []byte) WebsocketClientOpt

func WithWebsocketWithContext

func WithWebsocketWithContext(ctx context.Context) WebsocketClientOpt

type WebsocketExtensions

type WebsocketExtensions struct {
	Extensions            []string
	ClientContextTakeover bool
	ServerContextTakeover bool
	IsDeflate             bool
}

func GetWebsocketExtensions

func GetWebsocketExtensions(headers http.Header) *WebsocketExtensions

type WriteResetter

type WriteResetter interface {
	Reset(io.Writer)
}

WriteResetter is an optional interface that Compressor can implement.

type WriterFunc

type WriterFunc func(p []byte) (int, error)

WriterFunc is used to implement one off io.Writers.

func (WriterFunc) Write

func (f WriterFunc) Write(p []byte) (int, error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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