Пакет http
Обзор
Пакет http предоставляет реализации HTTP-клиента и сервера.
Get, Head, Post и PostForm делают HTTP (или HTTPS) запросы:
resp, err := http.Get("http://example.com/")
...
resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf)
...
resp, err := http.PostForm("http://example.com/form",
url.Values{"key": {"Value"}, "id": {"123"}})
Вызывающая сторона должна закрыть тело ответа, когда закончит с ним:
resp, err := http.Get("http://example.com/")
if err != nil {
// handle error
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
// ...
Клиенты и Транспорты
Для управления заголовками HTTP-клиента, политикой перенаправления и другими настройками создайте Client:
client := &http.Client{
CheckRedirect: redirectPolicyFunc,
}
resp, err := client.Get("http://example.com")
// ...
req, err := http.NewRequest("GET", "http://example.com", nil)
// ...
req.Header.Add("If-None-Match", `W/"wyzzy"`)
resp, err := client.Do(req)
// ...
Для управления прокси, настройками TLS, keep-alive, сжатием и другими настройками создайте Transport:
tr := &http.Transport{
MaxIdleConns: 10,
IdleConnTimeout: 30 * time.Second,
DisableCompression: true,
}
client := &http.Client{Transport: tr}
resp, err := client.Get("https://example.com")
Клиенты и Транспорты безопасны для одновременного использования несколькими горутинами и для повышения эффективности должны создаваться один раз и повторно использоваться.
Серверы
ListenAndServe запускает HTTP-сервер с заданным адресом и обработчиком. Обработчик обычно равен null, что означает использование DefaultServeMux. Handle и HandleFunc добавляют обработчики в DefaultServeMux:
http.Handle("/foo", fooHandler)
http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
})
log.Fatal(http.ListenAndServe(":8080", nil))
Для большего контроля над поведением сервера можно создать пользовательский сервер:
s := &http.Server{
Addr: ":8080",
Handler: myHandler,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
log.Fatal(s.ListenAndServe())
HTTP/2
Начиная с Go 1.6, пакет http имеет прозрачную поддержку протокола HTTP/2 при использовании HTTPS. Программы, которые должны отключить HTTP/2, могут сделать это, установив [Transport.TLSNextProto] (для клиентов) или [Server.TLSNextProto] (для серверов) в непустой, пустой массив. В качестве альтернативы, в настоящее время поддерживаются следующие настройки GODEBUG:
GODEBUG=http2client=0 # disable HTTP/2 client support GODEBUG=http2server=0 # disable HTTP/2 server support GODEBUG=http2debug=1 # enable verbose HTTP/2 debug logs GODEBUG=http2debug=2 # ... even more verbose, with frame dumps
Пожалуйста, сообщите о любых проблемах перед отключением поддержки HTTP/2: https://golang.org/s/http2bug
Транспорт Transport и сервер Server пакета http автоматически включают поддержку HTTP/2 для простых конфигураций. Для включения HTTP/2 для более сложных конфигураций, использования функций HTTP/2 более низкого уровня или использования новой версии пакета http2 Go, импортируйте "golang.org/x/net/http2" напрямую и используйте его функции ConfigureTransport и/или ConfigureServer. Ручная настройка HTTP/2 через пакет golang.org/x/net/http2 имеет приоритет над встроенной поддержкой HTTP/2 пакета net/http.
Индекс
Примеры
Файлы пакета
client.go clone.go cookie.go doc.go filetransport.go fs.go h2_bundle.go h2_error.go header.go http.go jar.go mapping.go method.go pattern.go request.go response.go responsecontroller.go roundtrip.go routing_index.go routing_tree.go servemux121.go server.go sniff.go socks_bundle.go status.go transfer.go transport.go transport_default_other.go
Константы
Общие HTTP-методы.
Если не указано иное, они определены в RFC 7231 разделе 4.3.
const (
MethodGet = "GET"
MethodHead = "HEAD"
MethodPost = "POST"
MethodPut = "PUT"
MethodPatch = "PATCH" // RFC 5789
MethodDelete = "DELETE"
MethodConnect = "CONNECT"
MethodOptions = "OPTIONS"
MethodTrace = "TRACE"
) HTTP-коды состояния, зарегистрированные в IANA. См.: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const (
StatusContinue = 100 // RFC 9110, 15.2.1
StatusSwitchingProtocols = 101 // RFC 9110, 15.2.2
StatusProcessing = 102 // RFC 2518, 10.1
StatusEarlyHints = 103 // RFC 8297
StatusOK = 200 // RFC 9110, 15.3.1
StatusCreated = 201 // RFC 9110, 15.3.2
StatusAccepted = 202 // RFC 9110, 15.3.3
StatusNonAuthoritativeInfo = 203 // RFC 9110, 15.3.4
StatusNoContent = 204 // RFC 9110, 15.3.5
StatusResetContent = 205 // RFC 9110, 15.3.6
StatusPartialContent = 206 // RFC 9110, 15.3.7
StatusMultiStatus = 207 // RFC 4918, 11.1
StatusAlreadyReported = 208 // RFC 5842, 7.1
StatusIMUsed = 226 // RFC 3229, 10.4.1
StatusMultipleChoices = 300 // RFC 9110, 15.4.1
StatusMovedPermanently = 301 // RFC 9110, 15.4.2
StatusFound = 302 // RFC 9110, 15.4.3
StatusSeeOther = 303 // RFC 9110, 15.4.4
StatusNotModified = 304 // RFC 9110, 15.4.5
StatusUseProxy = 305 // RFC 9110, 15.4.6
StatusTemporaryRedirect = 307 // RFC 9110, 15.4.8
StatusPermanentRedirect = 308 // RFC 9110, 15.4.9
StatusBadRequest = 400 // RFC 9110, 15.5.1
StatusUnauthorized = 401 // RFC 9110, 15.5.2
StatusPaymentRequired = 402 // RFC 9110, 15.5.3
StatusForbidden = 403 // RFC 9110, 15.5.4
StatusNotFound = 404 // RFC 9110, 15.5.5
StatusMethodNotAllowed = 405 // RFC 9110, 15.5.6
StatusNotAcceptable = 406 // RFC 9110, 15.5.7
StatusProxyAuthRequired = 407 // RFC 9110, 15.5.8
StatusRequestTimeout = 408 // RFC 9110, 15.5.9
StatusConflict = 409 // RFC 9110, 15.5.10
StatusGone = 410 // RFC 9110, 15.5.11
StatusLengthRequired = 411 // RFC 9110, 15.5.12
StatusPreconditionFailed = 412 // RFC 9110, 15.5.13
StatusRequestEntityTooLarge = 413 // RFC 9110, 15.5.14
StatusRequestURITooLong = 414 // RFC 9110, 15.5.15
StatusUnsupportedMediaType = 415 // RFC 9110, 15.5.16
StatusRequestedRangeNotSatisfiable = 416 // RFC 9110, 15.5.17
StatusExpectationFailed = 417 // RFC 9110, 15.5.18
StatusTeapot = 418 // RFC 9110, 15.5.19 (Unused)
StatusMisdirectedRequest = 421 // RFC 9110, 15.5.20
StatusUnprocessableEntity = 422 // RFC 9110, 15.5.21
StatusLocked = 423 // RFC 4918, 11.3
StatusFailedDependency = 424 // RFC 4918, 11.4
StatusTooEarly = 425 // RFC 8470, 5.2.
StatusUpgradeRequired = 426 // RFC 9110, 15.5.22
StatusPreconditionRequired = 428 // RFC 6585, 3
StatusTooManyRequests = 429 // RFC 6585, 4
StatusRequestHeaderFieldsTooLarge = 431 // RFC 6585, 5
StatusUnavailableForLegalReasons = 451 // RFC 7725, 3
StatusInternalServerError = 500 // RFC 9110, 15.6.1
StatusNotImplemented = 501 // RFC 9110, 15.6.2
StatusBadGateway = 502 // RFC 9110, 15.6.3
StatusServiceUnavailable = 503 // RFC 9110, 15.6.4
StatusGatewayTimeout = 504 // RFC 9110, 15.6.5
StatusHTTPVersionNotSupported = 505 // RFC 9110, 15.6.6
StatusVariantAlsoNegotiates = 506 // RFC 2295, 8.1
StatusInsufficientStorage = 507 // RFC 4918, 11.5
StatusLoopDetected = 508 // RFC 5842, 7.2
StatusNotExtended = 510 // RFC 2774, 7
StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6
) DefaultMaxHeaderBytes — максимальный разрешенный размер заголовков в HTTP-запросе. Это можно переопределить, установив [Server.MaxHeaderBytes].
const DefaultMaxHeaderBytes = 1 << 20 // 1 MB
DefaultMaxIdleConnsPerHost — значение по умолчанию для MaxIdleConnsPerHost в Transport.
const DefaultMaxIdleConnsPerHost = 2
TimeFormat — формат времени, используемый при генерации времени в заголовках HTTP. Он похож на time.RFC1123, но жестко задаёт часовой пояс GMT. Время, которое форматируется, должно быть в UTC, чтобы Format генерировал правильный формат.
Для разбора этого формата времени см. ParseTime.
const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"
TrailerPrefix — магический префикс для ключей карты [ResponseWriter.Header], который, если присутствует, сигнализирует о том, что запись в карте предназначена для трейлеров ответа, а не для заголовков ответа. Префикс удаляется после завершения вызова ServeHTTP, а значения отправляются в трейлерах.
Этот механизм предназначен только для трейлеров, которые неизвестны до записи заголовков. Если набор трейлеров фиксирован или известен до записи заголовка, предпочтительнее использовать стандартный механизм трейлеров Go:
https://pkg.go.dev/net/http#ResponseWriter https://pkg.go.dev/net/http#example-ResponseWriter-Trailers
const TrailerPrefix = "Trailer:"
Переменные
var (
// ErrNotSupported indicates that a feature is not supported.
//
// It is returned by ResponseController methods to indicate that
// the handler does not support the method, and by the Push method
// of Pusher implementations to indicate that HTTP/2 Push support
// is not available.
ErrNotSupported = &ProtocolError{"feature not supported"}
// Deprecated: ErrUnexpectedTrailer is no longer returned by
// anything in the net/http package. Callers should not
// compare errors against this variable.
ErrUnexpectedTrailer = &ProtocolError{"trailer header without chunked transfer encoding"}
// ErrMissingBoundary is returned by Request.MultipartReader when the
// request's Content-Type does not include a "boundary" parameter.
ErrMissingBoundary = &ProtocolError{"no multipart boundary param in Content-Type"}
// ErrNotMultipart is returned by Request.MultipartReader when the
// request's Content-Type is not multipart/form-data.
ErrNotMultipart = &ProtocolError{"request Content-Type isn't multipart/form-data"}
// Deprecated: ErrHeaderTooLong is no longer returned by
// anything in the net/http package. Callers should not
// compare errors against this variable.
ErrHeaderTooLong = &ProtocolError{"header too long"}
// Deprecated: ErrShortBody is no longer returned by
// anything in the net/http package. Callers should not
// compare errors against this variable.
ErrShortBody = &ProtocolError{"entity body too short"}
// Deprecated: ErrMissingContentLength is no longer returned by
// anything in the net/http package. Callers should not
// compare errors against this variable.
ErrMissingContentLength = &ProtocolError{"missing ContentLength in HEAD response"}
) Ошибки, используемые HTTP-сервером.
var (
// ErrBodyNotAllowed is returned by ResponseWriter.Write calls
// when the HTTP method or response code does not permit a
// body.
ErrBodyNotAllowed = errors.New("http: request method or response status code does not allow body")
// ErrHijacked is returned by ResponseWriter.Write calls when
// the underlying connection has been hijacked using the
// Hijacker interface. A zero-byte write on a hijacked
// connection will return ErrHijacked without any other side
// effects.
ErrHijacked = errors.New("http: connection has been hijacked")
// ErrContentLength is returned by ResponseWriter.Write calls
// when a Handler set a Content-Length response header with a
// declared size and then attempted to write more bytes than
// declared.
ErrContentLength = errors.New("http: wrote more than the declared Content-Length")
// Deprecated: ErrWriteAfterFlush is no longer returned by
// anything in the net/http package. Callers should not
// compare errors against this variable.
ErrWriteAfterFlush = errors.New("unused")
) var (
// ServerContextKey is a context key. It can be used in HTTP
// handlers with Context.Value to access the server that
// started the handler. The associated value will be of
// type *Server.
ServerContextKey = &contextKey{"http-server"}
// LocalAddrContextKey is a context key. It can be used in
// HTTP handlers with Context.Value to access the local
// address the connection arrived on.
// The associated value will be of type net.Addr.
LocalAddrContextKey = &contextKey{"local-addr"}
) DefaultClient — клиент Client по умолчанию и используется в Get, Head и Post.
var DefaultClient = &Client{} DefaultServeMux — ServeMux по умолчанию, используемый в Serve.
var DefaultServeMux = &defaultServeMux
ErrAbortHandler — значение паники-маяка для прерывания обработчика. Хотя любая паника из ServeHTTP прерывает ответ клиенту, паника с ErrAbortHandler также подавляет запись стека отладки в журнал ошибок сервера.
var ErrAbortHandler = errors.New("net/http: abort Handler") ErrBodyReadAfterClose возвращается при чтении тела Request или Response после закрытия тела. Это обычно происходит, когда тело читается после того, как HTTP Handler вызывает WriteHeader или Write на своем ResponseWriter.
var ErrBodyReadAfterClose = errors.New("http: invalid Read on closed Body") ErrHandlerTimeout возвращается при вызовах Write в ResponseWriter в обработчиках, у которых истекло время ожидания.
var ErrHandlerTimeout = errors.New("http: Handler timeout") ErrLineTooLong возвращается при чтении тел запросов или ответов с неправильной кодировкой chunked.
var ErrLineTooLong = internal.ErrLineTooLong
ErrMissingFile возвращается методом FormFile, когда указанное имя поля файла отсутствует в запросе или не является полем файла.
var ErrMissingFile = errors.New("http: no such file") ErrNoCookie возвращается методом Cookie запроса, когда cookie не найден.
var ErrNoCookie = errors.New("http: named cookie not present") ErrNoLocation возвращается методом Response.Location, когда заголовок Location отсутствует.
var ErrNoLocation = errors.New("http: no Location header in response") ErrSchemeMismatch возвращается, когда сервер возвращает HTTP-ответ клиенту HTTPS.
var ErrSchemeMismatch = errors.New("http: server gave HTTP response to HTTPS client") ErrServerClosed возвращается методами Server.Serve, ServeTLS, ListenAndServe и ListenAndServeTLS после вызова Server.Shutdown или Server.Close.
var ErrServerClosed = errors.New("http: Server closed") ErrSkipAltProtocol — значение ошибки-маяка, определённое в Transport.RegisterProtocol.
var ErrSkipAltProtocol = errors.New("net/http: skip alternate protocol") ErrUseLastResponse может возвращаться крючками Client.CheckRedirect для управления обработкой перенаправлений. Если возвращается, следующий запрос не отправляется, и возвращается последний ответ с незакрытым телом.
var ErrUseLastResponse = errors.New("net/http: use last response") NoBody — io.ReadCloser без байтов. Чтение всегда возвращает EOF, а закрытие всегда возвращает nil. Он может использоваться в исходящем запросе клиента, чтобы явно указать, что запрос содержит ноль байтов. Однако альтернативой является просто установка [Request.Body] в nil.
var NoBody = noBody{} func CanonicalHeaderKey
func CanonicalHeaderKey(s string) string
CanonicalHeaderKey возвращает канонический формат ключа заголовка s. Канонизация преобразует первую букву и любую букву после дефиса в верхний регистр; остальные преобразуются в нижний регистр. Например, канонический ключ для «accept-encoding» — «Accept-Encoding». Если s содержит пробел или неверные байты поля заголовка, он возвращается без изменений.
func DetectContentType
func DetectContentType(data []byte) string
DetectContentType реализует алгоритм, описанный в https://mimesniff.spec.whatwg.org/, для определения типа Content-Type заданных данных. Он рассматривает не более первых 512 байт данных. DetectContentType всегда возвращает допустимый MIME-тип: если он не может определить более специфический, он возвращает «application/octet-stream».
func Error
func Error(w ResponseWriter, error string, code int)
Error отвечает на запрос с указанным сообщением об ошибке и кодом HTTP. В противном случае запрос не завершается; вызывающий должен убедиться, что дальнейшие записи в w не выполняются. Сообщение об ошибке должно быть текстом.
Error удаляет заголовок Content-Length, устанавливает Content-Type в «text/plain; charset=utf-8» и X-Content-Type-Options в «nosniff». Это должным образом настраивает заголовок для сообщения об ошибке в случае, если вызывающий установил его, ожидая успешного вывода.
func Handle
func Handle(pattern string, handler Handler)
Handle регистрирует обработчик для заданного шаблона в DefaultServeMux. Документация для ServeMux объясняет, как выполняются сопоставления шаблонов.
Пример
Код:
package http_test
import (
"fmt"
"log"
"net/http"
"sync"
)
type countHandler struct {
mu sync.Mutex // guards n
n int
}
func (h *countHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.mu.Lock()
defer h.mu.Unlock()
h.n++
fmt.Fprintf(w, "count is %d\n", h.n)
}
func ExampleHandle() {
http.Handle("/count", new(countHandler))
log.Fatal(http.ListenAndServe(":8080", nil))
}
func HandleFunc
func HandleFunc(pattern string, handler func(ResponseWriter, *Request))
HandleFunc регистрирует функцию-обработчик для заданного шаблона в DefaultServeMux. Документация для ServeMux объясняет, как выполняются сопоставления шаблонов.
Пример
Код:
h1 := func(w http.ResponseWriter, _ *http.Request) {
io.WriteString(w, "Hello from a HandleFunc #1!\n")
}
h2 := func(w http.ResponseWriter, _ *http.Request) {
io.WriteString(w, "Hello from a HandleFunc #2!\n")
}
http.HandleFunc("/", h1)
http.HandleFunc("/endpoint", h2)
log.Fatal(http.ListenAndServe(":8080", nil))
func ListenAndServe
func ListenAndServe(addr string, handler Handler) error
ListenAndServe прослушивает адрес сети TCP addr и затем вызывает Serve с обработчиком для обработки запросов по входящим подключениям. Принятые подключения настраиваются для включения TCP keep-alives.
Обработчик обычно равен nil, в этом случае используется DefaultServeMux.
ListenAndServe всегда возвращает ошибку, отличную от nil.
Пример
Код:
// Hello world, the web server
helloHandler := func(w http.ResponseWriter, req *http.Request) {
io.WriteString(w, "Hello, world!\n")
}
http.HandleFunc("/hello", helloHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
func ListenAndServeTLS
func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error
ListenAndServeTLS работает аналогично ListenAndServe, за исключением того, что он ожидает HTTPS-подключения. Кроме того, должны быть предоставлены файлы, содержащие сертификат и соответствующий закрытый ключ для сервера. Если сертификат подписан центром сертификации, certFile должен содержать конкатенацию сертификата сервера, всех промежуточных сертификатов и сертификата центра сертификации.
Пример
Код:
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
io.WriteString(w, "Hello, TLS!\n")
})
// One can use generate_cert.go in crypto/tls to generate cert.pem and key.pem.
log.Printf("About to listen on 8443. Go to https://127.0.0.1:8443/")
err := http.ListenAndServeTLS(":8443", "cert.pem", "key.pem", nil)
log.Fatal(err)
func MaxBytesReader
func MaxBytesReader(w ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser
MaxBytesReader похож на io.LimitReader, но предназначен для ограничения размера входящих тел запросов. В отличие от io.LimitReader, MaxBytesReader возвращает ReadCloser, возвращает ошибку, отличную от nil, типа *MaxBytesError для чтения, выходящего за пределы ограничения, и закрывает исходный читатель при вызове метода Close.
MaxBytesReader предотвращает случайное или злонамеренное отправление клиентом большого запроса и растрату ресурсов сервера. При возможности, он сообщает ResponseWriter о закрытии соединения после достижения предела.
func NotFound
func NotFound(w ResponseWriter, r *Request)
NotFound отвечает на запрос ошибкой HTTP 404 not found.
func ParseHTTPVersion
func ParseHTTPVersion(vers string) (major, minor int, ok bool)
ParseHTTPVersion парсит строку версии HTTP в соответствии с RFC 7230, раздел 2.6. «HTTP/1.0» возвращает (1, 0, true). Обратите внимание, что строки без значений младших версий, такие как «HTTP/2», не являются допустимыми.
func ParseTime 1.1
func ParseTime(text string) (t time.Time, err error)
ParseTime парсит заголовок времени (такой как заголовок Date), пробуя каждый из трех форматов, разрешенных HTTP/1.1: TimeFormat, time.RFC850 и time.ANSIC.
func ProxyFromEnvironment
func ProxyFromEnvironment(req *Request) (*url.URL, error)
ProxyFromEnvironment возвращает URL прокси, который следует использовать для данного запроса, как указано переменными среды HTTP_PROXY, HTTPS_PROXY и NO_PROXY (или их строчными вариантами). Запросы используют прокси из переменной среды, соответствующей их схеме, если они не исключены NO_PROXY.
Значения среды могут быть полным URL или «host[:port]», в этом случае предполагается схема «http». Возвращается ошибка, если значение имеет другую форму.
Возвращаются nil URL и nil ошибка, если прокси не определен в среде или прокси не должен использоваться для данного запроса, как определено NO_PROXY.
В качестве особого случая, если req.URL.Host равен «localhost» (с или без номера порта), возвращаются nil URL и nil ошибка.
func ProxyURL
func ProxyURL(fixedURL *url.URL) func(*Request) (*url.URL, error)
ProxyURL возвращает функцию прокси (для использования в Transport), которая всегда возвращает один и тот же URL.
func Redirect
func Redirect(w ResponseWriter, r *Request, url string, code int)
Redirect отвечает на запрос перенаправлением на url, который может быть путем, относительным к пути запроса.
Предоставленный код должен быть в диапазоне 3xx и обычно является StatusMovedPermanently, StatusFound или StatusSeeOther.
Если заголовок Content-Type не был установлен, Redirect устанавливает его в «text/html; charset=utf-8» и записывает небольшой HTML-тело. Установка заголовка Content-Type в любое значение, включая nil, отключает это поведение.
func Serve
func Serve(l net.Listener, handler Handler) error
Serve принимает входящие HTTP-соединения на слушателе l, создавая новую службу goroutine для каждого. Goroutine службы читают запросы и затем вызывают handler для ответа на них.
Handler обычно равен nil, в этом случае используется DefaultServeMux.
Поддержка HTTP/2 включена только в том случае, если Listener возвращает соединения *tls.Conn и они были сконфигурированы с «h2» в TLS Config.NextProtos.
Serve всегда возвращает ошибку, отличную от nil.
func ServeContent
func ServeContent(w ResponseWriter, req *Request, name string, modtime time.Time, content io.ReadSeeker)
ServeContent отвечает на запрос, используя содержимое в предоставленном ReadSeeker. Основное преимущество ServeContent по сравнению с io.Copy заключается в том, что она правильно обрабатывает запросы Range, устанавливает тип MIME и обрабатывает запросы If-Match, If-Unmodified-Since, If-None-Match, If-Modified-Since и If-Range.
Если заголовок Content-Type ответа не установлен, ServeContent сначала пытается определить тип по расширению имени файла, и если это не удается, считывает первый блок содержимого и передает его в DetectContentType. Имя в противном случае не используется; в частности, оно может быть пустым и никогда не отправляется в ответе.
Если modtime не равен нулевому времени или эпохе Unix, ServeContent включает его в заголовок Last-Modified в ответе. Если запрос содержит заголовок If-Modified-Since, ServeContent использует modtime, чтобы решить, нужно ли вообще отправлять содержимое.
Метод Seek содержимого должен работать: ServeContent использует поиск до конца содержимого, чтобы определить его размер. Обратите внимание, что *os.File реализует интерфейс io.ReadSeeker.
Если вызывающая сторона установила заголовок ETag w в формате, определённом RFC 7232, раздел 2.3, ServeContent использует его для обработки запросов с помощью If-Match, If-None-Match или If-Range.
Если при обработке запроса возникает ошибка (например, при обработке неверного запроса range), ServeContent отвечает сообщением об ошибке. По умолчанию ServeContent удаляет заголовки Cache-Control, Content-Encoding, ETag и Last-Modified из ответов об ошибках. Настройка GODEBUG httpservecontentkeepheaders=1 заставляет ServeContent сохранять эти заголовки.
func ServeFile
func ServeFile(w ResponseWriter, r *Request, name string)
ServeFile отвечает на запрос содержимым указанного файла или каталога.
Если предоставленное имя файла или каталога является относительным путем, оно интерпретируется относительно текущего каталога и может восходить к родительским каталогам. Если предоставленное имя создано из пользовательского ввода, оно должно быть обработано перед вызовом ServeFile.
В качестве меры предосторожности, ServeFile отклонит запросы, где r.URL.Path содержит элемент пути «..»; это защищает от вызывающих сторон, которые могут небезопасно использовать filepath.Join на r.URL.Path без его очистки, а затем использовать результат filepath.Join в качестве аргумента имени.
В качестве еще одного специального случая, ServeFile перенаправляет любой запрос, где r.URL.Path заканчивается на «/index.html», на тот же путь без конечного «index.html». Чтобы избежать таких перенаправлений, либо измените путь, либо используйте ServeContent.
Вне этих двух специальных случаев ServeFile не использует r.URL.Path для выбора файла или каталога для обслуживания; используется только файл или каталог, предоставленный в аргументе имени.
func ServeFileFS 1.22
func ServeFileFS(w ResponseWriter, r *Request, fsys fs.FS, name string)
ServeFileFS отвечает на запрос содержимым указанного файла или каталога из файловой системы fsys. Файлы, предоставляемые fsys, должны реализовывать io.Seeker.
Если предоставленное имя создано из пользовательского ввода, оно должно быть обработано перед вызовом ServeFileFS.
В качестве меры предосторожности, ServeFileFS отклонит запросы, где r.URL.Path содержит элемент пути «..»; это защищает от вызывающих сторон, которые могут небезопасно использовать filepath.Join на r.URL.Path без его очистки, а затем использовать результат filepath.Join в качестве аргумента имени.
В качестве еще одного специального случая, ServeFileFS перенаправляет любой запрос, где r.URL.Path заканчивается на «/index.html», на тот же путь без конечного «index.html». Чтобы избежать таких перенаправлений, либо измените путь, либо используйте ServeContent.
Вне этих двух специальных случаев ServeFileFS не использует r.URL.Path для выбора файла или каталога для обслуживания; используется только файл или каталог, предоставленный в аргументе имени.
func ServeTLS 1.9
func ServeTLS(l net.Listener, handler Handler, certFile, keyFile string) error
ServeTLS принимает входящие HTTPS-соединения на слушателе l, создавая новую службу goroutine для каждого. Goroutine службы читают запросы и затем вызывают handler для ответа на них.
Handler обычно равен nil, в этом случае используется DefaultServeMux.
Кроме того, должны быть предоставлены файлы, содержащие сертификат и соответствующий закрытый ключ для сервера. Если сертификат подписан центром сертификации, certFile должен содержать конкатенацию сертификата сервера, всех промежуточных сертификатов и сертификата центра сертификации.
ServeTLS всегда возвращает ошибку, отличную от nil.
func SetCookie
func SetCookie(w ResponseWriter, cookie *Cookie)
SetCookie добавляет заголовок Set-Cookie в заголовки предоставленного ResponseWriter. Предоставленный cookie должен иметь валидное имя. Невалидные cookies могут быть безмолвно удалены.
func StatusText
func StatusText(code int) string
StatusText возвращает текст для кода HTTP состояния. Возвращает пустую строку, если код неизвестен.
type Client
Client — это HTTP-клиент. Его нулевое значение (DefaultClient) — это пригодный к использованию клиент, который использует DefaultTransport.
У [Client.Transport] обычно есть внутреннее состояние (кешированные TCP-соединения), поэтому Clients следует повторно использовать вместо создания по мере необходимости. Clients безопасны для одновременного использования несколькими goroutine.
Client — это более высокий уровень, чем RoundTripper (такой как Transport) и дополнительно обрабатывает HTTP-детали, такие как cookies и перенаправления.
При слежении за перенаправлениями Client будет пересылать все заголовки, установленные в начальном Request, за исключением:
- при пересылке чувствительных заголовков, таких как «Authorization», «WWW-Authenticate» и «Cookie», ненадежным целевым адресам. Эти заголовки будут игнорироваться при перенаправлении на домен, который не является доменным совпадением поддомена или точным совпадением начального домена. Например, перенаправление с «foo.com» на «foo.com» или «sub.foo.com» будет пересылать чувствительные заголовки, но перенаправление на «bar.com» — нет.
- при пересылке заголовка «Cookie» с не-nil cookie Jar. Поскольку каждое перенаправление может изменить состояние cookie jar, перенаправление может изменить cookie, установленный в начальном запросе. При пересылке заголовка «Cookie» любые изменённые cookies будут опущены, с ожиданием, что Jar вставит эти изменённые cookies с обновлёнными значениями (предполагая соответствие источнику). Если Jar равен nil, начальные cookies пересылаются без изменений.
type Client struct {
// Transport specifies the mechanism by which individual
// HTTP requests are made.
// If nil, DefaultTransport is used.
Transport RoundTripper
// CheckRedirect specifies the policy for handling redirects.
// If CheckRedirect is not nil, the client calls it before
// following an HTTP redirect. The arguments req and via are
// the upcoming request and the requests made already, oldest
// first. If CheckRedirect returns an error, the Client's Get
// method returns both the previous Response (with its Body
// closed) and CheckRedirect's error (wrapped in a url.Error)
// instead of issuing the Request req.
// As a special case, if CheckRedirect returns ErrUseLastResponse,
// then the most recent response is returned with its body
// unclosed, along with a nil error.
//
// If CheckRedirect is nil, the Client uses its default policy,
// which is to stop after 10 consecutive requests.
CheckRedirect func(req *Request, via []*Request) error
// Jar specifies the cookie jar.
//
// The Jar is used to insert relevant cookies into every
// outbound Request and is updated with the cookie values
// of every inbound Response. The Jar is consulted for every
// redirect that the Client follows.
//
// If Jar is nil, cookies are only sent if they are explicitly
// set on the Request.
Jar CookieJar
// Timeout specifies a time limit for requests made by this
// Client. The timeout includes connection time, any
// redirects, and reading the response body. The timer remains
// running after Get, Head, Post, or Do return and will
// interrupt reading of the Response.Body.
//
// A Timeout of zero means no timeout.
//
// The Client cancels requests to the underlying Transport
// as if the Request's Context ended.
//
// For compatibility, the Client will also use the deprecated
// CancelRequest method on Transport if found. New
// RoundTripper implementations should use the Request's Context
// for cancellation instead of implementing CancelRequest.
Timeout time.Duration // Go 1.3
}
func (*Client) CloseIdleConnections 1.12
func (c *Client) CloseIdleConnections()
CloseIdleConnections закрывает все соединения на его Transport, которые ранее были подключены из предыдущих запросов, но сейчас находятся в состоянии простоя в состоянии «keep-alive». Она не прерывает соединения, которые в настоящее время используются.
Если [Client.Transport] не имеет метода Client.CloseIdleConnections, то этот метод ничего не делает.
func (*Client) Do
func (c *Client) Do(req *Request) (*Response, error)
Do отправляет HTTP-запрос и возвращает HTTP-ответ, следуя политике (такой как перенаправления, cookies, auth), сконфигурированной в клиенте.
Возвращается ошибка, если она вызвана политикой клиента (например, CheckRedirect) или неудачей в обмене HTTP (например, проблемой сетевого подключения). Код состояния, не являющийся 2xx, не вызывает ошибку.
Если возвращаемая ошибка равна nil, Response будет содержать не-nil Body, который пользователь должен закрыть. Если Body не был прочитан до EOF и закрыт, базовый RoundTripper клиента (обычно Transport) может не быть в состоянии повторно использовать постоянное TCP-соединение с сервером для последующего запроса «keep-alive».
Тело запроса, если оно не равно nil, будет закрыто базовым Transport, даже при ошибках. Тело может быть закрыто асинхронно после возвращения Do.
При ошибке любой Response может быть проигнорирован. Непустой Response с непустой ошибкой возникает только при неудачном выполнении CheckRedirect, и даже тогда возвращаемое [Response.Body] уже закрыто.
Обычно вместо Do используются Get, Post или PostForm.
Если сервер отвечает с перенаправлением, клиент сначала использует функцию CheckRedirect, чтобы определить, следует ли выполнить перенаправление. Если разрешено, перенаправление 301, 302 или 303 приводит к последующим запросам с использованием HTTP-метода GET (или HEAD, если исходный запрос был HEAD), без тела. Перенаправление 307 или 308 сохраняет исходный HTTP-метод и тело, при условии, что определена функция [Request.GetBody]. Функция NewRequest автоматически устанавливает GetBody для распространенных стандартных типов тела.
Любая возвращаемая ошибка будет иметь тип *url.Error. Метод Timeout значения url.Error вернёт true, если запрос истек по времени.
func (*Client) Get
func (c *Client) Get(url string) (resp *Response, err error)
Get отправляет GET-запрос на указанный URL. Если ответ имеет один из следующих кодов перенаправления, Get следует за перенаправлением после вызова функции [Client.CheckRedirect]:
301 (Moved Permanently) 302 (Found) 303 (See Other) 307 (Temporary Redirect) 308 (Permanent Redirect)
Возвращается ошибка, если функция [Client.CheckRedirect] завершается неудачно или произошла ошибка протокола HTTP. Ответ с кодом, не являющимся 2xx, не вызывает ошибку. Любая возвращаемая ошибка будет иметь тип *url.Error. Метод Timeout значения url.Error вернёт true, если запрос истек по времени.
Когда err равен nil, resp всегда содержит непустой resp.Body. Вызывающая сторона должна закрыть resp.Body после завершения чтения из него.
Для отправки запроса с пользовательскими заголовками используйте NewRequest и Client.Do.
Для отправки запроса со значением контекста context.Context используйте NewRequestWithContext и Client.Do.
func (*Client) Head
func (c *Client) Head(url string) (resp *Response, err error)
Head отправляет запрос HEAD на указанный URL. Если ответ имеет один из следующих кодов перенаправления, Head следует за перенаправлением после вызова функции [Client.CheckRedirect]:
301 (Moved Permanently) 302 (Found) 303 (See Other) 307 (Temporary Redirect) 308 (Permanent Redirect)
Для отправки запроса со значением context.Context используйте NewRequestWithContext и Client.Do.
func (*Client) Post
func (c *Client) Post(url, contentType string, body io.Reader) (resp *Response, err error)
Post отправляет POST-запрос на указанный URL.
Вызывающая сторона должна закрыть resp.Body после завершения чтения из него.
Если предоставленное тело является io.Closer, оно закрывается после запроса.
Для установки пользовательских заголовков используйте NewRequest и Client.Do.
Для отправки запроса со значением контекста context.Context используйте NewRequestWithContext и Client.Do.
Подробности о том, как обрабатываются перенаправления, см. в документации метода Client.Do.
func (*Client) PostForm
func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error)
PostForm отправляет POST-запрос на указанный URL, данные ключей и значений которого кодируются в URL-символы в качестве тела запроса.
Заголовок Content-Type установлен в application/x-www-form-urlencoded. Чтобы установить другие заголовки, используйте NewRequest и Client.Do.
Когда err равен nil, resp всегда содержит непустой resp.Body. Вызывающая сторона должна закрыть resp.Body после завершения чтения из него.
Подробности о том, как обрабатываются перенаправления, см. в документации метода Client.Do.
Для отправки запроса со значением контекста context.Context используйте NewRequestWithContext и Client.Do.
type CloseNotifier 1.1
Интерфейс CloseNotifier реализуется ResponseWriters, позволяющими обнаруживать, когда основное подключение прервано.
Этот механизм может использоваться для отмены длительных операций на сервере, если клиент отключился до готовности ответа.
Устаревший: интерфейс CloseNotifier предшествует пакету контекстов Go. Новый код должен использовать Request.Context вместо него.
type CloseNotifier interface {
// CloseNotify returns a channel that receives at most a
// single value (true) when the client connection has gone
// away.
//
// CloseNotify may wait to notify until Request.Body has been
// fully read.
//
// After the Handler has returned, there is no guarantee
// that the channel receives a value.
//
// If the protocol is HTTP/1.1 and CloseNotify is called while
// processing an idempotent request (such as GET) while
// HTTP/1.1 pipelining is in use, the arrival of a subsequent
// pipelined request may cause a value to be sent on the
// returned channel. In practice HTTP/1.1 pipelining is not
// enabled in browsers and not seen often in the wild. If this
// is a problem, use HTTP/2 or only use CloseNotify on methods
// such as POST.
CloseNotify() <-chan bool
} type ConnState 1.3
ConnState представляет состояние клиентского подключения к серверу. Он используется необязательным крючком [Server.ConnState].
type ConnState int
const (
// StateNew represents a new connection that is expected to
// send a request immediately. Connections begin at this
// state and then transition to either StateActive or
// StateClosed.
StateNew ConnState = iota
// StateActive represents a connection that has read 1 or more
// bytes of a request. The Server.ConnState hook for
// StateActive fires before the request has entered a handler
// and doesn't fire again until the request has been
// handled. After the request is handled, the state
// transitions to StateClosed, StateHijacked, or StateIdle.
// For HTTP/2, StateActive fires on the transition from zero
// to one active request, and only transitions away once all
// active requests are complete. That means that ConnState
// cannot be used to do per-request work; ConnState only notes
// the overall state of the connection.
StateActive
// StateIdle represents a connection that has finished
// handling a request and is in the keep-alive state, waiting
// for a new request. Connections transition from StateIdle
// to either StateActive or StateClosed.
StateIdle
// StateHijacked represents a hijacked connection.
// This is a terminal state. It does not transition to StateClosed.
StateHijacked
// StateClosed represents a closed connection.
// This is a terminal state. Hijacked connections do not
// transition to StateClosed.
StateClosed
) func (ConnState) String 1.3
func (c ConnState) String() string
type Cookie
Cookie представляет HTTP-cookie, как отправленный в заголовке Set-Cookie HTTP-ответа или заголовке Cookie HTTP-запроса.
Подробности см. в https://tools.ietf.org/html/rfc6265.
type Cookie struct {
Name string
Value string
Quoted bool // indicates whether the Value was originally quoted; added in Go 1.23
Path string // optional
Domain string // optional
Expires time.Time // optional
RawExpires string // for reading cookies only
// MaxAge=0 means no 'Max-Age' attribute specified.
// MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'
// MaxAge>0 means Max-Age attribute present and given in seconds
MaxAge int
Secure bool
HttpOnly bool
SameSite SameSite // Go 1.11
Partitioned bool // Go 1.23
Raw string
Unparsed []string // Raw text of unparsed attribute-value pairs
}
func ParseCookie 1.23
func ParseCookie(line string) ([]*Cookie, error)
ParseCookie анализирует значение заголовка Cookie и возвращает все cookie, которые были установлены в нем. Поскольку одно и то же имя cookie может появляться несколько раз, возвращаемые значения могут содержать более одного значения для данного ключа.
func ParseSetCookie 1.23
func ParseSetCookie(line string) (*Cookie, error)
ParseSetCookie анализирует значение заголовка Set-Cookie и возвращает cookie. Возвращает ошибку при синтаксической ошибке.
func (*Cookie) String
func (c *Cookie) String() string
String возвращает сериализацию cookie для использования в заголовке Cookie (если установлены только Name и Value) или заголовке ответа Set-Cookie (если установлены другие поля). Если c равен nil или c.Name некорректен, возвращается пустая строка.
func (*Cookie) Valid 1.18
func (c *Cookie) Valid() error
Valid сообщает, является ли cookie валидным.
type CookieJar
CookieJar управляет хранением и использованием cookie в HTTP-запросах.
Реализации CookieJar должны быть безопасными для одновременного использования несколькими горутинами.
Пакет net/http/cookiejar предоставляет реализацию CookieJar.
type CookieJar interface {
// SetCookies handles the receipt of the cookies in a reply for the
// given URL. It may or may not choose to save the cookies, depending
// on the jar's policy and implementation.
SetCookies(u *url.URL, cookies []*Cookie)
// Cookies returns the cookies to send in a request for the given URL.
// It is up to the implementation to honor the standard cookie use
// restrictions such as in RFC 6265.
Cookies(u *url.URL) []*Cookie
} type Dir
Dir реализует FileSystem с использованием файловой системы, ограниченной определённым деревом каталогов.
Хотя метод [FileSystem.Open] принимает пути, разделенные '/', строковое значение Dir — это путь к каталогу в файловой системе, а не URL, поэтому он разделяется с помощью filepath.Separator, который необязательно равен '/'.
Обратите внимание, что Dir может раскрывать конфиденциальные файлы и каталоги. Dir будет следовать символичным ссылкам, выходящим за пределы древовидной структуры каталогов, что может быть особенно опасно при обслуживании из каталога, в котором пользователи могут создавать произвольные символьные ссылки. Dir также разрешит доступ к файлам и каталогам, начинающимся с точки, что может раскрыть конфиденциальные каталоги, такие как .git, или конфиденциальные файлы, такие как .htpasswd. Чтобы исключить файлы с ведущей точкой, удалите файлы/каталоги с сервера или создайте собственную реализацию FileSystem.
Пустой Dir рассматривается как «.».
type Dir string
func (Dir) Open
func (d Dir) Open(name string) (File, error)
Open реализует FileSystem с использованием os.Open, открывая файлы для чтения, корневой и относительной к каталогу d.
type File
File возвращается методом Open FileSystem и может быть обработан реализацией FileServer.
Методы должны вести себя так же, как и методы *os.File.
type File interface {
io.Closer
io.Reader
io.Seeker
Readdir(count int) ([]fs.FileInfo, error)
Stat() (fs.FileInfo, error)
} type FileSystem
FileSystem реализует доступ к набору именованных файлов. Элементы в пути к файлу разделяются косой чертой ('/', U+002F) независимо от конвенций операционной системы хоста. См. функцию FileServer для преобразования FileSystem в Handler.
Этот интерфейс предшествует интерфейсу fs.FS, который можно использовать вместо него: функция адаптера FS преобразует fs.FS в FileSystem.
type FileSystem interface {
Open(name string) (File, error)
} func FS 1.16
func FS(fsys fs.FS) FileSystem
FS преобразует fsys в реализацию FileSystem для использования с FileServer и NewFileTransport. Файлы, предоставляемые fsys, должны реализовывать io.Seeker.
type Flusher
Интерфейс Flusher реализуется ResponseWriters, которые позволяют HTTP-обработчику очищать буферизованные данные для клиента.
Стандартные реализации HTTP/1.x и HTTP/2 ResponseWriter поддерживают Flusher, но оболочки ResponseWriter могут не поддерживать. Обработчики всегда должны проверять эту возможность во время выполнения.
Обратите внимание, что даже для ResponseWriters, которые поддерживают Flush, если клиент подключён через HTTP-прокси, буферизованные данные могут не достичь клиента до завершения ответа.
type Flusher interface {
// Flush sends any buffered data to the client.
Flush()
} type HTTP2Config 1.24
HTTP2Config определяет параметры конфигурации HTTP/2, общие для Transport и Server.
type HTTP2Config struct {
// MaxConcurrentStreams optionally specifies the number of
// concurrent streams that a peer may have open at a time.
// If zero, MaxConcurrentStreams defaults to at least 100.
MaxConcurrentStreams int
// MaxDecoderHeaderTableSize optionally specifies an upper limit for the
// size of the header compression table used for decoding headers sent
// by the peer.
// A valid value is less than 4MiB.
// If zero or invalid, a default value is used.
MaxDecoderHeaderTableSize int
// MaxEncoderHeaderTableSize optionally specifies an upper limit for the
// header compression table used for sending headers to the peer.
// A valid value is less than 4MiB.
// If zero or invalid, a default value is used.
MaxEncoderHeaderTableSize int
// MaxReadFrameSize optionally specifies the largest frame
// this endpoint is willing to read.
// A valid value is between 16KiB and 16MiB, inclusive.
// If zero or invalid, a default value is used.
MaxReadFrameSize int
// MaxReceiveBufferPerConnection is the maximum size of the
// flow control window for data received on a connection.
// A valid value is at least 64KiB and less than 4MiB.
// If invalid, a default value is used.
MaxReceiveBufferPerConnection int
// MaxReceiveBufferPerStream is the maximum size of
// the flow control window for data received on a stream (request).
// A valid value is less than 4MiB.
// If zero or invalid, a default value is used.
MaxReceiveBufferPerStream int
// SendPingTimeout is the timeout after which a health check using a ping
// frame will be carried out if no frame is received on a connection.
// If zero, no health check is performed.
SendPingTimeout time.Duration
// PingTimeout is the timeout after which a connection will be closed
// if a response to a ping is not received.
// If zero, a default of 15 seconds is used.
PingTimeout time.Duration
// WriteByteTimeout is the timeout after which a connection will be
// closed if no data can be written to it. The timeout begins when data is
// available to write, and is extended whenever any bytes are written.
WriteByteTimeout time.Duration
// PermitProhibitedCipherSuites, if true, permits the use of
// cipher suites prohibited by the HTTP/2 spec.
PermitProhibitedCipherSuites bool
// CountError, if non-nil, is called on HTTP/2 errors.
// It is intended to increment a metric for monitoring.
// The errType contains only lowercase letters, digits, and underscores
// (a-z, 0-9, _).
CountError func(errType string)
}
type Handler
Handler отвечает на HTTP-запрос.
[Handler.ServeHTTP] должен записать заголовки ответа и данные в ResponseWriter, а затем вернуть значение. Возвращение сигнализирует о завершении запроса; использование ResponseWriter или чтение из [Request.Body] после или одновременно с завершением вызова ServeHTTP некорректно.
В зависимости от программного обеспечения HTTP-клиента, версии HTTP-протокола и любых посредников между клиентом и сервером Go, чтение из [Request.Body] после записи в ResponseWriter может быть невозможно. Осторожные обработчики должны сначала прочитать [Request.Body], а затем ответить.
За исключением чтения тела, обработчики не должны изменять предоставленный запрос.
Если ServeHTTP вызывает панику, сервер (вызывающий метод ServeHTTP) предполагает, что эффект паники был изолирован для активного запроса. Он восстанавливает панику, регистрирует трассировку стека в журнал ошибок сервера и либо закрывает сетевое соединение, либо отправляет HTTP/2 RST_STREAM, в зависимости от HTTP-протокола. Чтобы прервать обработчик, чтобы клиент видел прерванный ответ, но сервер не регистрировал ошибку, вызовите панику со значением ErrAbortHandler.
type Handler interface {
ServeHTTP(ResponseWriter, *Request)
} func AllowQuerySemicolons 1.17
func AllowQuerySemicolons(h Handler) Handler
AllowQuerySemicolons возвращает обработчик, который обрабатывает запросы путём преобразования любого незаэкранированного знака «точка с запятой» в строке запроса URL в амперсанды и вызова обработчика h.
Это восстанавливает поведение до Go 1.17, когда параметры запроса разделялись как точками с запятой, так и амперсандом. (См. golang.org/issue/25192). Обратите внимание, что это поведение не соответствует поведению многих прокси, и расхождение может привести к проблемам безопасности.
AllowQuerySemicolons должен вызываться до вызова Request.ParseForm.
func FileServer
func FileServer(root FileSystem) Handler
FileServer возвращает обработчик, который обслуживает HTTP-запросы с содержимым файловой системы, укоренённой в root.
В качестве специального случая, возвращаемый файловый сервер перенаправляет любые запросы, оканчивающиеся на "/index.html", на тот же путь, без заключительного "index.html".
Для использования реализации файловой системы операционной системы, используйте http.Dir:
http.Handle("/", http.FileServer(http.Dir("/tmp")))
Чтобы использовать реализацию fs.FS, используйте http.FileServerFS вместо этого.
Пример
Код:
// Simple static webserver:
log.Fatal(http.ListenAndServe(":8080", http.FileServer(http.Dir("/usr/share/doc"))))
Пример (DotFileHiding)
Код:
package http_test
import (
"io"
"io/fs"
"log"
"net/http"
"strings"
)
// containsDotFile reports whether name contains a path element starting with a period.
// The name is assumed to be a delimited by forward slashes, as guaranteed
// by the http.FileSystem interface.
func containsDotFile(name string) bool {
parts := strings.Split(name, "/")
for _, part := range parts {
if strings.HasPrefix(part, ".") {
return true
}
}
return false
}
// dotFileHidingFile is the http.File use in dotFileHidingFileSystem.
// It is used to wrap the Readdir method of http.File so that we can
// remove files and directories that start with a period from its output.
type dotFileHidingFile struct {
http.File
}
// Readdir is a wrapper around the Readdir method of the embedded File
// that filters out all files that start with a period in their name.
func (f dotFileHidingFile) Readdir(n int) (fis []fs.FileInfo, err error) {
files, err := f.File.Readdir(n)
for _, file := range files { // Filters out the dot files
if !strings.HasPrefix(file.Name(), ".") {
fis = append(fis, file)
}
}
if err == nil && n > 0 && len(fis) == 0 {
err = io.EOF
}
return
}
// dotFileHidingFileSystem is an http.FileSystem that hides
// hidden "dot files" from being served.
type dotFileHidingFileSystem struct {
http.FileSystem
}
// Open is a wrapper around the Open method of the embedded FileSystem
// that serves a 403 permission error when name has a file or directory
// with whose name starts with a period in its path.
func (fsys dotFileHidingFileSystem) Open(name string) (http.File, error) {
if containsDotFile(name) { // If dot file, return 403 response
return nil, fs.ErrPermission
}
file, err := fsys.FileSystem.Open(name)
if err != nil {
return nil, err
}
return dotFileHidingFile{file}, err
}
func ExampleFileServer_dotFileHiding() {
fsys := dotFileHidingFileSystem{http.Dir(".")}
http.Handle("/", http.FileServer(fsys))
log.Fatal(http.ListenAndServe(":8080", nil))
}
Пример (StripPrefix)
Код:
// To serve a directory on disk (/tmp) under an alternate URL
// path (/tmpfiles/), use StripPrefix to modify the request
// URL's path before the FileServer sees it:
http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
func FileServerFS 1.22
func FileServerFS(root fs.FS) Handler
FileServerFS возвращает обработчик, который обслуживает HTTP-запросы с содержимым файловой системы fsys. Файлы, предоставленные fsys, должны реализовывать io.Seeker.
В качестве специального случая, возвращаемый файловый сервер перенаправляет любые запросы, оканчивающиеся на "/index.html", на тот же путь, без заключительного "index.html".
http.Handle("/", http.FileServerFS(fsys))
func MaxBytesHandler 1.18
func MaxBytesHandler(h Handler, n int64) Handler
MaxBytesHandler возвращает Handler, который выполняет h с его ResponseWriter и [Request.Body], обернутым MaxBytesReader.
func NotFoundHandler
func NotFoundHandler() Handler
NotFoundHandler возвращает простой обработчик запросов, который отвечает на каждый запрос ответом «404 страница не найдена».
Пример
Код:
mux := http.NewServeMux()
// Create sample handler to returns 404
mux.Handle("/resources", http.NotFoundHandler())
// Create sample handler that returns 200
mux.Handle("/resources/people/", newPeopleHandler())
log.Fatal(http.ListenAndServe(":8080", mux))
func RedirectHandler
func RedirectHandler(url string, code int) Handler
RedirectHandler возвращает обработчик запросов, который перенаправляет каждый полученный запрос на указанный url с использованием заданного кода состояния.
Указанный код должен быть в диапазоне 3xx и обычно представляет собой StatusMovedPermanently, StatusFound или StatusSeeOther.
func StripPrefix
func StripPrefix(prefix string, h Handler) Handler
StripPrefix возвращает обработчик, который обрабатывает HTTP-запросы путём удаления заданного префикса из пути URL-запроса (и RawPath, если он задан) и вызова обработчика h. StripPrefix обрабатывает запрос на путь, который не начинается с префикса, отвечая ошибкой HTTP 404 не найдено. Префикс должен точно совпадать: если префикс в запросе содержит экранированные символы, ответом также будет ошибка HTTP 404 не найдено.
Пример
Код:
// To serve a directory on disk (/tmp) under an alternate URL
// path (/tmpfiles/), use StripPrefix to modify the request
// URL's path before the FileServer sees it:
http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
func TimeoutHandler
func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler
TimeoutHandler возвращает Handler, который выполняет h с заданным лимитом времени.
Новый обработчик вызывает h.ServeHTTP для обработки каждого запроса, но если вызов работает дольше, чем заданный лимит времени, обработчик отвечает ошибкой 503 Сервис недоступен и указанным сообщением в своём теле. (Если msg пуст, будет отправлено подходящее сообщение по умолчанию.) После такого таймаута записи h в его ResponseWriter вернут ErrHandlerTimeout.
TimeoutHandler поддерживает интерфейс Pusher, но не поддерживает интерфейсы Hijacker или Flusher.
тип HandlerFunc
Тип HandlerFunc является адаптером, позволяющим использовать обычные функции в качестве обработчиков HTTP. Если f — функция с соответствующей сигнатурой, HandlerFunc(f) — Handler, который вызывает f.
type HandlerFunc func(ResponseWriter, *Request)
func (HandlerFunc) ServeHTTP
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request)
ServeHTTP вызывает f(w, r).
тип Header
Header представляет собой пары ключ-значение в HTTP-заголовке.
Ключи должны быть в канонической форме, как возвращается CanonicalHeaderKey.
type Header map[string][]string
func (Header) Add
func (h Header) Add(key, value string)
Add добавляет пару ключ-значение в заголовок. Она добавляет к существующим значениям, связанным с ключом. Ключ нечувствителен к регистру; он канонизируется с помощью CanonicalHeaderKey.
func (Header) Clone 1.13
func (h Header) Clone() Header
Clone возвращает копию h или nil, если h равно nil.
func (Header) Del
func (h Header) Del(key string)
Del удаляет значения, связанные с ключом. Ключ нечувствителен к регистру; он канонизируется с помощью CanonicalHeaderKey.
func (Header) Get
func (h Header) Get(key string) string
Get получает первое значение, связанное с данным ключом. Если значений, связанных с ключом, нет, Get возвращает "". Нечувствительно к регистру; используется textproto.CanonicalMIMEHeaderKey для канонизации предоставленного ключа. Get предполагает, что все ключи хранятся в канонической форме. Чтобы использовать неканонические ключи, обратитесь к карте напрямую.
func (Header) Set
func (h Header) Set(key, value string)
Set устанавливает записи заголовков, связанные с ключом, на единственное значение value. Она заменяет любые существующие значения, связанные с ключом. Ключ нечувствителен к регистру; он канонизируется с помощью textproto.CanonicalMIMEHeaderKey. Чтобы использовать неканонические ключи, назначьте значение в карту напрямую.
func (Header) Values 1.14
func (h Header) Values(key string) []string
Values возвращает все значения, связанные с данным ключом. Нечувствительно к регистру; используется textproto.CanonicalMIMEHeaderKey для канонизации предоставленного ключа. Чтобы использовать неканонические ключи, обратитесь к карте напрямую. Возвращаемый срез не является копией.
func (Header) Write
func (h Header) Write(w io.Writer) error
Write записывает заголовок в формате wire.
func (Header) WriteSubset
func (h Header) WriteSubset(w io.Writer, exclude map[string]bool) error
WriteSubset записывает заголовок в формате wire. Если exclude не равен nil, ключи, где exclude[key] == true, не записываются. Ключи не канонизируются перед проверкой карты exclude.
тип Hijacker
Интерфейс Hijacker реализуется ResponseWriter, которые позволяют обработчику HTTP захватить соединение.
По умолчанию ResponseWriter для соединений HTTP/1.x поддерживает Hijacker, но соединения HTTP/2 намеренно не поддерживают. Обёртки ResponseWriter также могут не поддерживать Hijacker. Обработчики должны всегда проверять эту возможность во время выполнения.
type Hijacker interface {
// Hijack lets the caller take over the connection.
// After a call to Hijack the HTTP server library
// will not do anything else with the connection.
//
// It becomes the caller's responsibility to manage
// and close the connection.
//
// The returned net.Conn may have read or write deadlines
// already set, depending on the configuration of the
// Server. It is the caller's responsibility to set
// or clear those deadlines as needed.
//
// The returned bufio.Reader may contain unprocessed buffered
// data from the client.
//
// After a call to Hijack, the original Request.Body must not
// be used. The original Request's Context remains valid and
// is not canceled until the Request's ServeHTTP method
// returns.
Hijack() (net.Conn, *bufio.ReadWriter, error)
} Пример
Код:
http.HandleFunc("/hijack", func(w http.ResponseWriter, r *http.Request) {
hj, ok := w.(http.Hijacker)
if !ok {
http.Error(w, "webserver doesn't support hijacking", http.StatusInternalServerError)
return
}
conn, bufrw, err := hj.Hijack()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Don't forget to close the connection:
defer conn.Close()
bufrw.WriteString("Now we're speaking raw TCP. Say hi: ")
bufrw.Flush()
s, err := bufrw.ReadString('\n')
if err != nil {
log.Printf("error reading string: %v", err)
return
}
fmt.Fprintf(bufrw, "You said: %q\nBye.\n", s)
bufrw.Flush()
})
тип MaxBytesError 1.19
MaxBytesError возвращается MaxBytesReader, когда предел чтения превышен.
type MaxBytesError struct {
Limit int64
}
func (*MaxBytesError) Error 1.19
func (e *MaxBytesError) Error() string
тип ProtocolError
ProtocolError представляет собой ошибку протокола HTTP.
Устаревшее: Не все ошибки в пакете http, связанные с ошибками протокола, являются типа ProtocolError.
type ProtocolError struct {
ErrorString string
}
func (*ProtocolError) Error
func (pe *ProtocolError) Error() string
func (*ProtocolError) Is 1.21
func (pe *ProtocolError) Is(err error) bool
Is позволяет http.ErrNotSupported соответствовать errors.ErrUnsupported.
тип Protocols 1.24
Protocols — набор HTTP-протоколов. Значение по умолчанию — пустой набор протоколов.
Поддерживаемые протоколы:
HTTP1 — протоколы HTTP/1.0 и HTTP/1.1. HTTP1 поддерживается как в незащищённых TCP, так и в защищённых TLS-соединениях.
HTTP2 — протокол HTTP/2 через TLS-соединение.
UnencryptedHTTP2 — протокол HTTP/2 через незащищённое TCP-соединение.
type Protocols struct {
// contains filtered or unexported fields
}
Пример (Http1)
Код:
srv := http.Server{
Addr: ":8443",
}
// Serve only HTTP/1.
srv.Protocols = new(http.Protocols)
srv.Protocols.SetHTTP1(true)
log.Fatal(srv.ListenAndServeTLS("cert.pem", "key.pem"))
Пример (Http1or2)
Код:
t := http.DefaultTransport.(*http.Transport).Clone()
// Use either HTTP/1 and HTTP/2.
t.Protocols = new(http.Protocols)
t.Protocols.SetHTTP1(true)
t.Protocols.SetHTTP2(true)
cli := &http.Client{Transport: t}
res, err := cli.Get("http://www.google.com/robots.txt")
if err != nil {
log.Fatal(err)
}
res.Body.Close()
func (Protocols) HTTP1 1.24
func (p Protocols) HTTP1() bool
HTTP1 сообщает, включает ли p HTTP/1.
func (Protocols) HTTP2 1.24
func (p Protocols) HTTP2() bool
HTTP2 сообщает, включает ли p HTTP/2.
func (*Protocols) SetHTTP1 1.24
func (p *Protocols) SetHTTP1(ok bool)
SetHTTP1 добавляет или удаляет HTTP/1 из p.
func (*Protocols) SetHTTP2 1.24
func (p *Protocols) SetHTTP2(ok bool)
SetHTTP2 добавляет или удаляет HTTP/2 из p.
func (*Protocols) SetUnencryptedHTTP2 1.24
func (p *Protocols) SetUnencryptedHTTP2(ok bool)
SetUnencryptedHTTP2 добавляет или удаляет незащищённый HTTP/2 из p.
func (Protocols) String 1.24
func (p Protocols) String() string
func (Protocols) UnencryptedHTTP2 1.24
func (p Protocols) UnencryptedHTTP2() bool
UnencryptedHTTP2 сообщает, включает ли p незащищённый HTTP/2.
тип PushOptions 1.8
PushOptions описывает параметры для [Pusher.Push].
type PushOptions struct {
// Method specifies the HTTP method for the promised request.
// If set, it must be "GET" or "HEAD". Empty means "GET".
Method string
// Header specifies additional promised request headers. This cannot
// include HTTP/2 pseudo header fields like ":path" and ":scheme",
// which will be added automatically.
Header Header
}
тип Pusher 1.8
Pusher — это интерфейс, реализуемый ResponseWriter, который поддерживает HTTP/2 серверное отображение. Дополнительную информацию см. в https://tools.ietf.org/html/rfc7540#section-8.2.
type Pusher interface {
// Push initiates an HTTP/2 server push. This constructs a synthetic
// request using the given target and options, serializes that request
// into a PUSH_PROMISE frame, then dispatches that request using the
// server's request handler. If opts is nil, default options are used.
//
// The target must either be an absolute path (like "/path") or an absolute
// URL that contains a valid host and the same scheme as the parent request.
// If the target is a path, it will inherit the scheme and host of the
// parent request.
//
// The HTTP/2 spec disallows recursive pushes and cross-authority pushes.
// Push may or may not detect these invalid pushes; however, invalid
// pushes will be detected and canceled by conforming clients.
//
// Handlers that wish to push URL X should call Push before sending any
// data that may trigger a request for URL X. This avoids a race where the
// client issues requests for X before receiving the PUSH_PROMISE for X.
//
// Push will run in a separate goroutine making the order of arrival
// non-deterministic. Any required synchronization needs to be implemented
// by the caller.
//
// Push returns ErrNotSupported if the client has disabled push or if push
// is not supported on the underlying connection.
Push(target string, opts *PushOptions) error
} тип Request
Request представляет собой HTTP-запрос, полученный сервером или отправленный клиентом.
Семантика полей немного отличается при использовании клиентом и сервером. Кроме заметок по полям ниже, см. документацию для Request.Write и RoundTripper.
type Request struct {
// Method specifies the HTTP method (GET, POST, PUT, etc.).
// For client requests, an empty string means GET.
Method string
// URL specifies either the URI being requested (for server
// requests) or the URL to access (for client requests).
//
// For server requests, the URL is parsed from the URI
// supplied on the Request-Line as stored in RequestURI. For
// most requests, fields other than Path and RawQuery will be
// empty. (See RFC 7230, Section 5.3)
//
// For client requests, the URL's Host specifies the server to
// connect to, while the Request's Host field optionally
// specifies the Host header value to send in the HTTP
// request.
URL *url.URL
// The protocol version for incoming server requests.
//
// For client requests, these fields are ignored. The HTTP
// client code always uses either HTTP/1.1 or HTTP/2.
// See the docs on Transport for details.
Proto string // "HTTP/1.0"
ProtoMajor int // 1
ProtoMinor int // 0
// Header contains the request header fields either received
// by the server or to be sent by the client.
//
// If a server received a request with header lines,
//
// Host: example.com
// accept-encoding: gzip, deflate
// Accept-Language: en-us
// fOO: Bar
// foo: two
//
// then
//
// Header = map[string][]string{
// "Accept-Encoding": {"gzip, deflate"},
// "Accept-Language": {"en-us"},
// "Foo": {"Bar", "two"},
// }
//
// For incoming requests, the Host header is promoted to the
// Request.Host field and removed from the Header map.
//
// HTTP defines that header names are case-insensitive. The
// request parser implements this by using CanonicalHeaderKey,
// making the first character and any characters following a
// hyphen uppercase and the rest lowercase.
//
// For client requests, certain headers such as Content-Length
// and Connection are automatically written when needed and
// values in Header may be ignored. See the documentation
// for the Request.Write method.
Header Header
// Body is the request's body.
//
// For client requests, a nil body means the request has no
// body, such as a GET request. The HTTP Client's Transport
// is responsible for calling the Close method.
//
// For server requests, the Request Body is always non-nil
// but will return EOF immediately when no body is present.
// The Server will close the request body. The ServeHTTP
// Handler does not need to.
//
// Body must allow Read to be called concurrently with Close.
// In particular, calling Close should unblock a Read waiting
// for input.
Body io.ReadCloser
// GetBody defines an optional func to return a new copy of
// Body. It is used for client requests when a redirect requires
// reading the body more than once. Use of GetBody still
// requires setting Body.
//
// For server requests, it is unused.
GetBody func() (io.ReadCloser, error) // Go 1.8
// ContentLength records the length of the associated content.
// The value -1 indicates that the length is unknown.
// Values >= 0 indicate that the given number of bytes may
// be read from Body.
//
// For client requests, a value of 0 with a non-nil Body is
// also treated as unknown.
ContentLength int64
// TransferEncoding lists the transfer encodings from outermost to
// innermost. An empty list denotes the "identity" encoding.
// TransferEncoding can usually be ignored; chunked encoding is
// automatically added and removed as necessary when sending and
// receiving requests.
TransferEncoding []string
// Close indicates whether to close the connection after
// replying to this request (for servers) or after sending this
// request and reading its response (for clients).
//
// For server requests, the HTTP server handles this automatically
// and this field is not needed by Handlers.
//
// For client requests, setting this field prevents re-use of
// TCP connections between requests to the same hosts, as if
// Transport.DisableKeepAlives were set.
Close bool
// For server requests, Host specifies the host on which the
// URL is sought. For HTTP/1 (per RFC 7230, section 5.4), this
// is either the value of the "Host" header or the host name
// given in the URL itself. For HTTP/2, it is the value of the
// ":authority" pseudo-header field.
// It may be of the form "host:port". For international domain
// names, Host may be in Punycode or Unicode form. Use
// golang.org/x/net/idna to convert it to either format if
// needed.
// To prevent DNS rebinding attacks, server Handlers should
// validate that the Host header has a value for which the
// Handler considers itself authoritative. The included
// ServeMux supports patterns registered to particular host
// names and thus protects its registered Handlers.
//
// For client requests, Host optionally overrides the Host
// header to send. If empty, the Request.Write method uses
// the value of URL.Host. Host may contain an international
// domain name.
Host string
// Form contains the parsed form data, including both the URL
// field's query parameters and the PATCH, POST, or PUT form data.
// This field is only available after ParseForm is called.
// The HTTP client ignores Form and uses Body instead.
Form url.Values
// PostForm contains the parsed form data from PATCH, POST
// or PUT body parameters.
//
// This field is only available after ParseForm is called.
// The HTTP client ignores PostForm and uses Body instead.
PostForm url.Values // Go 1.1
// MultipartForm is the parsed multipart form, including file uploads.
// This field is only available after ParseMultipartForm is called.
// The HTTP client ignores MultipartForm and uses Body instead.
MultipartForm *multipart.Form
// Trailer specifies additional headers that are sent after the request
// body.
//
// For server requests, the Trailer map initially contains only the
// trailer keys, with nil values. (The client declares which trailers it
// will later send.) While the handler is reading from Body, it must
// not reference Trailer. After reading from Body returns EOF, Trailer
// can be read again and will contain non-nil values, if they were sent
// by the client.
//
// For client requests, Trailer must be initialized to a map containing
// the trailer keys to later send. The values may be nil or their final
// values. The ContentLength must be 0 or -1, to send a chunked request.
// After the HTTP request is sent the map values can be updated while
// the request body is read. Once the body returns EOF, the caller must
// not mutate Trailer.
//
// Few HTTP clients, servers, or proxies support HTTP trailers.
Trailer Header
// RemoteAddr allows HTTP servers and other software to record
// the network address that sent the request, usually for
// logging. This field is not filled in by ReadRequest and
// has no defined format. The HTTP server in this package
// sets RemoteAddr to an "IP:port" address before invoking a
// handler.
// This field is ignored by the HTTP client.
RemoteAddr string
// RequestURI is the unmodified request-target of the
// Request-Line (RFC 7230, Section 3.1.1) as sent by the client
// to a server. Usually the URL field should be used instead.
// It is an error to set this field in an HTTP client request.
RequestURI string
// TLS allows HTTP servers and other software to record
// information about the TLS connection on which the request
// was received. This field is not filled in by ReadRequest.
// The HTTP server in this package sets the field for
// TLS-enabled connections before invoking a handler;
// otherwise it leaves the field nil.
// This field is ignored by the HTTP client.
TLS *tls.ConnectionState
// Cancel is an optional channel whose closure indicates that the client
// request should be regarded as canceled. Not all implementations of
// RoundTripper may support Cancel.
//
// For server requests, this field is not applicable.
//
// Deprecated: Set the Request's context with NewRequestWithContext
// instead. If a Request's Cancel field and context are both
// set, it is undefined whether Cancel is respected.
Cancel <-chan struct{} // Go 1.5
// Response is the redirect response which caused this request
// to be created. This field is only populated during client
// redirects.
Response *Response // Go 1.7
// Pattern is the [ServeMux] pattern that matched the request.
// It is empty if the request was not matched against a pattern.
Pattern string // Go 1.23
// contains filtered or unexported fields
}
func NewRequest
func NewRequest(method, url string, body io.Reader) (*Request, error)
NewRequest оборачивает NewRequestWithContext с использованием context.Background.
func NewRequestWithContext 1.13
func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*Request, error)
NewRequestWithContext возвращает новый Request с заданным методом, URL и необязательным телом.
Если предоставленный body также является io.Closer, возвращаемый [Request.Body] устанавливается в body и будет закрыт (возможно, асинхронно) методами Client Do, Post и PostForm, а также Transport.RoundTrip.
NewRequestWithContext возвращает Request, подходящий для использования с Client.Do или Transport.RoundTrip. Для создания запроса для тестирования обработчика сервера используйте функцию net/http/httptest.NewRequest, функцию ReadRequest или вручную обновите поля Request. Для исходящего запроса клиента контекст контролирует весь жизненный цикл запроса и его ответа: получение соединения, отправка запроса и чтение заголовков и тела ответа. Различия между входящими и исходящими полями запроса см. в документации типа Request.
Если body имеет тип *bytes.Buffer, *bytes.Reader или *strings.Reader, ContentLength возвращаемого запроса устанавливается в его точное значение (вместо -1), GetBody заполняется (чтобы 307 и 308 перенаправления могли повторить тело), а Body устанавливается в NoBody, если ContentLength равно 0.
func ReadRequest
func ReadRequest(b *bufio.Reader) (*Request, error)
ReadRequest считывает и анализирует входящий запрос из b.
ReadRequest — это функция низкого уровня и должна использоваться только в специализированных приложениях; большинство кода должно использовать Server для чтения запросов и обработки их с помощью интерфейса Handler. ReadRequest поддерживает только запросы HTTP/1.x. Для HTTP/2 используйте golang.org/x/net/http2.
func (*Request) AddCookie
func (r *Request) AddCookie(c *Cookie)
AddCookie добавляет cookie в запрос. В соответствии с RFC 6265, раздел 5.4, AddCookie не добавляет более одного поля заголовка Cookie. Это означает, что все cookie, если таковые имеются, записываются в одну строку, разделенные точкой с запятой. AddCookie обрабатывает только имя и значение c и не обрабатывает заголовок Cookie, уже присутствующий в запросе.
func (*Request) BasicAuth 1.4
func (r *Request) BasicAuth() (username, password string, ok bool)
BasicAuth возвращает имя пользователя и пароль, предоставленные в заголовке Authorization запроса, если запрос использует HTTP Basic Authentication. См. RFC 2617, раздел 2.
func (*Request) Clone 1.13
func (r *Request) Clone(ctx context.Context) *Request
Clone возвращает глубокую копию r с изменённым контекстом на ctx. Предоставленный ctx не должен быть nil.
Clone выполняет только поверхностную копию поля Body.
Для исходящего запроса клиента контекст контролирует весь жизненный цикл запроса и его ответа: получение соединения, отправка запроса и чтение заголовков и тела ответа.
func (*Request) Context 1.7
func (r *Request) Context() context.Context
Context возвращает контекст запроса. Для изменения контекста используйте Request.Clone или Request.WithContext.
Возвращаемый контекст всегда не равен nil; по умолчанию он равен контексту фонового выполнения.
Для исходящих запросов клиента контекст контролирует отмену.
Для входящих запросов сервера контекст отменяется при закрытии соединения клиента, отмене запроса (с HTTP/2) или при возвращении метода ServeHTTP.
func (*Request) Cookie
func (r *Request) Cookie(name string) (*Cookie, error)
Cookie возвращает cookie с заданным именем, предоставленным в запросе, или ErrNoCookie, если cookie не найдено. Если несколько cookie соответствуют заданному имени, будет возвращена только одна cookie.
func (*Request) Cookies
func (r *Request) Cookies() []*Cookie
Cookies анализирует и возвращает HTTP cookie, отправленные с запросом.
func (*Request) CookiesNamed 1.23
func (r *Request) CookiesNamed(name string) []*Cookie
CookiesNamed анализирует и возвращает HTTP cookie с заданным именем, отправленные с запросом, или пустой срез, если не найдено совпадений.
func (*Request) FormFile
func (r *Request) FormFile(key string) (multipart.File, *multipart.FileHeader, error)
FormFile возвращает первый файл для заданного ключа формы. FormFile вызывает Request.ParseMultipartForm и Request.ParseForm при необходимости.
func (*Request) FormValue
func (r *Request) FormValue(key string) string
FormValue возвращает первое значение для заданного компонента запроса. Порядок приоритета:
- Тело формы application/x-www-form-urlencoded (только POST, PUT, PATCH)
- Параметры запроса (всегда)
- Тело формы multipart/form-data (всегда)
FormValue вызывает Request.ParseMultipartForm и Request.ParseForm при необходимости и игнорирует любые ошибки, возвращаемые этими функциями. Если ключ не найден, FormValue возвращает пустую строку. Для доступа к нескольким значениям одного и того же ключа вызовите ParseForm, а затем напрямую проверьте [Request.Form].
func (*Request) MultipartReader
func (r *Request) MultipartReader() (*multipart.Reader, error)
MultipartReader возвращает читатель MIME multipart, если это запрос POST multipart/form-data или multipart/mixed, иначе возвращает nil и ошибку. Используйте эту функцию вместо Request.ParseMultipartForm для обработки тела запроса как потока.
func (*Request) ParseForm
func (r *Request) ParseForm() error
ParseForm заполняет r.Form и r.PostForm.
Для всех запросов ParseForm анализирует исходную часть запроса из URL и обновляет r.Form.
Для запросов POST, PUT и PATCH она также считывает тело запроса, анализирует его как форму и помещает результаты в r.PostForm и r.Form. Параметры тела запроса имеют приоритет над значениями строки запроса URL в r.Form.
Если размер тела запроса Body еще не ограничен с помощью MaxBytesReader, размер ограничивается 10 МБ.
Для других HTTP-методов или когда Content-Type не является application/x-www-form-urlencoded, тело запроса не считывается, а r.PostForm инициализируется как не-nil, пустое значение.
Request.ParseMultipartForm автоматически вызывает ParseForm. ParseForm идемпотентна.
func (*Request) ParseMultipartForm
func (r *Request) ParseMultipartForm(maxMemory int64) error
ParseMultipartForm анализирует тело запроса как multipart/form-data. Весь тело запроса анализируется, и до maxMemory байт частей файла хранятся в памяти, а оставшаяся часть — в временных файлах на диске. ParseMultipartForm вызывает Request.ParseForm при необходимости. Если ParseForm возвращает ошибку, ParseMultipartForm возвращает её, но продолжает анализ тела запроса. После одного вызова ParseMultipartForm последующие вызовы не имеют эффекта.
func (*Request) PathValue 1.22
func (r *Request) PathValue(name string) string
PathValue возвращает значение для имени шаблона пути wildcard в шаблоне ServeMux, соответствующего запросу. Возвращает пустую строку, если запрос не сопоставлен с шаблоном или в шаблоне нет такого wildcard.
func (*Request) PostFormValue 1.1
func (r *Request) PostFormValue(key string) string
PostFormValue возвращает первое значение для заданного компонента тела запроса POST, PUT или PATCH. Параметры запроса URL игнорируются. PostFormValue вызывает Request.ParseMultipartForm и Request.ParseForm при необходимости и игнорирует любые возвращаемые ошибки. Если ключ не найден, PostFormValue возвращает пустую строку.
func (*Request) ProtoAtLeast
func (r *Request) ProtoAtLeast(major, minor int) bool
ProtoAtLeast сообщает, является ли используемый в запросе HTTP-протокол не ниже указанной версии major.minor.
func (*Request) Referer
func (r *Request) Referer() string
Referer возвращает URL-адрес ссылки, если он был отправлен в запросе.
Referer написан с ошибкой, как и в самом запросе, это ошибка, оставшаяся со времён ранних версий HTTP. Это значение также можно получить из карты Header как Header["Referer"]; преимущество использования метода заключается в том, что компилятор может диагностировать программы, использующие альтернативную (правильную английскую) запись req.Referrer(), но не может диагностировать программы, использующие Header["Referrer"].
func (*Request) SetBasicAuth
func (r *Request) SetBasicAuth(username, password string)
SetBasicAuth устанавливает заголовок Authorization запроса для использования HTTP Basic Authentication с предоставленным именем пользователя и паролем.
При использовании HTTP Basic Authentication предоставленные имя пользователя и пароль не шифруются. Его следует использовать только в запросе HTTPS.
Имя пользователя не может содержать двоеточие. Некоторые протоколы могут накладывать дополнительные требования к предварительному экранированию имени пользователя и пароля. Например, при использовании с OAuth2 оба аргумента должны быть предварительно закодированы с помощью url.QueryEscape.
func (*Request) SetPathValue 1.22
func (r *Request) SetPathValue(name, value string)
SetPathValue устанавливает имя в значение, чтобы последующие вызовы r.PathValue(name) возвращали значение.
func (*Request) UserAgent
func (r *Request) UserAgent() string
UserAgent возвращает User-Agent клиента, если он был отправлен в запросе.
func (*Request) WithContext 1.7
func (r *Request) WithContext(ctx context.Context) *Request
WithContext возвращает поверхностную копию r с изменённым контекстом на ctx. Предоставленный ctx не должен быть nil.
Для исходящего запроса клиента контекст контролирует весь жизненный цикл запроса и его ответа: получение соединения, отправка запроса и чтение заголовков и тела ответа.
Для создания нового запроса с контекстом используйте NewRequestWithContext. Для создания глубокой копии запроса с новым контекстом используйте Request.Clone.
func (*Request) Write
func (r *Request) Write(w io.Writer) error
Write записывает HTTP/1.1 запрос (заголовок и тело) в формате проводов. Этот метод обращается к следующим полям запроса:
Host URL Method (defaults to "GET") Header ContentLength TransferEncoding Body
Если Body присутствует, Content-Length ≤ 0 и [Request.TransferEncoding] не установлен в "identity", Write добавляет "Transfer-Encoding: chunked" в заголовок. Body закрывается после отправки.
func (*Request) WriteProxy
func (r *Request) WriteProxy(w io.Writer) error
WriteProxy подобен Request.Write, но записывает запрос в форме, ожидаемой HTTP-прокси. В частности, Request.WriteProxy записывает начальную строку Request-URI запроса с абсолютным URI, в соответствии с разделом 5.3 RFC 7230, включая схему и хост. В любом случае WriteProxy также записывает заголовок Host, используя либо r.Host, либо r.URL.Host.
type Response
Response представляет собой ответ на HTTP-запрос.
Клиент Client и Transport возвращают ответы от серверов после получения заголовков ответа. Тело ответа передаётся по запросу, по мере чтения поля Body.
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 // Go 1.7
// 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 // Go 1.3
}
func Get
func Get(url string) (resp *Response, err error)
Get отправляет GET-запрос на указанный URL. Если ответ содержит один из следующих кодов перенаправления, Get следует за перенаправлением, не более чем 10 раз:
301 (Moved Permanently) 302 (Found) 303 (See Other) 307 (Temporary Redirect) 308 (Permanent Redirect)
Возвращается ошибка, если перенаправлений слишком много или произошла ошибка протокола HTTP. Ответ с кодом, отличным от 2xx, не вызывает ошибку. Любая возвращаемая ошибка будет типа *url.Error. Метод Timeout значения url.Error вернёт true, если запрос истек по времени.
Когда err равен nil, resp всегда содержит непустое resp.Body. Вызывающий код должен закрыть resp.Body, когда закончит чтение из него.
Get — это обёртка вокруг DefaultClient.Get.
Для отправки запроса с настраиваемыми заголовками используйте NewRequest и DefaultClient.Do.
Для отправки запроса с заданным контекстом context.Context используйте NewRequestWithContext и DefaultClient.Do.
Пример
Код:
res, err := http.Get("http://www.google.com/robots.txt")
if err != nil {
log.Fatal(err)
}
body, err := io.ReadAll(res.Body)
res.Body.Close()
if res.StatusCode > 299 {
log.Fatalf("Response failed with status code: %d and\nbody: %s\n", res.StatusCode, body)
}
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s", body)
func Head
func Head(url string) (resp *Response, err error)
Head отправляет HEAD-запрос на указанный URL. Если ответ содержит один из следующих кодов перенаправления, Head следует за перенаправлением, не более чем 10 раз:
301 (Moved Permanently) 302 (Found) 303 (See Other) 307 (Temporary Redirect) 308 (Permanent Redirect)
Head — это обёртка вокруг DefaultClient.Head.
Для отправки запроса с заданным context.Context используйте NewRequestWithContext и DefaultClient.Do.
func Post
func Post(url, contentType string, body io.Reader) (resp *Response, err error)
Post отправляет POST-запрос на указанный URL.
Вызывающий код должен закрыть resp.Body, когда закончит чтение из него.
Если предоставленное тело является io.Closer, оно закрывается после запроса.
Post — это обёртка вокруг DefaultClient.Post.
Для установки настраиваемых заголовков используйте NewRequest и DefaultClient.Do.
См. документацию метода Client.Do для получения подробностей о том, как обрабатываются перенаправления.
Для отправки запроса с заданным context.Context используйте NewRequestWithContext и DefaultClient.Do.
func PostForm
func PostForm(url string, data url.Values) (resp *Response, err error)
PostForm отправляет POST-запрос на указанный URL, с ключами и значениями данных, закодированными в URL в качестве тела запроса.
Заголовок Content-Type установлен в application/x-www-form-urlencoded. Чтобы установить другие заголовки, используйте NewRequest и DefaultClient.Do.
Когда err равен nil, resp всегда содержит непустое resp.Body. Вызывающий код должен закрыть resp.Body, когда закончит чтение из него.
PostForm — это обёртка вокруг DefaultClient.PostForm.
См. документацию метода Client.Do для получения подробностей о том, как обрабатываются перенаправления.
Для отправки запроса с заданным context.Context используйте NewRequestWithContext и DefaultClient.Do.
func ReadResponse
func ReadResponse(r *bufio.Reader, req *Request) (*Response, error)
ReadResponse считывает и возвращает HTTP-ответ из r. Параметр req необязательно указывает запрос Request, соответствующий этому Response. Если он равен nil, предполагается GET-запрос. Клиенты должны вызвать resp.Body.Close, когда закончат чтение resp.Body. После этого вызова клиенты могут проверить resp.Trailer, чтобы найти пары ключ/значение, включённые в трейлере ответа.
func (*Response) Cookies
func (r *Response) Cookies() []*Cookie
Cookies анализирует и возвращает cookies, установленные в заголовках Set-Cookie.
func (*Response) Location
func (r *Response) Location() (*url.URL, error)
Location возвращает URL из заголовка ответа "Location", если он присутствует. Относительные перенаправления разрешаются относительно [Response.Request]. ErrNoLocation возвращается, если заголовок Location отсутствует.
func (*Response) ProtoAtLeast
func (r *Response) ProtoAtLeast(major, minor int) bool
ProtoAtLeast проверяет, соответствует ли используемый в ответе протокол HTTP хотя бы major.minor.
func (*Response) Write
func (r *Response) Write(w io.Writer) error
Write записывает r в w в формате HTTP/1.x ответа сервера, включая строку состояния, заголовки, тело и необязательный трейлер.
Этот метод обращается к следующим полям ответа r:
StatusCode ProtoMajor ProtoMinor Request.Method TransferEncoding Trailer Body ContentLength Header, values for non-canonical keys will have unpredictable behavior
Тело ответа закрывается после отправки.
type ResponseController 1.20
ResponseController используется обработчиком HTTP для управления ответом.
ResponseController не может быть использован после того, как метод [Handler.ServeHTTP] вернул значение.
type ResponseController struct {
// contains filtered or unexported fields
}
func NewResponseController 1.20
func NewResponseController(rw ResponseWriter) *ResponseController
NewResponseController создаёт ResponseController для запроса.
ResponseWriter должен быть исходным значением, переданным в метод [Handler.ServeHTTP], или иметь метод Unwrap, возвращающий исходный ResponseWriter.
Если ResponseWriter реализует любой из следующих методов, ResponseController вызовет их соответствующим образом:
Flush() FlushError() error // alternative Flush returning an error Hijack() (net.Conn, *bufio.ReadWriter, error) SetReadDeadline(deadline time.Time) error SetWriteDeadline(deadline time.Time) error EnableFullDuplex() error
Если ResponseWriter не поддерживает метод, ResponseController возвращает ошибку, соответствующую ErrNotSupported.
func (*ResponseController) EnableFullDuplex 1.21
func (c *ResponseController) EnableFullDuplex() error
EnableFullDuplex указывает, что обработчик запросов будет чередовать чтение из [Request.Body] с записью в ResponseWriter.
Для запросов HTTP/1 сервер Go по умолчанию потребляет любую непрочитанную часть тела запроса перед началом записи ответа, препятствуя обработчикам одновременного чтения запроса и записи ответа. Вызов EnableFullDuplex отключает это поведение и позволяет обработчикам продолжать чтение запроса и одновременную запись ответа.
Для запросов HTTP/2 сервер Go всегда допускает одновременное чтение и ответы.
func (*ResponseController) Flush 1.20
func (c *ResponseController) Flush() error
Flush сбрасывает буферизованные данные клиенту.
func (*ResponseController) Hijack 1.20
func (c *ResponseController) Hijack() (net.Conn, *bufio.ReadWriter, error)
Hijack позволяет вызывающей стороне взять под контроль соединение. См. интерфейс Hijacker для получения подробностей.
func (*ResponseController) SetReadDeadline 1.20
func (c *ResponseController) SetReadDeadline(deadline time.Time) error
SetReadDeadline устанавливает крайний срок для чтения всего запроса, включая тело. Чтение из тела запроса после истечения крайнего срока вернёт ошибку. Нулевое значение означает отсутствие крайнего срока.
Установка крайнего срока после его истечения не продлит его.
func (*ResponseController) SetWriteDeadline 1.20
func (c *ResponseController) SetWriteDeadline(deadline time.Time) error
SetWriteDeadline устанавливает крайний срок для записи ответа. Запись в тело ответа после истечения крайнего срока не будет блокироваться, но может завершиться успешно, если данные были буферизованы. Нулевое значение означает отсутствие крайнего срока.
Установка крайнего срока после его истечения не продлит его.
type ResponseWriter
Интерфейс ResponseWriter используется обработчиком HTTP для построения HTTP-ответа.
ResponseWriter не может быть использован после того, как [Handler.ServeHTTP] вернул значение.
type ResponseWriter interface {
// Header returns the header map that will be sent by
// [ResponseWriter.WriteHeader]. The [Header] map also is the mechanism with which
// [Handler] implementations can set HTTP trailers.
//
// Changing the header map after a call to [ResponseWriter.WriteHeader] (or
// [ResponseWriter.Write]) has no effect unless the HTTP status code was of the
// 1xx class or the modified headers are trailers.
//
// There are two ways to set Trailers. The preferred way is to
// predeclare in the headers which trailers you will later
// send by setting the "Trailer" header to the names of the
// trailer keys which will come later. In this case, those
// keys of the Header map are treated as if they were
// trailers. See the example. The second way, for trailer
// keys not known to the [Handler] until after the first [ResponseWriter.Write],
// is to prefix the [Header] map keys with the [TrailerPrefix]
// constant value.
//
// To suppress automatic response headers (such as "Date"), set
// their value to nil.
Header() Header
// Write writes the data to the connection as part of an HTTP reply.
//
// If [ResponseWriter.WriteHeader] has not yet been called, Write calls
// WriteHeader(http.StatusOK) before writing the data. If the Header
// does not contain a Content-Type line, Write adds a Content-Type set
// to the result of passing the initial 512 bytes of written data to
// [DetectContentType]. Additionally, if the total size of all written
// data is under a few KB and there are no Flush calls, the
// Content-Length header is added automatically.
//
// Depending on the HTTP protocol version and the client, calling
// Write or WriteHeader may prevent future reads on the
// Request.Body. For HTTP/1.x requests, handlers should read any
// needed request body data before writing the response. Once the
// headers have been flushed (due to either an explicit Flusher.Flush
// call or writing enough data to trigger a flush), the request body
// may be unavailable. For HTTP/2 requests, the Go HTTP server permits
// handlers to continue to read the request body while concurrently
// writing the response. However, such behavior may not be supported
// by all HTTP/2 clients. Handlers should read before writing if
// possible to maximize compatibility.
Write([]byte) (int, error)
// WriteHeader sends an HTTP response header with the provided
// status code.
//
// If WriteHeader is not called explicitly, the first call to Write
// will trigger an implicit WriteHeader(http.StatusOK).
// Thus explicit calls to WriteHeader are mainly used to
// send error codes or 1xx informational responses.
//
// The provided code must be a valid HTTP 1xx-5xx status code.
// Any number of 1xx headers may be written, followed by at most
// one 2xx-5xx header. 1xx headers are sent immediately, but 2xx-5xx
// headers may be buffered. Use the Flusher interface to send
// buffered data. The header map is cleared when 2xx-5xx headers are
// sent, but not with 1xx headers.
//
// The server will automatically send a 100 (Continue) header
// on the first read from the request body if the request has
// an "Expect: 100-continue" header.
WriteHeader(statusCode int)
} Пример (Трейлеры)
HTTP-трейлеры — это набор пар ключ/значение, подобных заголовкам, которые приходят после HTTP-ответа, а не перед ним.
Код:
mux := http.NewServeMux()
mux.HandleFunc("/sendstrailers", func(w http.ResponseWriter, req *http.Request) {
// Before any call to WriteHeader or Write, declare
// the trailers you will set during the HTTP
// response. These three headers are actually sent in
// the trailer.
w.Header().Set("Trailer", "AtEnd1, AtEnd2")
w.Header().Add("Trailer", "AtEnd3")
w.Header().Set("Content-Type", "text/plain; charset=utf-8") // normal header
w.WriteHeader(http.StatusOK)
w.Header().Set("AtEnd1", "value 1")
io.WriteString(w, "This HTTP response has both headers before this text and trailers at the end.\n")
w.Header().Set("AtEnd2", "value 2")
w.Header().Set("AtEnd3", "value 3") // These will appear as trailers.
})
type RoundTripper
RoundTripper — это интерфейс, представляющий возможность выполнения одной HTTP-транзакции, получая Response для данного Request.
RoundTripper должен быть безопасен для одновременного использования несколькими горутинами.
type RoundTripper interface {
// RoundTrip executes a single HTTP transaction, returning
// a Response for the provided Request.
//
// RoundTrip should not attempt to interpret the response. In
// particular, RoundTrip must return err == nil if it obtained
// a response, regardless of the response's HTTP status code.
// A non-nil err should be reserved for failure to obtain a
// response. Similarly, RoundTrip should not attempt to
// handle higher-level protocol details such as redirects,
// authentication, or cookies.
//
// RoundTrip should not modify the request, except for
// consuming and closing the Request's Body. RoundTrip may
// read fields of the request in a separate goroutine. Callers
// should not mutate or reuse the request until the Response's
// Body has been closed.
//
// RoundTrip must always close the body, including on errors,
// but depending on the implementation may do so in a separate
// goroutine even after RoundTrip returns. This means that
// callers wanting to reuse the body for subsequent requests
// must arrange to wait for the Close call before doing so.
//
// The Request's URL and Header fields must be initialized.
RoundTrip(*Request) (*Response, error)
} DefaultTransport — это реализация по умолчанию Transport и используется DefaultClient. Он устанавливает сетевые подключения по мере необходимости и кэширует их для повторного использования последующими вызовами. Он использует HTTP-прокси, как указано переменными среды HTTP_PROXY, HTTPS_PROXY и NO_PROXY (или их строчными вариантами).
var DefaultTransport RoundTripper = &Transport{
Proxy: ProxyFromEnvironment,
DialContext: defaultTransportDialContext(&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}),
ForceAttemptHTTP2: true,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
} func NewFileTransport
func NewFileTransport(fs FileSystem) RoundTripper
NewFileTransport возвращает новый RoundTripper, обслуживающий предоставленный FileSystem. Возвращаемый RoundTripper игнорирует хост URL в своих входящих запросах, а также большинство других свойств запроса.
Типичный случай использования NewFileTransport — регистрация протокола "file" с Transport, как в:
t := &http.Transport{}
t.RegisterProtocol("file", http.NewFileTransport(http.Dir("/")))
c := &http.Client{Transport: t}
res, err := c.Get("file:///etc/passwd")
...
func NewFileTransportFS 1.22
func NewFileTransportFS(fsys fs.FS) RoundTripper
NewFileTransportFS возвращает новый RoundTripper, обслуживающий предоставленную файловую систему fsys. Возвращаемый RoundTripper игнорирует хост URL в своих входящих запросах, а также большинство других свойств запроса. Файлы, предоставляемые fsys, должны реализовывать io.Seeker.
Типичный случай использования NewFileTransportFS — регистрация протокола "file" с Transport, как в:
fsys := os.DirFS("/")
t := &http.Transport{}
t.RegisterProtocol("file", http.NewFileTransportFS(fsys))
c := &http.Client{Transport: t}
res, err := c.Get("file:///etc/passwd")
...
type SameSite 1.11
SameSite позволяет серверу определить атрибут cookie, делая невозможным для браузера отправлять этот cookie вместе с межсайтовыми запросами. Основная цель — уменьшить риск утечки информации между сайтами и обеспечить некоторую защиту от поддельных межсайтовых запросов.
См. https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00 для получения подробностей.
type SameSite int
const (
SameSiteDefaultMode SameSite = iota + 1
SameSiteLaxMode
SameSiteStrictMode
SameSiteNoneMode
) type ServeMux
ServeMux — это мультиплексор HTTP-запросов. Он сопоставляет URL каждого входящего запроса со списком зарегистрированных шаблонов и вызывает обработчик для шаблона, наиболее точно соответствующего URL.
Шаблоны
Шаблоны могут соответствовать методу, хосту и пути запроса. Некоторые примеры:
- "/index.html" соответствует пути "/index.html" для любого хоста и метода.
- "GET /static/" соответствует запросу GET, путь которого начинается с "/static/".
- "example.com/" соответствует любому запросу к хосту "example.com".
- "example.com/{$}" соответствует запросам с хостом "example.com" и путём "/".
- "/b/{bucket}/o/{objectname...}" соответствует путям, первый сегмент которых — "b", а третий — "o". Имя "bucket" обозначает второй сегмент, а "objectname" — оставшуюся часть пути.
В общем случае шаблон выглядит так
[METHOD ][HOST]/[PATH]
Все три части необязательны; "/" является допустимым шаблоном. Если METHOD присутствует, за ним должен следовать хотя бы один пробел или табуляция.
Буквальные (то есть не содержащие подстановочных знаков) части шаблона сопоставляются соответствующим частям запроса в регистрозависимом режиме.
Шаблон без метода соответствует любому методу. Шаблон с методом GET соответствует как GET, так и HEAD запросам. В противном случае метод должен точно совпадать.
Шаблон без хоста соответствует любому хосту. Шаблон с хостом соответствует URL-адресам только на этом хосте.
Путь может включать сегменты с подстановочными знаками вида {NAME} или {NAME...}. Например, "/b/{bucket}/o/{objectname...}". Имя подстановочного знака должно быть корректным идентификатором Go. Подстановочные знаки должны быть полными сегментами пути: они должны предшествовать слэшу и следовать за слэшем или заканчивать строку. Например, "/b_{bucket}" — некорректный шаблон.
Обычно подстановочный знак соответствует только одному сегменту пути, заканчивающемуся на следующем буквальном слэше (не %2F) в URL-адресе запроса. Но если "..." присутствует, то подстановочный знак соответствует оставшейся части пути URL, включая слэши. (Поэтому подстановочный знак "..." недопустим в любом месте, кроме конца шаблона). Сопоставление для подстановочного знака можно получить, вызвав Request.PathValue с именем подстановочного знака. Конечный слэш в пути действует как анонимный подстановочный знак "...".
Специальный подстановочный знак {$} соответствует только концу URL-адреса. Например, шаблон "/{$}" соответствует только пути "/", а шаблон "/" соответствует любому пути.
Для сопоставления пути шаблона и пути входящего запроса деэкранируются сегмент за сегментом. Таким образом, например, путь "/a%2Fb/100%25" обрабатывается как имеющий два сегмента, "a/b" и "100%". Шаблон "/a%2fb/" соответствует ему, но шаблон "/a/b/" не соответствует.
Приоритет
Если два или более шаблона соответствуют запросу, то приоритет имеет наиболее конкретный шаблон. Шаблон P1 более конкретен, чем P2, если P1 соответствует строгому подмножеству запросов P2; то есть, если P2 соответствует всем запросам P1 и ещё больше. Если ни один не более конкретен, то шаблоны конфликтуют. Есть одно исключение из этого правила, для обеспечения обратной совместимости: если два шаблона по-другому конфликтуют, и один имеет хост, а другой нет, то шаблон с хостом имеет приоритет. Если шаблон, переданный в ServeMux.Handle или ServeMux.HandleFunc, конфликтует с другим зарегистрированным шаблоном, эти функции вызывают ошибку паники.
В качестве примера общего правила, "/images/thumbnails/" более конкретен, чем "/images/", поэтому оба могут быть зарегистрированы. Первый соответствует путям, начинающимся с "/images/thumbnails/", а второй — любому другому пути в поддереве "/images/".
Рассмотрим ещё один пример, шаблоны "GET /" и "/index.html": оба соответствуют запросу GET для "/index.html", но первый шаблон соответствует всем другим GET и HEAD запросам, а второй — любому запросу для "/index.html", использующему другой метод. Шаблоны конфликтуют.
Перенаправление по окончательному слэшу
Рассмотрим ServeMux с обработчиком для поддерева, зарегистрированного с помощью конечного слэша или подстановочного знака "...". Если ServeMux получает запрос для корня поддерева без конечного слэша, он перенаправляет запрос, добавляя конечный слэш. Это поведение может быть переопределено с помощью отдельной регистрации для пути без конечного слэша или подстановочного знака "...". Например, регистрация "/images/" заставляет ServeMux перенаправлять запрос для "/images" на "/images/", если "/images" не был зарегистрирован отдельно.
Сантизация запроса
ServeMux также заботится о санитизации пути URL-запроса и заголовка Host, удаляя номер порта и перенаправляя любые запросы, содержащие сегменты . или .. или повторяющиеся слэши, на эквивалентный, более чистый URL. Экранированные элементы пути, такие как "%2e" для "." и "%2f" для "/", сохраняются и не считаются разделителями для маршрутизации запроса.
Совместимость
Синтаксис шаблонов и поведение сопоставления ServeMux существенно изменились в Go 1.22. Чтобы восстановить старое поведение, установите переменную среды GODEBUG на "httpmuxgo121=1". Это значение считывается один раз при запуске программы; изменения во время выполнения будут проигнорированы.
Изменения, несовместимые с обратной совместимостью, включают:
- В версии 1.21 подстановочные знаки были обычными буквальными сегментами пути. Например, шаблон "/{x}" будет соответствовать только этому пути в 1.21, но будет соответствовать любому односегментному пути в 1.22.
- В версии 1.21 ни один шаблон не отклонялся, если он не был пустым или не вступал в конфликт с уже существующим шаблоном. В версии 1.22 синтаксически некорректные шаблоны будут вызывать ошибку паники в ServeMux.Handle и ServeMux.HandleFunc. Например, в 1.21 шаблоны "/{" и "/a{x}" соответствовали сами себе, но в 1.22 они некорректны и вызовут панику при регистрации.
- В версии 1.22 каждый сегмент шаблона деэкранируется; этого не делалось в 1.21. Например, в 1.22 шаблон "/%61" соответствует пути "/a" ("%61" — это экранированная последовательность URL для "a"), но в 1.21 он бы соответствовал только пути "/%2561" (где "%25" — экранированная последовательность для процента).
- При сопоставлении шаблонов с путями в версии 1.22 каждый сегмент пути деэкранируется; в 1.21 весь путь деэкранировался. Это изменение в основном влияет на то, как обрабатываются пути с экранированными элементами %2F, смежными со слэшами. Подробности см. в https://go.dev/issue/21955.
type ServeMux struct {
// contains filtered or unexported fields
}
Функция NewServeMux
func NewServeMux() *ServeMux
NewServeMux выделяет и возвращает новый ServeMux.
Функция (*ServeMux) Handle
func (mux *ServeMux) Handle(pattern string, handler Handler)
Handle регистрирует обработчик для данного шаблона. Если данный шаблон конфликтует с уже зарегистрированным, Handle вызывает ошибку паники.
Пример
Код:
mux := http.NewServeMux()
mux.Handle("/api/", apiHandler{})
mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
// The "/" pattern matches everything, so we need to check
// that we're at the root here.
if req.URL.Path != "/" {
http.NotFound(w, req)
return
}
fmt.Fprintf(w, "Welcome to the home page!")
})
Функция (*ServeMux) HandleFunc
func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request))
HandleFunc регистрирует функцию-обработчик для данного шаблона. Если данный шаблон конфликтует с уже зарегистрированным, HandleFunc вызывает ошибку паники.
Функция (*ServeMux) Handler 1.1
func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string)
Handler возвращает обработчик, используемый для данного запроса, консультируясь с r.Method, r.Host и r.URL.Path. Он всегда возвращает непустой обработчик. Если путь не находится в канонической форме, обработчик будет внутренне сгенерированным обработчиком, перенаправляющим на канонический путь. Если хост содержит порт, он игнорируется при сопоставлении обработчиков.
Путь и хост используются без изменений для запросов CONNECT.
Handler также возвращает зарегистрированный шаблон, который соответствует запросу, или, в случае внутренне сгенерированных перенаправлений, путь, который будет соответствовать после выполнения перенаправления.
Если нет зарегистрированного обработчика, применяемого к запросу, Handler возвращает обработчик «страница не найдена» и пустой шаблон.
Функция (*ServeMux) ServeHTTP
func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request)
ServeHTTP направляет запрос обработчику, шаблон которого наиболее точно соответствует URL-адресу запроса.
Тип Server
Server определяет параметры для запуска HTTP-сервера. Нулевое значение 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
// DisableGeneralOptionsHandler, if true, passes "OPTIONS *" requests to the Handler,
// otherwise responds with 200 OK and Content-Length: 0.
DisableGeneralOptionsHandler bool // Go 1.20
// 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 zero, the value of
// ReadTimeout is used. If negative, or if zero and ReadTimeout
// is zero or negative, there is no timeout.
ReadHeaderTimeout time.Duration // Go 1.8
// 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 zero, the value
// of ReadTimeout is used. If negative, or if zero and ReadTimeout
// is zero or negative, there is no timeout.
IdleTimeout time.Duration // Go 1.8
// 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) // Go 1.1
// 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) // Go 1.3
// 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 // Go 1.3
// 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 // Go 1.13
// 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 // Go 1.13
// HTTP2 configures HTTP/2 connections.
//
// This field does not yet have any effect.
// See https://go.dev/issue/67813.
HTTP2 *HTTP2Config // Go 1.24
// Protocols is the set of protocols accepted by the server.
//
// If Protocols includes UnencryptedHTTP2, the server will accept
// unencrypted HTTP/2 connections. The server can serve both
// HTTP/1 and unencrypted HTTP/2 on the same address and port.
//
// If Protocols is nil, the default is usually HTTP/1 and HTTP/2.
// If TLSNextProto is non-nil and does not contain an "h2" entry,
// the default is HTTP/1 only.
Protocols *Protocols // Go 1.24
// contains filtered or unexported fields
}
Функция (*Server) Close 1.8
func (s *Server) Close() error
Close немедленно закрывает все активные net.Listeners и любые соединения в состоянии StateNew, StateActive или StateIdle. Для плавного завершения используйте Server.Shutdown.
Close не пытается закрыть (и даже не знает о) каких-либо перехваченных соединениях, таких как WebSocket.
Close возвращает любую ошибку, возвращённую при закрытии базового Listener(ов) Server.
Функция (*Server) ListenAndServe
func (s *Server) ListenAndServe() error
ListenAndServe прослушивает TCP-сетевой адрес s.Addr и затем вызывает Serve для обработки запросов на входящих соединениях. Принятые соединения настраиваются для активации TCP keep-alives.
Если s.Addr пусто, используется ":http".
ListenAndServe всегда возвращает непустую ошибку. После Server.Shutdown или Server.Close возвращаемая ошибка — ErrServerClosed.
Функция (*Server) ListenAndServeTLS
func (s *Server) ListenAndServeTLS(certFile, keyFile string) error
ListenAndServeTLS прослушивает TCP-сетевой адрес s.Addr и затем вызывает ServeTLS для обработки запросов на входящих TLS-соединениях. Принятые соединения настраиваются для активации TCP keep-alives.
Файлы, содержащие сертификат и соответствующий закрытый ключ для сервера, должны быть предоставлены, если ни TLSConfig.Certificates, ни TLSConfig.GetCertificate сервера не заполнены. Если сертификат подписан центром сертификации, certFile должен быть конкатенацией сертификата сервера, всех промежуточных сертификатов и сертификата CA.
Если s.Addr пусто, используется ":https".
ListenAndServeTLS всегда возвращает непустую ошибку. После Server.Shutdown или Server.Close возвращаемая ошибка — ErrServerClosed.
Функция (*Server) RegisterOnShutdown 1.9
func (s *Server) RegisterOnShutdown(f func())
RegisterOnShutdown регистрирует функцию для вызова при Server.Shutdown. Это можно использовать для плавного завершения соединений, которые прошли апгрейд протокола ALPN или были перехвачены. Эта функция должна начинать протокольно-специфичное плавное завершение, но не должна ждать завершения завершения.
Функция (*Server) Serve
func (s *Server) Serve(l net.Listener) error
Serve принимает входящие соединения на Listener l, создавая новую службу goroutine для каждого. Goroutine службы читают запросы и затем вызывают s.Handler для ответа на них.
Поддержка HTTP/2 включена только в том случае, если Listener возвращает соединения *tls.Conn и они были сконфигурированы с "h2" в TLS Config.NextProtos.
Serve всегда возвращает непустую ошибку и закрывает l. После Server.Shutdown или Server.Close возвращаемая ошибка — ErrServerClosed.
Функция (*Server) ServeTLS 1.9
func (s *Server) ServeTLS(l net.Listener, certFile, keyFile string) error
ServeTLS принимает входящие подключения на Listener l, создавая новую горутину службы для каждого. Горутины службы выполняют настройку TLS и затем читают запросы, вызывая s.Handler для ответа на них.
Если не заполнены TLSConfig.Certificates сервера, TLSConfig.GetCertificate или config.GetConfigForClient, необходимо предоставить файлы с сертификатом и соответствующим закрытым ключом сервера. Если сертификат подписан центром сертификации, certFile должен содержать объединение сертификата сервера, всех промежуточных сертификатов и сертификата ЦС.
ServeTLS всегда возвращает ошибку, отличную от nil. После Server.Shutdown или Server.Close возвращаемая ошибка — ErrServerClosed.
func (*Server) SetKeepAlivesEnabled 1.3
func (s *Server) SetKeepAlivesEnabled(v bool)
SetKeepAlivesEnabled управляет включением HTTP keep-alive. По умолчанию keep-alive включены всегда. Отключать их следует только в очень ограниченных ресурсами средах или при завершении работы сервера.
func (*Server) Shutdown 1.8
func (s *Server) Shutdown(ctx context.Context) error
Shutdown плавно завершает работу сервера без прерывания активных подключений. Shutdown работает, сначала закрывая все открытые слушатели, затем закрывая все неактивные подключения, а затем ожидая неопределённое время, пока подключения не станут неактивными и не завершатся. Если предоставленный контекст истекает до завершения завершения работы, Shutdown возвращает ошибку контекста, иначе он возвращает любую ошибку, возвращённую при закрытии основного слушателя(ов) сервера.
При вызове Shutdown Serve, ListenAndServe и ListenAndServeTLS немедленно возвращают ErrServerClosed. Убедитесь, что программа не завершается и вместо этого ожидает возврата Shutdown.
Shutdown не пытается закрыть и не ожидает завершения работы перехваченных подключений, таких как WebSocket. Вызывающий Shutdown должен отдельно уведомлять такие долгоживущие подключения о завершении работы и ожидать их закрытия, если это необходимо. См. Server.RegisterOnShutdown для способов регистрации функций уведомления о завершении работы.
После вызова Shutdown на сервере он больше не может быть повторно использован; дальнейшие вызовы методов, таких как Serve, вернут ErrServerClosed.
Пример
Код:
var srv http.Server
idleConnsClosed := make(chan struct{})
go func() {
sigint := make(chan os.Signal, 1)
signal.Notify(sigint, os.Interrupt)
<-sigint
// We received an interrupt signal, shut down.
if err := srv.Shutdown(context.Background()); err != nil {
// Error from closing listeners, or context timeout:
log.Printf("HTTP server Shutdown: %v", err)
}
close(idleConnsClosed)
}()
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
// Error starting or closing listener:
log.Fatalf("HTTP server ListenAndServe: %v", err)
}
<-idleConnsClosed
type Transport
Transport — это реализация RoundTripper, которая поддерживает HTTP, HTTPS и HTTP-прокси (как для HTTP, так и для HTTPS с CONNECT).
По умолчанию Transport кэширует подключения для последующего повторного использования. Это может привести к большому количеству открытых подключений при обращении к множеству хостов. Это поведение можно управлять с помощью метода Transport.CloseIdleConnections и полей [Transport.MaxIdleConnsPerHost] и [Transport.DisableKeepAlives].
Транспорты должны повторно использоваться, а не создаваться по мере необходимости. Транспорты безопасны для одновременного использования несколькими горутинами.
Transport — это низкоуровневый инструмент для отправки HTTP и HTTPS-запросов. Для функционала высокого уровня, такого как куки и переадресации, см. Client.
Transport использует HTTP/1.1 для HTTP-URL и либо HTTP/1.1, либо HTTP/2 для HTTPS-URL, в зависимости от поддержки HTTP/2 сервером и конфигурации Transport. DefaultTransport поддерживает HTTP/2. Чтобы явно включить HTTP/2 в транспорте, установите [Transport.Protocols].
Ответы со статусами в диапазоне 1xx либо обрабатываются автоматически (100 expect-continue), либо игнорируются. Исключение составляет HTTP-статус-код 101 (Switching Protocols), который считается конечным статусом и возвращается Transport.RoundTrip. Чтобы увидеть пропущенные ответы 1xx, используйте пакет httptrace trace и свойство ClientTrace.Got1xxResponse.
Transport повторно отправляет запрос только при обнаружении сетевой ошибки, если подключение уже успешно использовалось, если запрос идемпотентен и либо не имеет тела, либо у него определён [Request.GetBody]. HTTP-запросы считаются идемпотентными, если они имеют методы GET, HEAD, OPTIONS или TRACE; или если их карта заголовков Header содержит запись "Idempotency-Key" или "X-Idempotency-Key". Если значение ключа идемпотентности — пустой срез, запрос обрабатывается как идемпотентный, но заголовок не отправляется по сети.
type Transport struct {
// Proxy specifies a function to return a proxy for a given
// Request. If the function returns a non-nil error, the
// request is aborted with the provided error.
//
// The proxy type is determined by the URL scheme. "http",
// "https", "socks5", and "socks5h" are supported. If the scheme is empty,
// "http" is assumed.
// "socks5" is treated the same as "socks5h".
//
// If the proxy URL contains a userinfo subcomponent,
// the proxy request will pass the username and password
// in a Proxy-Authorization header.
//
// If Proxy is nil or returns a nil *URL, no proxy is used.
Proxy func(*Request) (*url.URL, error)
// OnProxyConnectResponse is called when the Transport gets an HTTP response from
// a proxy for a CONNECT request. It's called before the check for a 200 OK response.
// If it returns an error, the request fails with that error.
OnProxyConnectResponse func(ctx context.Context, proxyURL *url.URL, connectReq *Request, connectRes *Response) error // Go 1.20
// DialContext specifies the dial function for creating unencrypted TCP connections.
// If DialContext is nil (and the deprecated Dial below is also nil),
// then the transport dials using package net.
//
// DialContext runs concurrently with calls to RoundTrip.
// A RoundTrip call that initiates a dial may end up using
// a connection dialed previously when the earlier connection
// becomes idle before the later DialContext completes.
DialContext func(ctx context.Context, network, addr string) (net.Conn, error) // Go 1.7
// Dial specifies the dial function for creating unencrypted TCP connections.
//
// Dial runs concurrently with calls to RoundTrip.
// A RoundTrip call that initiates a dial may end up using
// a connection dialed previously when the earlier connection
// becomes idle before the later Dial completes.
//
// Deprecated: Use DialContext instead, which allows the transport
// to cancel dials as soon as they are no longer needed.
// If both are set, DialContext takes priority.
Dial func(network, addr string) (net.Conn, error)
// DialTLSContext specifies an optional dial function for creating
// TLS connections for non-proxied HTTPS requests.
//
// If DialTLSContext is nil (and the deprecated DialTLS below is also nil),
// DialContext and TLSClientConfig are used.
//
// If DialTLSContext is set, the Dial and DialContext hooks are not used for HTTPS
// requests and the TLSClientConfig and TLSHandshakeTimeout
// are ignored. The returned net.Conn is assumed to already be
// past the TLS handshake.
DialTLSContext func(ctx context.Context, network, addr string) (net.Conn, error) // Go 1.14
// DialTLS specifies an optional dial function for creating
// TLS connections for non-proxied HTTPS requests.
//
// Deprecated: Use DialTLSContext instead, which allows the transport
// to cancel dials as soon as they are no longer needed.
// If both are set, DialTLSContext takes priority.
DialTLS func(network, addr string) (net.Conn, error) // Go 1.4
// TLSClientConfig specifies the TLS configuration to use with
// tls.Client.
// If nil, the default configuration is used.
// If non-nil, HTTP/2 support may not be enabled by default.
TLSClientConfig *tls.Config
// TLSHandshakeTimeout specifies the maximum amount of time to
// wait for a TLS handshake. Zero means no timeout.
TLSHandshakeTimeout time.Duration // Go 1.3
// DisableKeepAlives, if true, disables HTTP keep-alives and
// will only use the connection to the server for a single
// HTTP request.
//
// This is unrelated to the similarly named TCP keep-alives.
DisableKeepAlives bool
// DisableCompression, if true, prevents the Transport from
// requesting compression with an "Accept-Encoding: gzip"
// request header when the Request contains no existing
// Accept-Encoding value. If the Transport requests gzip on
// its own and gets a gzipped response, it's transparently
// decoded in the Response.Body. However, if the user
// explicitly requested gzip it is not automatically
// uncompressed.
DisableCompression bool
// MaxIdleConns controls the maximum number of idle (keep-alive)
// connections across all hosts. Zero means no limit.
MaxIdleConns int // Go 1.7
// MaxIdleConnsPerHost, if non-zero, controls the maximum idle
// (keep-alive) connections to keep per-host. If zero,
// DefaultMaxIdleConnsPerHost is used.
MaxIdleConnsPerHost int
// MaxConnsPerHost optionally limits the total number of
// connections per host, including connections in the dialing,
// active, and idle states. On limit violation, dials will block.
//
// Zero means no limit.
MaxConnsPerHost int // Go 1.11
// IdleConnTimeout is the maximum amount of time an idle
// (keep-alive) connection will remain idle before closing
// itself.
// Zero means no limit.
IdleConnTimeout time.Duration // Go 1.7
// ResponseHeaderTimeout, if non-zero, specifies the amount of
// time to wait for a server's response headers after fully
// writing the request (including its body, if any). This
// time does not include the time to read the response body.
ResponseHeaderTimeout time.Duration // Go 1.1
// ExpectContinueTimeout, if non-zero, specifies the amount of
// time to wait for a server's first response headers after fully
// writing the request headers if the request has an
// "Expect: 100-continue" header. Zero means no timeout and
// causes the body to be sent immediately, without
// waiting for the server to approve.
// This time does not include the time to send the request header.
ExpectContinueTimeout time.Duration // Go 1.6
// TLSNextProto specifies how the Transport switches to an
// alternate protocol (such as HTTP/2) after a TLS ALPN
// protocol negotiation. If Transport dials a TLS connection
// with a non-empty protocol name and TLSNextProto contains a
// map entry for that key (such as "h2"), then the func is
// called with the request's authority (such as "example.com"
// or "example.com:1234") and the TLS connection. The function
// must return a RoundTripper that then handles the request.
// If TLSNextProto is not nil, HTTP/2 support is not enabled
// automatically.
TLSNextProto map[string]func(authority string, c *tls.Conn) RoundTripper // Go 1.6
// ProxyConnectHeader optionally specifies headers to send to
// proxies during CONNECT requests.
// To set the header dynamically, see GetProxyConnectHeader.
ProxyConnectHeader Header // Go 1.8
// GetProxyConnectHeader optionally specifies a func to return
// headers to send to proxyURL during a CONNECT request to the
// ip:port target.
// If it returns an error, the Transport's RoundTrip fails with
// that error. It can return (nil, nil) to not add headers.
// If GetProxyConnectHeader is non-nil, ProxyConnectHeader is
// ignored.
GetProxyConnectHeader func(ctx context.Context, proxyURL *url.URL, target string) (Header, error) // Go 1.16
// MaxResponseHeaderBytes specifies a limit on how many
// response bytes are allowed in the server's response
// header.
//
// Zero means to use a default limit.
MaxResponseHeaderBytes int64 // Go 1.7
// WriteBufferSize specifies the size of the write buffer used
// when writing to the transport.
// If zero, a default (currently 4KB) is used.
WriteBufferSize int // Go 1.13
// ReadBufferSize specifies the size of the read buffer used
// when reading from the transport.
// If zero, a default (currently 4KB) is used.
ReadBufferSize int // Go 1.13
// ForceAttemptHTTP2 controls whether HTTP/2 is enabled when a non-zero
// Dial, DialTLS, or DialContext func or TLSClientConfig is provided.
// By default, use of any those fields conservatively disables HTTP/2.
// To use a custom dialer or TLS config and still attempt HTTP/2
// upgrades, set this to true.
ForceAttemptHTTP2 bool // Go 1.13
// HTTP2 configures HTTP/2 connections.
//
// This field does not yet have any effect.
// See https://go.dev/issue/67813.
HTTP2 *HTTP2Config // Go 1.24
// Protocols is the set of protocols supported by the transport.
//
// If Protocols includes UnencryptedHTTP2 and does not include HTTP1,
// the transport will use unencrypted HTTP/2 for requests for http:// URLs.
//
// If Protocols is nil, the default is usually HTTP/1 only.
// If ForceAttemptHTTP2 is true, or if TLSNextProto contains an "h2" entry,
// the default is HTTP/1 and HTTP/2.
Protocols *Protocols // Go 1.24
// contains filtered or unexported fields
}
func (*Transport) CancelRequest 1.1
func (t *Transport) CancelRequest(req *Request)
CancelRequest отменяет запрос в процессе закрытием его подключения. CancelRequest следует вызывать только после того, как Transport.RoundTrip вернул значение.
Устарело: используйте Request.WithContext для создания запроса с отменяемым контекстом вместо этого. CancelRequest не может отменить запросы HTTP/2. Это может стать бессмысленной операцией в будущей версии Go.
func (*Transport) Clone 1.13
func (t *Transport) Clone() *Transport
Clone возвращает глубокую копию экспортированных полей t.
func (*Transport) CloseIdleConnections
func (t *Transport) CloseIdleConnections()
CloseIdleConnections закрывает все подключения, которые ранее были подключены из предыдущих запросов, но сейчас неактивны в состоянии «keep-alive». Он не прерывает подключения, которые используются в данный момент.
func (*Transport) RegisterProtocol
func (t *Transport) RegisterProtocol(scheme string, rt RoundTripper)
RegisterProtocol регистрирует новый протокол со схемой. Transport будет передавать запросы с данной схемой в rt. Ответственность rt — симулировать семантику HTTP-запросов.
RegisterProtocol может использоваться другими пакетами для предоставления реализаций схем протоколов, таких как «ftp» или «file».
Если rt.RoundTrip возвращает ErrSkipAltProtocol, Transport будет обрабатывать Transport.RoundTrip сам для этого запроса, как если бы протокол не был зарегистрирован.
func (*Transport) RoundTrip
func (t *Transport) RoundTrip(req *Request) (*Response, error)
RoundTrip реализует интерфейс RoundTripper.
Для поддержки HTTP-клиента высокого уровня (например, обработки куки и переадресаций) см. Get, Post и тип Client.
Как и в интерфейсе RoundTripper, типы ошибок, возвращаемые RoundTrip, не определены.
Подкаталоги
| Имя | Описание |
|---|---|
| .. | |
| cgi | Пакет cgi реализует CGI (Common Gateway Interface), как указано в RFC 3875. |
| cookiejar | Пакет cookiejar реализует хранилище cookie http.CookieJar, совместимое с RFC 6265, в оперативной памяти. |
| fcgi | Пакет fcgi реализует протокол FastCGI. |
| httptest | Пакет httptest предоставляет утилиты для тестирования HTTP. |
| httptrace | Пакет httptrace предоставляет механизмы для отслеживания событий внутри HTTP-запросов клиента. |
| httputil | Пакет httputil предоставляет HTTP-утилиты, дополняющие более распространённые утилиты в пакете net/http. |
| pprof | Пакет pprof обслуживает по HTTP данные профилирования выполнения в формате, ожидаемом инструментом визуализации pprof. |
© Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
http://golang.org/pkg/net/http/