httpKit

package
v3.1.112 Latest Latest
Warning

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

Go to latest
Published: Dec 24, 2024 License: Apache-2.0 Imports: 28 Imported by: 0

Documentation

Overview

Package httpKit

请求头 || 响应头 key: 不区分大小写

Index

Constants

View Source
const (
	// PlainContentType 纯文本格式.
	PlainContentType = "text/plain; charset=utf-8"

	// JsonContentType JSON数据格式.
	JsonContentType = "application/json; charset=utf-8"

	// XmlContentType XML数据格式.
	XmlContentType = "text/xml; charset=utf-8"

	// FormUrlencodedContentType 适用于 POST 请求.
	/*
		application/x-www-form-urlencoded: 将键值对的参数用&连接起来,如果有空格,将空格转换为+加号;有特殊符号,将特殊符号转换为ASCII HEX值.
		application/x-www-form-urlencoded是浏览器默认的编码格式,对于Get请求,是将参数转换?key=value&key=value格式,连接到url后.
	*/
	FormUrlencodedContentType = "application/x-www-form-urlencoded; charset=utf-8"

	// OctetStreamContentType 二进制流数据(如常见的文件下载).
	/*
		参考:https://www.runoob.com/http/http-content-type.html
	*/
	OctetStreamContentType = "application/octet-stream; charset=utf-8"
)
View Source
const (
	HeaderAccept = "Accept"

	HeaderAcceptEncoding = "Accept-Encoding"

	HeaderAcceptLanguage = "Accept-Language"

	HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials"

	HeaderAccessControlAllowHeaders = "Access-Control-Allow-Headers"

	HeaderAccessControlAllowMethods = "Access-Control-Allow-Methods"

	HeaderAccessControlAllowOrigin = "Access-Control-Allow-Origin"

	HeaderAccessControlMaxAge = "Access-Control-Max-Age"

	HeaderAllow = "Allow"

	HeaderCacheControl = "Cache-Control"

	HeaderContentType = "Content-Type"

	HeaderConnection = "Connection"

	HeaderDate = "Date"

	HeaderHost = "Host"

	HeaderOrigin = "Origin"

	HeaderSetCookie = "Set-Cookie"

	HeaderVary = "Vary"

	HeaderUpgrade = "Upgrade"

	HeaderXXSSProtection = "X-XSS-Protection"

	HeaderChimeraProxy = "Chimera-Proxy"
)

Variables

View Source
var (
	// GetRequestPublicIp 获取http请求的 "公网ip".
	/*
		涉及的请求头:
		(1) "X-Forwarded-For"
		(2) "X-Real-Ip"
	*/
	GetRequestPublicIp func(req *http.Request) string = netutil.GetRequestPublicIp
)
View Source
var (
	// GetStatusText 获取 http状态码 的描述文本.
	GetStatusText func(code int) string = http.StatusText
)
View Source
var (
	NotSeekableError = errorKit.Newf("request body is not seekable")
)
View Source
var (
	RemoteIPHeaders = []string{"X-Forwarded-For", "X-Real-IP"}
)

Functions

func AddHeader

func AddHeader(header http.Header, key, value string)

AddHeader

PS: key对应的 切片 中,在 最后面 添加value.

e.g.

header := make(map[string][]string)
AddHeader(header, "k", "0")
fmt.Println(header) 		// map[K:[0]]
AddHeader(header, "k", "1")
fmt.Println(header) 		// map[K:[0 1]]
AddHeader(header, "k", "1")
fmt.Println(header) 		// map[K:[0 1 1]]

func AddHeaderIfMissing

func AddHeaderIfMissing(header http.Header, key, value string)

AddHeaderIfMissing

PS: 区分大小写.

func AddHeaderIfMissingIgnoreCase

func AddHeaderIfMissingIgnoreCase(header http.Header, key, value string)

AddHeaderIfMissingIgnoreCase

PS: 不区分大小写.

func AssertHttpUrl

