Movatterモバイル変換


[0]ホーム

URL:


textproto

packagestandard library
go1.25.4Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2025 License:BSD-3-ClauseImports:11Imported by:17,188

Details

Repository

cs.opensource.google/go/go

Links

Documentation

Overview

Package textproto implements generic support for text-based request/responseprotocols in the style of HTTP, NNTP, and SMTP.

This package enforces the HTTP/1.1 character set defined byRFC 9112 for header keys and values.

The package provides:

Error, which represents a numeric error response froma server.

Pipeline, to manage pipelined requests and responsesin a client.

Reader, to read numeric response code lines,key: value headers, lines wrapped with leading spaceson continuation lines, and whole text blocks endingwith a dot on a line by itself.

Writer, to write dot-encoded text blocks.

Conn, a convenient packaging ofReader,Writer, andPipeline for usewith a single network connection.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

funcCanonicalMIMEHeaderKey

func CanonicalMIMEHeaderKey(sstring)string

CanonicalMIMEHeaderKey returns the canonical format of theMIME header key s. The canonicalization converts the firstletter and any letter following a hyphen to upper case;the rest are converted to lowercase. For example, thecanonical key for "accept-encoding" is "Accept-Encoding".MIME header keys are assumed to be ASCII only.If s contains a space or invalid header field bytes asdefined byRFC 9112, it is returned without modifications.

funcTrimBytesadded ingo1.1

func TrimBytes(b []byte) []byte

TrimBytes returns b without leading and trailing ASCII space.

funcTrimStringadded ingo1.1

func TrimString(sstring)string

TrimString returns s without leading and trailing ASCII space.

Types

typeConn

