Module net.http stdlib

net.http
Version:
0.3.3
License:
MIT
Dependencies from vmod:
0
Imports:
10
Imported by:
3
Repository:
OS-specific
Show selected OS-specific symbols.
Backend-specific
Show selected Backend-specific symbols.

Dependencies defined in v.mod

This section is empty.

Imported by

Aliases

This section is empty.

Constants

This section is empty.

Sum types

This section is empty.

Functions

#fn delete

fn delete(url string) !Response

delete sends an HTTP DELETE request to the given url.

#fn download_file

fn download_file(url string, out_file_path string) !

download_file retrieves a document from the URL url, and saves it in the output file path out_file_path.

#fn escape

deprecated:escape is deprecated, use urllib.query_unescape() instead
fn escape(s string) string

#fn escape_url

deprecated:escape_url is deprecated, use urllib.query_escape() instead
fn escape_url(s string) string

#fn fetch

fn fetch(config FetchConfig) !Response

fetch sends an HTTP request to the url with the given method and configuration.

#fn get

fn get(url string) !Response

get sends a GET HTTP request to the given url.

#fn get_text

fn get_text(url string) string

get_text sends an HTTP GET request to the given url and returns the text content of the response.

#fn method_from_str

fn method_from_str(m string) Method

method_from_str returns the corresponding Method enum field given a string m, e.g. 'GET' would return Method.get.

Currently, the default value is Method.get for unsupported string value.

#fn new_custom_header_from_map

fn new_custom_header_from_map(kvs map[string]string) !Header

new_custom_header_from_map creates a Header from string key value pairs

#fn new_header_from_map

fn new_header_from_map(kvs map[CommonHeader]string) Header

new_header_from_map creates a Header from key value pairs

#fn parse_form

fn parse_form(body string) map[string]string

Parse URL encoded key=value&key=value forms

FIXME: Some servers can require the parameter in a specific order.

a possible solution is to use the a list of QueryValue

#fn parse_multipart_form

fn parse_multipart_form(body string, boundary string) (map[string]string, map[string][]FileData)

#fn parse_request

fn parse_request(mut reader &io.BufferedReader) !Request

parse_request parses a raw HTTP request into a Request object.

See also: parse_request_head, which parses only the headers.

#fn parse_request_head

fn parse_request_head(mut reader &io.BufferedReader) !Request

parse_request_head parses only the header of a raw HTTP request into a Request object

#fn parse_response

fn parse_response(resp string) !Response

Parse a raw HTTP response into a Response object

#fn patch

fn patch(url string, data string) !Response

patch sends string data as an HTTP PATCH request to the given url.

#fn post

fn post(url string, data string) !Response

post sends the string data as an HTTP POST request to the given url.

#fn post_form

fn post_form(url string, data map[string]string) !Response

post_form sends the map data as X-WWW-FORM-URLENCODED data to an HTTP POST request to the given url.

#fn post_json

fn post_json(url string, data string) !Response

post_json sends the JSON data as an HTTP POST request to the given url.

#fn post_multipart_form

fn post_multipart_form(url string, conf PostMultipartFormConfig) !Response

post_multipart_form sends multipart form data conf as an HTTP POST request to the given url.

#fn put

fn put(url string, data string) !Response

put sends string data as an HTTP PUT request to the given url.

#fn read_cookies

fn read_cookies(h map[string][]string, filter string) []&Cookie

Parses all "Cookie" values from the header h and returns the successfully parsed Cookies.

if filter isn't empty, only cookies of that name are returned

#fn read_set_cookies

fn read_set_cookies(h map[string][]string) []&Cookie

Parses all "Set-Cookie" values from the header h and returns the successfully parsed Cookies.

#fn status_from_int

fn status_from_int(code int) Status

status_from_int returns the corresponding enum field of Status given the code in integer value.

#fn unescape

deprecated:unescape is deprecated, use urllib.query_escape() instead
fn unescape(s string) string