func AssertHttpUrl(httpUrl string) error

func DelHeader

func DelHeader(header http.Header, key string)

func DownloadFile added in v3.0.106

func DownloadFile(w http.ResponseWriter, r *http.Request, path, name string) error

DownloadFile 下载文件(文件路径).

参考: gin里面的 Context.File() 和 Context.FileAttachment().

func DownloadFileContent added in v3.0.106

func DownloadFileContent(w http.ResponseWriter, r *http.Request, content []byte, name string) error

DownloadFileContent 下载文件(文件内容).

参考: gin里面的 Context.File() 和 Context.FileAttachment(). 支持: office文档、图片...

func GetAcceptLanguages added in v3.0.19

func GetAcceptLanguages(req *http.Request) []string

GetAcceptLanguages 根据请求头"Accept-Language".

func GetCertificateInfo added in v3.0.106

func GetCertificateInfo(url string) (*x509.Certificate, error)

GetCertificateInfo

获取https过期时间

https://www.topgoer.cn/docs/gochajian/gofdgjh

@return 仅返回第一个证书信息(有多个的话)

func GetClientIP

func GetClientIP(r *http.Request) string

GetClientIP

PS: 参考 gin's Context.ClientIP().

func GetClientIPFromHeader

func GetClientIPFromHeader(r *http.Request) string

GetClientIPFromHeader

PS: 参考 gin's Context.ClientIP().

func GetClientScheme

func GetClientScheme(req *http.Request) string

GetClientScheme 客户端发送的原始请求 使用的Web协议.

!!!: 返回值不一定准确,除非 代理s 好好配合(有的话).

@return "http" || "https"

func GetFormFile

func GetFormFile(r *http.Request, key string, maxMemory int64) (multipart.File, *multipart.FileHeader, error)

GetFormFile

[Go] golang获取http中的get传递的参数

https://www.cnblogs.com/taoshihan/p/12943118.html

@param maxMemory 可以为-1,此时将采用默认值

func GetHeader

func GetHeader(header http.Header, key string) string

GetHeader

PS: (1) 不存在与 key 对应值的话,将返回 ""; (2) 存在多个值的话([]string && len > 1),返回第一个值.

func GetHeaderValues

func GetHeaderValues(header http.Header, key string) []string

GetHeaderValues

@param key 不存在对应值的话,将返回 nil

func GetHost added in v3.0.106

func GetHost(req *http.Request) string

func GetMethod

func GetMethod(req *http.Request) string

GetMethod 请求的method.

func GetOrigin

func GetOrigin(header http.Header) string

GetOrigin 获取请求的Origin

func GetProto

func GetProto(req *http.Request) string

GetProto 服务器的HTTP版本.

@return (1) "HTTP/1.0"

(2) "HTTP/1.1"
(3) "HTTP/2.0"(https)

func GetRawQuery

func GetRawQuery(req *http.Request) string

GetRawQuery

e.g. http://127.0.0.1/a/b?1=1&2=2 => "1=1&2=2"

func GetReferer

func GetReferer(r *http.Request) string

GetReferer

PS: (1) 涉及 Referer验证; (2) 参考: notes/Web(漏洞等)/Web.wps

func GetRemoteIP

func GetRemoteIP(r *http.Request) string

GetRemoteIP 获取客户端IP地址(客户端的远程IP地址).

PS: 参考 gin's Context.RemoteIP().

e.g. 当客户端通过代理服务器连接时,RemoteIP() 返回代理服务器的 IP 地址

func GetRequestUrl

func GetRequestUrl(req *http.Request) string

GetRequestUrl 返回当前接口的url(带query).

func GetRoute

func GetRoute(req *http.Request) string

GetRoute 获取: 路由(不带query).

e.g.

http://127.0.0.1/a/b?1=1&2=2 => "/a/b"

func GetRouteWithQuery

func GetRouteWithQuery(req *http.Request) string

GetRouteWithQuery 获取: 路由(带query).

e.g.

http://127.0.0.1/a/b?1=1&2=2 => "/a/b?1=1&2=2"

func GetScheme

func GetScheme(req *http.Request) string

GetScheme 请求使用的Web协议.

@return "http" || "https"

func GetUserAgent

func GetUserAgent(header http.Header) string

GetUserAgent 获取http请求头中"User Agent"的值.

参考: https://www.sunzhongwei.com/golang-gin-for-user-agent-in-http-request-header-value

e.g. Chrome浏览器: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36 Safari浏览器: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.5 Safari/605.1.15

func GetUserAgentInfo added in v3.0.106

func GetUserAgentInfo(header http.Header) *useragent.UserAgent

GetUserAgentInfo

亚微秒级的解析速度!Go 语言的高性能 User-Agent 解析库

https://mp.weixin.qq.com/s/Qvj64_WofoCZ8j0eTCq6cQ

PS: 如果是 Postman 发的http请求,返回值的所有字段都是零值.

func HeaderContainsValue

func HeaderContainsValue(header http.Header, key, value string) bool

HeaderContainsValue Header中,指定key对应的value切片是否包含指定value?

PS: 区分大小写.

func HeaderContainsValueIgnoreCase

func HeaderContainsValueIgnoreCase(header http.Header, key, value string) bool

HeaderContainsValueIgnoreCase Header中,指定key对应的value切片是否包含指定value?\

PS: 不区分大小写.

func HeaderToMap

func HeaderToMap(header http.Header) map[string]interface{}

HeaderToMap http.Header(即 map[string][]string) => map[string]interface{}

func HeaderToString added in v3.0.106

func HeaderToString(header http.Header) (string, error)

HeaderToString Converts http header to a string.

func IsValidStatusCode added in v3.0.106

func IsValidStatusCode(code int) bool

IsValidStatusCode 响应的 http状态码 是否有效?

PS: (1) 判断参考了 jQuery; (2) 正常情况下,响应的http状态码有效的情况下,才会去读取响应的body.

func MakeRequestBodySeekable

func MakeRequestBodySeekable(req *http.Request) error

MakeRequestBodySeekable

Go语言: 如何让 request.Body 可以多次读取

https://www.cnblogs.com/ayanmw/p/17191530.html

PS: (1) 一般与 proxy() 搭配使用; (2) 某个路由涉及代理(请求转发)的话,需要在handler里面 首先 调用此方法; (3) 请求有内容的话,会全部读取一遍请求体内容.

func ObtainGetParam

func ObtainGetParam(r *http.Request, key string) string

ObtainGetParam

[Go] golang获取http中的get传递的参数

https://www.cnblogs.com/taoshihan/p/12943118.html

func ObtainPostParam

func ObtainPostParam(r *http.Request, key string) (string, error)

ObtainPostParam

[Go] golang获取http中的get传递的参数

https://www.cnblogs.com/taoshihan/p/12943118.html

func OverrideRequestBody

func OverrideRequestBody(req *http.Request, m map[string][]string) error

OverrideRequestBody 覆盖 POST请求 的请求体(request body).

func PolyfillContextPath

func PolyfillContextPath(relativePath string) string

PolyfillContextPath *

  • e.g.
  • "" => ""
  • "/" => "/"
  • "//" => "/"
  • "///" => "/"
  • "/c/////c//" => "/c/c/" *
  • @return 优化过的ContextPath

func Redirect added in v3.0.106

func Redirect(w http.ResponseWriter, r *http.Request, url string, code int) error

Redirect 请求重定向.

