Golang包(三)

二十七、hex

包 hex 实现十六进制编码和解码。

27.1 EncodeToString()

func EncodeToString(src []byte) string

EncodeToString 返回 src 的十六进制编码。

func main() {
	src := []byte("Hello")
	encodedStr := hex.EncodeToString(src)

	fmt.Printf("%s\n", encodedStr)
	fmt.Printf("%x\n", src)
}

27.2 DecodeString()

func DecodeString(s string) ([]byte, error)

DecodeString返回由十六进制字符串s表示的字节切片。
DecodeString期望src只包含十六进制字符,并且src具有合适的长度。如果输入格式不正确,DecodeString返回错误发生前已解码的字节。

func main() {
	const s = "48656c6c6f20476f7068657221"
	decoded, err := hex.DecodeString(s)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%s\n", decoded)
}

二十八、path

包path实现了操作斜杠分隔路径的实用例程。
路径包应该只用于由正斜杠分隔的路径,例如url中的路径。这个包不处理带有驱动器号或反斜杠的Windows路径;要操作操作系统路径,请使用path/filepath包。

28.1 path/filepath

包 filepath 实现了用与目标操作系统定义的文件路径兼容的方式操作文件名路径的实用例程。

根据操作系统的不同,filepath包可以使用正斜杠或反斜杠。要处理总是使用正斜杠的url等路径,而不考虑操作系统,请参阅path包。

28.1 Base

func Base(path string) string
Base返回path的最后一个元素。在提取最后一个元素之前删除尾随路径分隔符。如果路径为空,Base返回"."。如果路径完全由分隔符组成,Base返回一个分隔符。

二十九、mime

包mime实现了mime规范的部分内容。

mime/multipart

包 multipart 实现了RFC 2046中定义的MIME multipart 解析。
这种实现对于HTTP (RFC 2388)和流行浏览器生成的multipart 体(multipart bodies)已经足够了。

FileHeader

// FileHeader描述多部分请求(multipart request)的文件部分。
type FileHeader struct {
	Filename string
	Header   textproto.MIMEHeader
	Size     int64

	content []byte
	tmpfile string
}

Form

type Form struct {
	Value map[string][]string
	File  map[string][]*FileHeader
}

Form 是经过解析的 multipart form。
它的File部分要么存储在内存中,要么存储在磁盘上,可以通过*FileHeader的 Open方法访问。
它的Value部分被存储为字符串。两者都是按字段名来键入的。

三十、net

30.1 http

包 http 提供http客户端和服务器实现。

类型

1) FileSystem

type FileSystem interface {
	Open(name string) (File, error)
}

FileSystem 实现对命名文件集合的访问。文件路径中的元素用斜杠(‘/’,U+002F)字符分隔,而不考虑主机操作系统的约定。参见FileServer函数将文件系统转换为处理程序。
该接口的使用时间早于fs.FS接口,它可以代替FileSystem :FS适配器函数转换一个fs.FSFileSystem

2) Response