#fn unescape_url

deprecated:unescape_url is deprecated, use urllib.query_unescape() instead
fn unescape_url(s string) string

#fn url_encode_form_data

fn url_encode_form_data(data map[string]string) string

url_encode_form_data converts mapped data to a URL encoded string.

#fn version_from_str

fn version_from_str(v string) Version

Structs

#fn new_header

fn new_header(kvs []HeaderConfig) Header

Create a new Header object

#fn (&Header) free

fn (mut h &Header) free()

#fn (&Header) add

fn (mut h &Header) add(key CommonHeader, value string)

add appends a value to the header key.

#fn (&Header) add_custom

fn (mut h &Header) add_custom(key string, value string) !

add_custom appends a value to a custom header key. This function will return an error if the key contains invalid header characters.

#fn (&Header) add_map

fn (mut h &Header) add_map(kvs map[CommonHeader]string)

add_map appends the value for each header key.

#fn (&Header) add_custom_map

fn (mut h &Header) add_custom_map(kvs map[string]string) !

add_custom_map appends the value for each custom header key.

#fn (&Header) set

fn (mut h &Header) set(key CommonHeader, value string)

set sets the key-value pair. This function will clear any other values that exist for the CommonHeader.

#fn (&Header) set_custom

fn (mut h &Header) set_custom(key string, value string) !

set_custom sets the key-value pair for a custom header key. This function will clear any other values that exist for the header. This function will return an error if the key contains invalid header characters.

#fn (&Header) delete

fn (mut h &Header) delete(key CommonHeader)

delete deletes all values for a key.

#fn (&Header) delete_custom

fn (mut h &Header) delete_custom(key string)

delete_custom deletes all values for a custom header key.

#fn (&Header) coerce

fn (mut h &Header) coerce(flags HeaderCoerceConfig)

coerce coerces data in the Header by joining keys that match case-insensitively into one entry.

#fn (Header) contains

fn (h Header) contains(key CommonHeader) bool

contains returns whether the header key exists in the map.

#fn (Header) contains_custom

fn (h Header) contains_custom(key string, flags HeaderQueryConfig) bool

contains_custom returns whether the custom header key exists in the map.

#fn (Header) get

fn (h Header) get(key CommonHeader) !string

get gets the first value for the CommonHeader, or none if the key does not exist.

#fn (Header) get_custom

fn (h Header) get_custom(key string, flags HeaderQueryConfig) !string

get_custom gets the first value for the custom header, or none if the key does not exist.

#fn (Header) starting_with

fn (h Header) starting_with(key string) !string

starting_with gets the first header starting with key, or none if the key does not exist.

#fn (Header) values

fn (h Header) values(key CommonHeader) []string

values gets all values for the CommonHeader.

#fn (Header) custom_values

fn (h Header) custom_values(key string, flags HeaderQueryConfig) []string

custom_values gets all values for the custom header.

#fn (Header) keys

fn (h Header) keys() []string

keys gets all header keys as strings

#fn (Header) render

manualfree
fn (h Header) render(flags HeaderRenderConfig) string

render renders the Header into a string for use in sending HTTP requests. All header lines will end in \r\n

#fn (Header) join

fn (h Header) join(other Header) Header

join combines two Header structs into a new Header struct

#fn (&Header) add_key

fn (mut h &Header) add_key(key string)

Helper function to add a key to the keys map

#fn (Header) str

fn (h Header) str() string

str returns the headers string as seen in HTTP/1.1 requests.

Key order is not guaranteed.

#struct HeaderConfig

pub struct HeaderConfig {
	key   CommonHeader
	value string
}

#struct HeaderCoerceConfig

params
pub struct HeaderCoerceConfig {
	canonicalize bool
}

#struct HeaderQueryConfig

params
pub struct HeaderQueryConfig {
	exact bool
}

#struct HeaderRenderConfig

params
pub struct HeaderRenderConfig {
	version      Version
	coerce       bool
	canonicalize bool
}

#struct FetchConfig

pub struct FetchConfig {
pub mut:
	url        string
	method     Method
	header     Header
	data       string
	params     map[string]string
	cookies    map[string]string
	user_agent string = 'v.http'
	verbose    bool
	//
	validate               bool   // set this to true, if you want to stop requests, when their certificates are found to be invalid
	verify                 string // the path to a rootca.pem file, containing trusted CA certificate(s)
	cert                   string // the path to a cert.pem file, containing client certificate(s) for the request
	cert_key               string // the path to a key.pem file, containing private keys for the client certificate(s)
	in_memory_verification bool   // if true, verify, cert, and cert_key are read from memory, not from a file
	allow_redirect         bool = true // whether to allow redirect
}

FetchConfig holds configuration data for the fetch function.

#struct PostMultipartFormConfig

params
pub struct PostMultipartFormConfig {
pub mut:
	form   map[string]string
	files  map[string][]FileData
	header Header
}

#struct Request

pub struct Request {
pub mut:
	version    Version = .v1_1
	method     Method
	header     Header
	cookies    map[string]string
	data       string
	url        string
	user_agent string = 'v.http'
	verbose    bool
	user_ptr   voidptr
	// NOT implemented for ssl connections
	// time = -1 for no timeout
	read_timeout  i64 = 30 * time.second
	write_timeout i64 = 30 * time.second
	//
	validate               bool // when true, certificate failures will stop further processing
	verify                 string
	cert                   string
	cert_key               string
	in_memory_verification bool // if true, verify, cert, and cert_key are read from memory, not from a file
	allow_redirect         bool = true // whether to allow redirect
}

Request holds information about an HTTP request (either received by a server or to be sent by a client)

#fn new_request

fn new_request(method Method, url_ string, data string) Request

new_request creates a new Request given the request method, url_, and data.

#fn (&Request) ssl_do

Linux
fn (req &Request) ssl_do(port int, method Method, host_name string, path string) !Response

#fn (&Request) free

fn (mut req &Request) free()

#fn (&Request) add_header

fn (mut req &Request) add_header(key CommonHeader, val string)

add_header adds the key and value of an HTTP request header To add a custom header, use add_custom_header

#fn (&Request) add_custom_header

fn (mut req &Request) add_custom_header(key string, val string) !

add_custom_header adds the key and value of an HTTP request header This method may fail if the key contains characters that are not permitted

#fn (&Request) do

fn (req &Request) do() !Response

do will send the HTTP request and returns http.Response as soon as the response is recevied

#fn (&Request) method_and_url_to_response

fn (req &Request) method_and_url_to_response(method Method, url net.urllib.URL) !Response

#fn (&Request) build_request_headers

fn (req &Request) build_request_headers(method Method, host_name string, path string) string

#fn (&Request) build_request_cookies_header

fn (req &Request) build_request_cookies_header() string

#fn (&Request) http_do

fn (req &Request) http_do(host string, method Method, path string) !Response

#fn (&Request) referer

fn (req &Request) referer() string

referer returns 'Referer' header value of the given request

#struct FileData

pub struct FileData {
pub:
	filename     string
	content_type string
	data         string
}

#struct UnexpectedExtraAttributeError

pub struct UnexpectedExtraAttributeError {
	Error
	attributes []string
}

#struct MultiplePathAttributesError

pub struct MultiplePathAttributesError {
	Error
}

#struct Response

pub struct Response {
pub mut:
	body         string
	text         string [deprecated: 'use Response.body instead'; deprecated_after: '2022-10-03']
	header       Header
	status_code  int
	status_msg   string
	http_version string
}

Response represents the result of the request

#fn new_response

fn new_response(conf ResponseConfig) Response

new_response creates a Response object from the configuration. This function will add a Content-Length header if body is not empty.

#fn (&Response) free

fn (mut resp &Response) free()

#fn (Response) bytes

fn (resp Response) bytes() []u8

Formats resp to bytes suitable for HTTP response transmission

#fn (Response) bytestr

fn (resp Response) bytestr() string

Formats resp to a string suitable for HTTP response transmission

#fn (Response) cookies

fn (r Response) cookies() []Cookie

cookies parses the Set-Cookie headers into Cookie objects

#fn (Response) status

fn (r Response) status() Status

status parses the status_code into a Status struct

#fn (&Response) set_status

fn (mut r &Response) set_status(s Status)

set_status sets the status_code and status_msg of the response

#fn (Response) version

fn (r Response) version() Version

version parses the version

#fn (&Response) set_version

fn (mut r &Response) set_version(v Version)

set_version sets the http_version string of the response

#struct ResponseConfig

pub struct ResponseConfig {
	version Version = .v1_1
	status  Status  = .ok
	header  Header
	body    string
	text    string  [deprecated: 'use ResponseConfig.body instead'; deprecated_after: '2022-10-03']
}

#struct Server

pub struct Server {
mut:
	state    ServerStatus = .closed
	listener net.TcpListener
pub mut:
	port           int           = 8080
	handler        Handler       = DebugHandler{}
	read_timeout   time.Duration = 30 * time.second
	write_timeout  time.Duration = 30 * time.second
	accept_timeout time.Duration = 30 * time.second
}

#fn (&Server) listen_and_serve

fn (mut s &Server) listen_and_serve()

listen_and_serve listens on the server port s.port over TCP network and uses s.parse_and_respond to handle requests on incoming connections with s.handler.

#fn (&Server) stop

inline
fn (mut s &Server) stop()

stop signals the server that it should not respond anymore.

#fn (&Server) close

inline
fn (mut s &Server) close()

close immediatly closes the port and signals the server that it has been closed.

#fn (&Server) status

inline
fn (s &Server) status() ServerStatus

status indicates whether the server is running, stopped, or closed.

#fn (&Server) parse_and_respond

fn (mut s &Server) parse_and_respond(mut conn &net.TcpConn)

Interfaces

This section is empty.

Enums

#enum SameSite

pub enum SameSite {
	same_site_default_mode = 1
	same_site_lax_mode
	same_site_strict_mode
	same_site_none_mode
}

SameSite allows a server to define a cookie attribute making it impossible for the browser to send this cookie along with cross-site requests. The main goal is to mitigate the risk of cross-origin information leakage, and provide some protection against cross-site request forgery attacks.

See https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00 for details.

#enum CommonHeader

pub enum CommonHeader {
	accept
	accept_ch
	accept_charset
	accept_ch_lifetime
	accept_encoding
	accept_language
	accept_patch
	accept_post
	accept_ranges
	access_control_allow_credentials
	access_control_allow_headers
	access_control_allow_methods
	access_control_allow_origin
	access_control_expose_headers
	access_control_max_age
	access_control_request_headers
	access_control_request_method
	age
	allow
	alt_svc
	authorization
	authority
	cache_control
	clear_site_data
	connection
	content_disposition
	content_encoding
	content_language
	content_length
	content_location
	content_range
	content_security_policy
	content_security_policy_report_only
	content_type
	cookie
	cross_origin_embedder_policy
	cross_origin_opener_policy
	cross_origin_resource_policy
	date
	device_memory
	digest
	dnt
	early_data
	etag
	expect
	expect_ct
	expires
	feature_policy
	forwarded
	from
	host
	if_match
	if_modified_since
	if_none_match
	if_range
	if_unmodified_since
	index
	keep_alive
	large_allocation
	last_modified
	link
	location
	nel
	origin
	pragma
	proxy_authenticate
	proxy_authorization
	range
	referer
	referrer_policy
	retry_after
	save_data
	sec_fetch_dest
	sec_fetch_mode
	sec_fetch_site
	sec_fetch_user
	sec_websocket_accept
	server
	server_timing
	set_cookie
	sourcemap
	strict_transport_security
	te
	timing_allow_origin
	tk
	trailer
	transfer_encoding
	upgrade
	upgrade_insecure_requests
	user_agent
	vary
	via
	want_digest
	warning
	www_authenticate
	x_content_type_options
	x_dns_prefetch_control
	x_forwarded_for
	x_forwarded_host
	x_forwarded_proto
	x_frame_options
	x_xss_protection
}