PS: 301: http.StatusMovedPermanently 表示资源已被永久移动到新位置,以后对该资源的请求都应使用新的URL。 302: http.StatusFound 有时称为"Moved Temporarily",表示资源临时被移动到另一个位置,客户端应继续使用原有URL进行以后的请求。 303: http.StatusSeeOther 指示客户端应使用GET方法访问另一个URL以获取资源,通常用于在POST请求后重定向到一个新的资源。 307: http.StatusTemporaryRedirect 表示资源临时被移动到另一个位置,但客户端应继续使用原有URL进行以后的请求(与302不同的是,307要求重定向请求方法和主体不变)。 308: http.StatusPermanentRedirect 表示资源已被永久移动到新位置,客户端以后应使用新的URL进行请求(与301不同的是,308要求重定向请求方法和主体不变)。

!!!选择使用: (1) 302:当重定向后的操作不需要保持原请求方法(例如将POST转换为GET是可以接受的)时使用。 (2) 307:当需要保持原请求方法(例如POST必须保持为POST)时使用,以确保请求数据和操作的正确传递。

@param url e.g. 完整的网址

	"https://www.baidu.com"
e.g.1 仅仅是路由
	"/b"

@param code (1) [300, 308] || 201

(2) Richelieu: 推荐使用 307 或 308

func ResetRequestBody

func ResetRequestBody(req *http.Request) error

ResetRequestBody 重置请求体,以防: 已经读完body了,请求转发给别人,别人收到的请求没内容.

func RespondData

func RespondData(w http.ResponseWriter, code int, contentType string, data []byte) error

RespondData 响应字节流(二进制流)

参考: gin里面的 Context.Content() .

@return 如果不为nil,建议输出到控制台

func RespondJson

func RespondJson(w http.ResponseWriter, code int, obj any) error

RespondJson

参考: gin里面的 Context.JSON() .

func RespondString

func RespondString(w http.ResponseWriter, code int, format string, values ...any) error

RespondString

参考: gin里面的 Context.String() .

func RespondStringData

func RespondStringData(w http.ResponseWriter, code int, data []byte) error

func SetHeader

func SetHeader(header http.Header, key, value string)

SetHeader

e.g.

header := make(map[string][]string)

httpKit.AddHeader(header, "k", "0")
fmt.Println(header) 				// map[K:[0]]
httpKit.AddHeader(header, "k", "1")
fmt.Println(header) 				// map[K:[0 1]]

httpKit.SetHeader(header, "k", "2")
fmt.Println(header) 				// map[K:[2]]
httpKit.SetHeader(header, "k", "")
fmt.Println(header) 				// map[]

func SetHeaderIfMissing

func SetHeaderIfMissing(header http.Header, key, value string)

SetHeaderIfMissing

PS: 区分大小写.

func SetHeaderIfMissingIgnoreCase

func SetHeaderIfMissingIgnoreCase(header http.Header, key, value string)

SetHeaderIfMissingIgnoreCase

PS: 不区分大小写.

func SetHost added in v3.0.106

func SetHost(req *http.Request, newHost string)

SetHost 修改请求头中的Host,一般用于请求转发前.

func Status

func Status(w http.ResponseWriter, code int)

Status 设置响应的http状态码

PS: (1) 不建议多次设置 http状态码; (2) 如果多次设置的话,感觉 第一次设置的值 会生效.

@param code -1: 不设置http状态码

func ToRequestBodyString

func ToRequestBodyString(m map[string][]string) string

ToRequestBodyString

条件: (1) POST (2) x-www-form-urlencoded

e.g.

m := map[string][]string{
	"a": []string{"test"},
	"b": []string{"测试"},
}
fmt.Println(ToRequestBodyString(m)) // a=test&b=%E6%B5%8B%E8%AF%95

func TryToResetRequestBody

func TryToResetRequestBody(req *http.Request) (err error)

Types

type Repeat

type Repeat struct {
	Reader io.ReaderAt
	Offset int64
}

func (*Repeat) Close

func (p *Repeat) Close() error

func (*Repeat) Read

func (p *Repeat) Read(val []byte) (n int, err error)

Read 重写读方法,使每次读取request.Body时能从指定位置读取

func (*Repeat) Reset

func (p *Repeat) Reset()

Reset 重置偏移量

Jump to

Keyboard shortcuts

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