type Response struct {
	Status     string // e.g. "200 OK"
	StatusCode int    // e.g. 200
	Proto      string // e.g. "HTTP/1.0"
	ProtoMajor int    // e.g. 1
	ProtoMinor int    // e.g. 0

	// Header maps header keys to values. If the response had multiple
	// headers with the same key, they may be concatenated, with comma
	// delimiters.  (RFC 7230, section 3.2.2 requires that multiple headers
	// be semantically equivalent to a comma-delimited sequence.) When
	// Header values are duplicated by other fields in this struct (e.g.,
	// ContentLength, TransferEncoding, Trailer), the field values are
	// authoritative.
	//
	// Keys in the map are canonicalized (see CanonicalHeaderKey).
	Header Header

	// Body represents the response body.
	//
	// The response body is streamed on demand as the Body field
	// is read. If the network connection fails or the server
	// terminates the response, Body.Read calls return an error.
	//
	// The http Client and Transport guarantee that Body is always
	// non-nil, even on responses without a body or responses with
	// a zero-length body. It is the caller's responsibility to
	// close Body. The default HTTP client's Transport may not
	// reuse HTTP/1.x "keep-alive" TCP connections if the Body is
	// not read to completion and closed.
	//
	// The Body is automatically dechunked if the server replied
	// with a "chunked" Transfer-Encoding.
	//
	// As of Go 1.12, the Body will also implement io.Writer
	// on a successful "101 Switching Protocols" response,
	// as used by WebSockets and HTTP/2's "h2c" mode.
	Body io.ReadCloser

	// ContentLength records the length of the associated content. The
	// value -1 indicates that the length is unknown. Unless Request.Method
	// is "HEAD", values >= 0 indicate that the given number of bytes may
	// be read from Body.
	ContentLength int64

	// Contains transfer encodings from outer-most to inner-most. Value is
	// nil, means that "identity" encoding is used.
	TransferEncoding []string

	// Close records whether the header directed that the connection be
	// closed after reading Body. The value is advice for clients: neither
	// ReadResponse nor Response.Write ever closes a connection.
	Close bool

	// Uncompressed reports whether the response was sent compressed but
	// was decompressed by the http package. When true, reading from
	// Body yields the uncompressed content instead of the compressed
	// content actually set from the server, ContentLength is set to -1,
	// and the "Content-Length" and "Content-Encoding" fields are deleted
	// from the responseHeader. To get the original response from
	// the server, set Transport.DisableCompression to true.
	Uncompressed bool

	// Trailer maps trailer keys to values in the same
	// format as Header.
	//
	// The Trailer initially contains only nil values, one for
	// each key specified in the server's "Trailer" header
	// value. Those values are not added to Header.
	//
	// Trailer must not be accessed concurrently with Read calls
	// on the Body.
	//
	// After Body.Read has returned io.EOF, Trailer will contain
	// any trailer values sent by the server.
	Trailer Header

	// Request is the request that was sent to obtain this Response.
	// Request's Body is nil (having already been consumed).
	// This is only populated for Client requests.
	Request *Request

	// TLS contains information about the TLS connection on which the
	// response was received. It is nil for unencrypted responses.
	// The pointer is shared between responses and should not be
	// modified.
	TLS *tls.ConnectionState
}

3) Server

type Server struct {
	// Addr optionally specifies the TCP address for the server to listen on,
	// in the form "host:port". If empty, ":http" (port 80) is used.
	// The service names are defined in RFC 6335 and assigned by IANA.
	// See net.Dial for details of the address format.
	Addr string

	Handler Handler // handler to invoke, http.DefaultServeMux if nil

	// TLSConfig optionally provides a TLS configuration for use
	// by ServeTLS and ListenAndServeTLS. Note that this value is
	// cloned by ServeTLS and ListenAndServeTLS, so it's not
	// possible to modify the configuration with methods like
	// tls.Config.SetSessionTicketKeys. To use
	// SetSessionTicketKeys, use Server.Serve with a TLS Listener
	// instead.
	TLSConfig *tls.Config

	// ReadTimeout is the maximum duration for reading the entire
	// request, including the body. A zero or negative value means
	// there will be no timeout.
	//
	// Because ReadTimeout does not let Handlers make per-request
	// decisions on each request body's acceptable deadline or
	// upload rate, most users will prefer to use
	// ReadHeaderTimeout. It is valid to use them both.
	ReadTimeout time.Duration

	// ReadHeaderTimeout is the amount of time allowed to read
	// request headers. The connection's read deadline is reset
	// after reading the headers and the Handler can decide what
	// is considered too slow for the body. If ReadHeaderTimeout
	// is zero, the value of ReadTimeout is used. If both are
	// zero, there is no timeout.
	ReadHeaderTimeout time.Duration

	// WriteTimeout is the maximum duration before timing out
	// writes of the response. It is reset whenever a new
	// request's header is read. Like ReadTimeout, it does not
	// let Handlers make decisions on a per-request basis.
	// A zero or negative value means there will be no timeout.
	WriteTimeout time.Duration

	// IdleTimeout is the maximum amount of time to wait for the
	// next request when keep-alives are enabled. If IdleTimeout
	// is zero, the value of ReadTimeout is used. If both are
	// zero, there is no timeout.
	IdleTimeout time.Duration

	// MaxHeaderBytes controls the maximum number of bytes the
	// server will read parsing the request header's keys and
	// values, including the request line. It does not limit the
	// size of the request body.
	// If zero, DefaultMaxHeaderBytes is used.
	MaxHeaderBytes int

	// TLSNextProto optionally specifies a function to take over
	// ownership of the provided TLS connection when an ALPN
	// protocol upgrade has occurred. The map key is the protocol
	// name negotiated. The Handler argument should be used to
	// handle HTTP requests and will initialize the Request's TLS
	// and RemoteAddr if not already set. The connection is
	// automatically closed when the function returns.
	// If TLSNextProto is not nil, HTTP/2 support is not enabled
	// automatically.
	TLSNextProto map[string]func(*Server, *tls.Conn, Handler)

	// ConnState specifies an optional callback function that is
	// called when a client connection changes state. See the
	// ConnState type and associated constants for details.
	ConnState func(net.Conn, ConnState)

	// ErrorLog specifies an optional logger for errors accepting
	// connections, unexpected behavior from handlers, and
	// underlying FileSystem errors.
	// If nil, logging is done via the log package's standard logger.
	ErrorLog *log.Logger

	// BaseContext optionally specifies a function that returns
	// the base context for incoming requests on this server.
	// The provided Listener is the specific Listener that's
	// about to start accepting requests.
	// If BaseContext is nil, the default is context.Background().
	// If non-nil, it must return a non-nil context.
	BaseContext func(net.Listener) context.Context

	// ConnContext optionally specifies a function that modifies
	// the context used for a new connection c. The provided ctx
	// is derived from the base context and has a ServerContextKey
	// value.
	ConnContext func(ctx context.Context, c net.Conn) context.Context

	inShutdown atomicBool // true when server is in shutdown

	disableKeepAlives int32     // accessed atomically.
	nextProtoOnce     sync.Once // guards setupHTTP2_* init
	nextProtoErr      error     // result of http2.ConfigureServer if used

	mu         sync.Mutex
	listeners  map[*net.Listener]struct{}
	activeConn map[*conn]struct{}
	doneChan   chan struct{}
	onShutdown []func()
}

30.1.1 FS()

func FS(fsys fs.FS) FileSystem

FS将fsys转换为FileSystem实现,与 FileServer 和 NewFileTransport一起使用。

30.1.2 Get()

func Get(url string) (resp *Response, err error)

Get向指定的URL发出Get。如果响应是以下重定向代码之一,Get会跟随重定向,最多10个重定向:
301 (Moved Permanently)
302 (Found)
303 (See Other)
307 (Temporary Redirect)
308 (Permanent Redirect)

如果重定向过多或存在HTTP协议错误,则返回错误。非2xx响应不会导致错误。任何返回的错误都是*url.Error类型。如果请求超时,url.Error值的Timeout方法将报告true

当err为nil时,respp总是包含一个非nil的respp.body。呼叫者应关闭响应。当从它中读取时。

Get是DefaultClient.Get的包装器。
使用NewRequest和DefaultClient.Do发出带有自定义头的请求。

用指定的context.Context,使用NewRequestWithContext和DefaultClient.Do。

30.1.3 ListenAndServe()

func ListenAndServe(addr string, handler Handler) error

ListenAndServe监听TCP网络地址addr,然后调用与处理程序一起服务,以处理传入连接上的请求。已接受的连接被配置为启用TCP keep-alives。
处理程序通常为nil,在这种情况下使用 DefaultServeMux
ListenAndServe总是返回一个非nil错误。

三十一、signal

31.1 Notify()

func Notify(c chan<- os.Signal, sig ...os.Signal)

Notify使包 signal 将传入信号中继到c
如果没有提供信号,所有传入的信号将被中继到c。否则,只有提供的信号将会。
包 signal 不会阻塞发送到c:调用者必须确保c有足够的缓冲空间以跟上预期的信号速率。对于仅用于通知一个信号值的通道,大小为1的缓冲区就足够了。
允许使用同一个通道多次调用Notify:每次调用都会扩展发送到该通道的信号集。从集合中删除信号的唯一方法是调用Stop。
允许使用不同的通道和相同的信号多次调用Notify:每个通道独立地接收传入信号的副本。

31.2 Stop()

func Stop(c chan<- os.Signal)

Stop使包 signal 停止向c中继传入信号。
它使用c撤消之前对Notify的所有调用的效果。当Stop返回时,保证c将不再接收信号。

三十二、database

32.1 sql

包 sql 提供了sql(或类sql)数据库的通用接口。

32.1.1 database/sql/driver

包 driver 定义了数据库驱动程序要实现的接口,就像包sql使用的那样。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值