CommonHeader is an enum of the most common HTTP headers

fn (h CommonHeader) str() string

#enum Method

pub enum Method {
	get
	post
	put
	head
	delete
	options
	trace
	connect
	patch
}

The methods listed here are some of the most used ones, ordered by commonality. A comprehensive list is available at:

https://www.iana.org/assignments/http-methods/http-methods.xhtml

#fn (Method) str

fn (m Method) str() string

str returns the string representation of the HTTP Method m.

#enum ServerStatus

pub enum ServerStatus {
	running
	stopped
	closed
}

ServerStatus is the current status of the server.

.running means that the server is active and serving.

.stopped means that the server is not active but still listening.

.closed means that the server is completely inactive.

#enum Status

pub enum Status {
	unknown = -1
	unassigned = 0
	cont = 100
	switching_protocols = 101
	processing = 102
	checkpoint_draft = 103
	ok = 200
	created = 201
	accepted = 202
	non_authoritative_information = 203
	no_content = 204
	reset_content = 205
	partial_content = 206
	multi_status = 207
	already_reported = 208
	im_used = 226
	multiple_choices = 300
	moved_permanently = 301
	found = 302
	see_other = 303
	not_modified = 304
	use_proxy = 305
	switch_proxy = 306
	temporary_redirect = 307
	permanent_redirect = 308
	bad_request = 400
	unauthorized = 401
	payment_required = 402
	forbidden = 403
	not_found = 404
	method_not_allowed = 405
	not_acceptable = 406
	proxy_authentication_required = 407
	request_timeout = 408
	conflict = 409
	gone = 410
	length_required = 411
	precondition_failed = 412
	request_entity_too_large = 413
	request_uri_too_long = 414
	unsupported_media_type = 415
	requested_range_not_satisfiable = 416
	expectation_failed = 417
	im_a_teapot = 418
	misdirected_request = 421
	unprocessable_entity = 422
	locked = 423
	failed_dependency = 424
	unordered_collection = 425
	upgrade_required = 426
	precondition_required = 428
	too_many_requests = 429
	request_header_fields_too_large = 431
	unavailable_for_legal_reasons = 451
	client_closed_request = 499
	internal_server_error = 500
	not_implemented = 501
	bad_gateway = 502
	service_unavailable = 503
	gateway_timeout = 504
	http_version_not_supported = 505
	variant_also_negotiates = 506
	insufficient_storage = 507
	loop_detected = 508
	bandwidth_limit_exceeded = 509
	not_extended = 510
	network_authentication_required = 511
}

The status codes listed here are based on the comprehensive list, available at:

https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml

#fn (Status) str

fn (code Status) str() string

str returns the string representation of Status code.

#fn (Status) int

fn (code Status) int() int

int converts an assigned and known Status to its integral equivalent.

if a Status is unknown or unassigned, this method will return zero

#fn (Status) is_valid

fn (code Status) is_valid() bool

is_valid returns true if the status code is assigned and known

#fn (Status) is_error

fn (code Status) is_error() bool

is_error will return true if the status code represents either a client or a server error; otherwise will return false

#fn (Status) is_success

fn (code Status) is_success() bool

is_success will return true if the status code represents either an informational, success, or redirection response; otherwise will return false

#enum Version

pub enum Version {
	unknown
	v1_1
	v2_0
	v1_0
}

The versions listed here are the most common ones.

#fn (Version) str

fn (v Version) str() string

#fn (Version) protos

fn (v Version) protos() (int, int)

protos returns the version major and minor numbers