type Conn struct {ReaderWriterPipeline// contains filtered or unexported fields}

A Conn represents a textual network protocol connection.It consists of aReader andWriter to manage I/Oand aPipeline to sequence concurrent requests on the connection.These embedded types carry methods with them;see the documentation of those types for details.

funcDial

func Dial(network, addrstring) (*Conn,error)

Dial connects to the given address on the given network usingnet.Dialand then returns a newConn for the connection.

funcNewConn

func NewConn(connio.ReadWriteCloser) *Conn

NewConn returns a newConn using conn for I/O.

func (*Conn)Close

func (c *Conn) Close()error

Close closes the connection.

func (*Conn)Cmd

func (c *Conn) Cmd(formatstring, args ...any) (iduint, errerror)

Cmd is a convenience method that sends a command afterwaiting its turn in the pipeline. The command text is theresult of formatting format with args and appending \r\n.Cmd returns the id of the command, for use with StartResponse and EndResponse.

For example, a client might run a HELP command that returns a dot-bodyby using:

id, err := c.Cmd("HELP")if err != nil {return nil, err}c.StartResponse(id)defer c.EndResponse(id)if _, _, err = c.ReadCodeLine(110); err != nil {return nil, err}text, err := c.ReadDotBytes()if err != nil {return nil, err}return c.ReadCodeLine(250)

typeError

type Error struct {CodeintMsgstring}

An Error represents a numeric error response from a server.

func (*Error)Error

func (e *Error) Error()string

typeMIMEHeader

type MIMEHeader map[string][]string

A MIMEHeader represents a MIME-style header mappingkeys to sets of values.

func (MIMEHeader)Add

func (hMIMEHeader) Add(key, valuestring)

Add adds the key, value pair to the header.It appends to any existing values associated with key.

func (MIMEHeader)Del

func (hMIMEHeader) Del(keystring)

Del deletes the values associated with key.

func (MIMEHeader)Get

func (hMIMEHeader) Get(keystring)string

Get gets the first value associated with the given key.It is case insensitive;CanonicalMIMEHeaderKey is usedto canonicalize the provided key.If there are no values associated with the key, Get returns "".To use non-canonical keys, access the map directly.

func (MIMEHeader)Set

func (hMIMEHeader) Set(key, valuestring)

Set sets the header entries associated with key tothe single element value. It replaces any existingvalues associated with key.

func (MIMEHeader)Valuesadded ingo1.14

func (hMIMEHeader) Values(keystring) []string

Values returns all values associated with the given key.It is case insensitive;CanonicalMIMEHeaderKey isused to canonicalize the provided key. To use non-canonicalkeys, access the map directly.The returned slice is not a copy.

typePipeline

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

A Pipeline manages a pipelined in-order request/response sequence.

To use a Pipeline p to manage multiple clients on a connection,each client should run:

id := p.Next()// take a numberp.StartRequest(id)// wait for turn to send request«send request»p.EndRequest(id)// notify Pipeline that request is sentp.StartResponse(id)// wait for turn to read response«read response»p.EndResponse(id)// notify Pipeline that response is read

A pipelined server can use the same calls to ensure thatresponses computed in parallel are written in the correct order.

func (*Pipeline)EndRequest

func (p *Pipeline) EndRequest(iduint)

EndRequest notifies p that the request with the given id has been sent(or, if this is a server, received).

func (*Pipeline)EndResponse

func (p *Pipeline) EndResponse(iduint)

EndResponse notifies p that the response with the given id has been received(or, if this is a server, sent).

func (*Pipeline)Next

func (p *Pipeline) Next()uint

Next returns the next id for a request/response pair.

func (*Pipeline)StartRequest

func (p *Pipeline) StartRequest(iduint)

StartRequest blocks until it is time to send (or, if this is a server, receive)the request with the given id.

func (*Pipeline)StartResponse

func (p *Pipeline) StartResponse(iduint)

StartResponse blocks until it is time to receive (or, if this is a server, send)the request with the given id.

typeProtocolError

type ProtocolErrorstring

A ProtocolError describes a protocol violation suchas an invalid response or a hung-up connection.

func (ProtocolError)Error

func (pProtocolError) Error()string

typeReader

type Reader struct {R *bufio.Reader// contains filtered or unexported fields}

A Reader implements convenience methods for reading requestsor responses from a text protocol network connection.

funcNewReader

func NewReader(r *bufio.Reader) *Reader

NewReader returns a newReader reading from r.

To avoid denial of service attacks, the providedbufio.Readershould be reading from anio.LimitReader or similar Reader to boundthe size of responses.

func (*Reader)DotReader

func (r *Reader) DotReader()io.Reader

DotReader returns a newReader that satisfies Reads using thedecoded text of a dot-encoded block read from r.The returned Reader is only valid until the next callto a method on r.

Dot encoding is a common framing used for data blocksin text protocols such as SMTP. The data consists of a sequenceof lines, each of which ends in "\r\n". The sequence itselfends at a line containing just a dot: ".\r\n". Lines beginningwith a dot are escaped with an additional dot to avoidlooking like the end of the sequence.

The decoded form returned by the Reader's Read methodrewrites the "\r\n" line endings into the simpler "\n",removes leading dot escapes if present, and stops with errorio.EOFafter consuming (and discarding) the end-of-sequence line.

func (*Reader)ReadCodeLine

func (r *Reader) ReadCodeLine(expectCodeint) (codeint, messagestring, errerror)

ReadCodeLine reads a response code line of the form

code message

where code is a three-digit status code and the messageextends to the rest of the line. An example of such a line is:

220 plan9.bell-labs.com ESMTP

If the prefix of the status does not match the digits in expectCode,ReadCodeLine returns with err set to &Error{code, message}.For example, if expectCode is 31, an error will be returned ifthe status is not in the range [310,319].

If the response is multi-line, ReadCodeLine returns an error.

An expectCode <= 0 disables the check of the status code.

func (*Reader)ReadContinuedLine

func (r *Reader) ReadContinuedLine() (string,error)

ReadContinuedLine reads a possibly continued line from r,eliding the final trailing ASCII white space.Lines after the first are considered continuations if theybegin with a space or tab character. In the returned data,continuation lines are separated from the previous lineonly by a single space: the newline and leading white spaceare removed.

For example, consider this input:

Line 1  continued...Line 2

The first call to ReadContinuedLine will return "Line 1 continued..."and the second will return "Line 2".

Empty lines are never continued.

func (*Reader)ReadContinuedLineBytes

func (r *Reader) ReadContinuedLineBytes() ([]byte,error)

ReadContinuedLineBytes is likeReader.ReadContinuedLine butreturns a []byte instead of a string.

func (*Reader)ReadDotBytes

func (r *Reader) ReadDotBytes() ([]byte,error)

ReadDotBytes reads a dot-encoding and returns the decoded data.

See the documentation for theReader.DotReader method for details about dot-encoding.

func (*Reader)ReadDotLines

func (r *Reader) ReadDotLines() ([]string,error)

ReadDotLines reads a dot-encoding and returns a slicecontaining the decoded lines, with the final \r\n or \n elided from each.

See the documentation for theReader.DotReader method for details about dot-encoding.

func (*Reader)ReadLine

func (r *Reader) ReadLine() (string,error)

ReadLine reads a single line from r,eliding the final \n or \r\n from the returned string.

func (*Reader)ReadLineBytes

func (r *Reader) ReadLineBytes() ([]byte,error)

ReadLineBytes is likeReader.ReadLine but returns a []byte instead of a string.

func (*Reader)ReadMIMEHeader

func (r *Reader) ReadMIMEHeader() (MIMEHeader,error)

ReadMIMEHeader reads a MIME-style header from r.The header is a sequence of possibly continued Key: Value linesending in a blank line.The returned map m mapsCanonicalMIMEHeaderKey(key) to asequence of values in the same order encountered in the input.

For example, consider this input:

My-Key: Value 1Long-Key: Even       Longer ValueMy-Key: Value 2

Given that input, ReadMIMEHeader returns the map:

map[string][]string{"My-Key": {"Value 1", "Value 2"},"Long-Key": {"Even Longer Value"},}

func (*Reader)ReadResponse

func (r *Reader) ReadResponse(expectCodeint) (codeint, messagestring, errerror)

ReadResponse reads a multi-line response of the form:

code-message line 1code-message line 2...code message line n

where code is a three-digit status code. The first line starts with thecode and a hyphen. The response is terminated by a line that startswith the same code followed by a space. Each line in message isseparated by a newline (\n).

See page 36 ofRFC 959 (https://www.ietf.org/rfc/rfc959.txt) fordetails of another form of response accepted:

code-message line 1message line 2...code message line n

If the prefix of the status does not match the digits in expectCode,ReadResponse returns with err set to &Error{code, message}.For example, if expectCode is 31, an error will be returned ifthe status is not in the range [310,319].

An expectCode <= 0 disables the check of the status code.

typeWriter

type Writer struct {W *bufio.Writer// contains filtered or unexported fields}

A Writer implements convenience methods for writingrequests or responses to a text protocol network connection.

funcNewWriter

func NewWriter(w *bufio.Writer) *Writer

NewWriter returns a newWriter writing to w.

func (*Writer)DotWriter

func (w *Writer) DotWriter()io.WriteCloser

DotWriter returns a writer that can be used to write a dot-encoding to w.It takes care of inserting leading dots when necessary,translating line-ending \n into \r\n, and adding the final .\r\n linewhen the DotWriter is closed. The caller should close theDotWriter before the next call to a method on w.

See the documentation for theReader.DotReader method for details about dot-encoding.

func (*Writer)PrintfLine

func (w *Writer) PrintfLine(formatstring, args ...any)error

PrintfLine writes the formatted output followed by \r\n.

Source Files

View all Source files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp