Skip to content

web #

Constants #

pub const (
	methods_with_form = [http.Method.post, .put, .patch]
	headers_close     = http.new_custom_header_from_map({
		'Server':                           'Vieter'
		http.CommonHeader.connection.str(): 'close'
	}) or { panic('should never fail') }

	http_302          = http.new_response(
		status: .found
		body: '302 Found'
		header: headers_close
	)
	http_400          = http.new_response(
		status: .bad_request
		body: '400 Bad Request'
		header: http.new_header(
			key: .content_type
			value: 'text/plain'
		).join(headers_close)
	)
	http_401          = http.new_response(
		status: .unauthorized
		body: '401 Unauthorized'
		header: http.new_header(
			key: .content_type
			value: 'text/plain'
		).join(headers_close)
	)
	http_404          = http.new_response(
		status: .not_found
		body: '404 Not Found'
		header: http.new_header(
			key: .content_type
			value: 'text/plain'
		).join(headers_close)
	)
	http_500          = http.new_response(
		status: .internal_server_error
		body: '500 Internal Server Error'
		header: http.new_header(
			key: .content_type
			value: 'text/plain'
		).join(headers_close)
	)
	mime_types        = {
		'.aac':    'audio/aac'
		'.abw':    'application/x-abiword'
		'.arc':    'application/x-freearc'
		'.avi':    'video/x-msvideo'
		'.azw':    'application/vnd.amazon.ebook'
		'.bin':    'application/octet-stream'
		'.bmp':    'image/bmp'
		'.bz':     'application/x-bzip'
		'.bz2':    'application/x-bzip2'
		'.cda':    'application/x-cdf'
		'.csh':    'application/x-csh'
		'.css':    'text/css'
		'.csv':    'text/csv'
		'.doc':    'application/msword'
		'.docx':   'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
		'.eot':    'application/vnd.ms-fontobject'
		'.epub':   'application/epub+zip'
		'.gz':     'application/gzip'
		'.gif':    'image/gif'
		'.htm':    'text/html'
		'.html':   'text/html'
		'.ico':    'image/vnd.microsoft.icon'
		'.ics':    'text/calendar'
		'.jar':    'application/java-archive'
		'.jpeg':   'image/jpeg'
		'.jpg':    'image/jpeg'
		'.js':     'text/javascript'
		'.json':   'application/json'
		'.jsonld': 'application/ld+json'
		'.mid':    'audio/midi audio/x-midi'
		'.midi':   'audio/midi audio/x-midi'
		'.mjs':    'text/javascript'
		'.mp3':    'audio/mpeg'
		'.mp4':    'video/mp4'
		'.mpeg':   'video/mpeg'
		'.mpkg':   'application/vnd.apple.installer+xml'
		'.odp':    'application/vnd.oasis.opendocument.presentation'
		'.ods':    'application/vnd.oasis.opendocument.spreadsheet'
		'.odt':    'application/vnd.oasis.opendocument.text'
		'.oga':    'audio/ogg'
		'.ogv':    'video/ogg'
		'.ogx':    'application/ogg'
		'.opus':   'audio/opus'
		'.otf':    'font/otf'
		'.png':    'image/png'
		'.pdf':    'application/pdf'
		'.php':    'application/x-httpd-php'
		'.ppt':    'application/vnd.ms-powerpoint'
		'.pptx':   'application/vnd.openxmlformats-officedocument.presentationml.presentation'
		'.rar':    'application/vnd.rar'
		'.rtf':    'application/rtf'
		'.sh':     'application/x-sh'
		'.svg':    'image/svg+xml'
		'.swf':    'application/x-shockwave-flash'
		'.tar':    'application/x-tar'
		'.tif':    'image/tiff'
		'.tiff':   'image/tiff'
		'.ts':     'video/mp2t'
		'.ttf':    'font/ttf'
		'.txt':    'text/plain'
		'.vsd':    'application/vnd.visio'
		'.wav':    'audio/wav'
		'.weba':   'audio/webm'
		'.webm':   'video/webm'
		'.webp':   'image/webp'
		'.woff':   'font/woff'
		'.woff2':  'font/woff2'
		'.xhtml':  'application/xhtml+xml'
		'.xls':    'application/vnd.ms-excel'
		'.xlsx':   'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
		'.xml':    'application/xml'
		'.xul':    'application/vnd.mozilla.xul+xml'
		'.zip':    'application/zip'
		'.3gp':    'video/3gpp'
		'.3g2':    'video/3gpp2'
		'.7z':     'application/x-7z-compressed'
	}
	max_http_post_size = 1024 * 1024
	default_port       = 8080
)
const attrs_to_ignore = ['auth', 'markused']

Method attributes that should be ignored when parsing, as they're used elsewhere.

fn filter #

fn filter(s string) string

filter Do not delete.
It used by vlib/v/gen/c/str_intp.v:130 for string interpolation inside web templates TODO: move it to template render

fn route_matches #

fn route_matches(url_words []string, route_words []string) ?[]string

route_matches returns wether a route matches

fn parse_query_from_url #

fn parse_query_from_url(url urllib.URL) map[string]string

Extracts query parameters from a URL.

fn run #

pub fn run[T](global_app &T, port int)

run runs the app

fn handle_conn #

fn handle_conn[T](mut conn net.TcpConn, mut app T, routes map[string]Route)

handle_conn handles a connection

fn parse_attrs #

fn parse_attrs(name string, attrs []string) !([]http.Method, string)

Parsing function attributes for methods and path.

fn parse_form_from_request #

fn parse_form_from_request(request http.Request) !(map[string]string, map[string][]http.FileData)

Extract form data from an HTTP request.

interface DbInterface #

interface DbInterface {
	db voidptr
}

struct FileData #

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

struct Context #

pub struct Context {
pub:
// HTTP Request
	req http.Request
// API key used when authenticating requests
	api_key string
// TODO Response
pub mut:
// TCP connection to client.
// But beware, do not store it for further use, after request processing web will close connection.
	conn &net.TcpConn = unsafe { nil }
// Gives access to a shared logger object
	logger shared log.Log
// Used to collect metrics on the web server
	collector &metrics.MetricsCollector
// time.ticks() from start of web connection handle.
// You can use it to determine how much time is spent on your request.
	page_gen_start i64
// REQUEST
	static_files      map[string]string
	static_mime_types map[string]string
// Map containing query params for the route.
// Example: `http://localhost:3000/index?q=vpm&order_by=desc => { 'q': 'vpm', 'order_by': 'desc' }
	query map[string]string
// Multipart-form fields.
	form map[string]string
// Files from multipart-form.
	files map[string][]http.FileData
// Allows reading the request body
	reader &io.BufferedReader = unsafe { nil }
// RESPONSE
	status       http.Status = http.Status.ok
	content_type string      = 'text/plain'
// response headers
	header http.Header
}

The Context struct represents the Context which hold the HTTP request and response.
It has fields for the query, form, files.

fn (Context) before_request #

pub fn (ctx Context) before_request()

Defining this method is optional.
before_request is called before every request (aka middleware).
Probably you can use it for check user session cookie or add header.

fn (Context) body #

pub fn (mut ctx Context) body(status http.Status, content_type string, body string) Result

body sends the given body as an HTTP response.

fn (Context) file #

pub fn (mut ctx Context) file(f_path string) Result

file Response HTTP_OK with file as payload This function manually implements responses because it needs to stream the file contents

fn (Context) is_authenticated #

pub fn (ctx &Context) is_authenticated() bool

is_authenticated checks whether the request passes a correct API key.

fn (Context) json #

pub fn (mut ctx Context) json[T](status http.Status, j T) Result

json[T] HTTP_OK with json_s as payload with content-type application/json

fn (Context) ldebug #

pub fn (mut ctx Context) ldebug(msg string)

ldebug create a log message with the debug level

fn (Context) lerror #

pub fn (mut ctx Context) lerror(msg string)

lerror create a log message with the error level

fn (Context) lfatal #

pub fn (mut ctx Context) lfatal(msg string)

lfatal create a log message with the fatal level

fn (Context) linfo #

pub fn (mut ctx Context) linfo(msg string)

linfo create a log message with the info level

fn (Context) lwarn #

pub fn (mut ctx Context) lwarn(msg string)

lwarn create a log message with the warn level

fn (Context) redirect #

pub fn (mut ctx Context) redirect(url string) Result

redirect Redirect to an url

fn (Context) send #

pub fn (mut ctx Context) send() bool

send is a convenience function for sending the HTTP response with an empty body.

fn (Context) send_custom_response #

fn (mut ctx Context) send_custom_response(resp &http.Response) !

send_custom_response sends the given http.Response to the client. It can be used to overwrite the Context object & send a completely custom http.Response instead.

fn (Context) send_reader #

fn (mut ctx Context) send_reader(mut reader io.Reader, size u64) !

send_reader reads at most size bytes from the given reader & writes them to the TCP connection socket. Internally, a 10KB buffer is used, to avoid having to store all bytes in memory at once.

fn (Context) send_reader_response #

pub fn (mut ctx Context) send_reader_response(mut reader io.Reader, size u64) bool

send_reader_response constructs the resulting HTTP response with the given body & streams the reader's contents to the client.

fn (Context) send_response #

pub fn (mut ctx Context) send_response(res string) bool

send_response constructs the resulting HTTP response with the given body string & sends it to the client.

fn (Context) send_response_header #

pub fn (mut ctx Context) send_response_header() !

send_response_header constructs a valid HTTP response with an empty body & sends it to the client.

fn (Context) send_string #

fn (mut ctx Context) send_string(s string) !

send_string writes the given string to the TCP connection socket.

fn (Context) server_error #

pub fn (mut ctx Context) server_error(ecode int) Result

server_error Response a server error

fn (Context) status #

pub fn (mut ctx Context) status(status http.Status) Result

status responds with an empty textual response, essentially only returning the given status code.

struct Route #

struct Route {
	methods []http.Method
	path    string
}

struct Result #

[noinit]
pub struct Result {}

A dummy structure that returns from routes to indicate that you actually sent something to a user