### V CLI Module: Basic Command Line Parsing Example Source: https://modules.vlang.io/cli.html Demonstrates how to use the `cli` module to create a command-line application with subcommands. It shows the setup and parsing of arguments from `os.args`. This example requires the `os` and `cli` modules. ```v module main import os import cli fn main() { mut app := cli.Command{ name: 'example-app' description: 'example-app' execute: fn (cmd cli.Command) ! { println('hello app') return } commands: [ cli.Command{ name: 'sub' execute: fn (cmd cli.Command) ! { println('hello subcommand') return } }, ] } app.setup() app.parse(os.args) } ``` -------------------------------- ### Setup and Run Benchmark in V Source: https://modules.vlang.io/x.benchmark.html Initializes a new benchmark instance using the setup function and executes it using the run method. The setup function requires a benchmark function and optional parameters defined in BenchmarkDefaults. ```V fn setup(bench_func fn () !, params BenchmarkDefaults) !Benchmark fn (mut b Benchmark) run() ``` -------------------------------- ### Initialize and Run a Terminal UI Application in V Source: https://modules.vlang.io/term.ui.html Demonstrates the basic setup of a term.ui application, including the definition of an App struct, event handling, and the main frame rendering loop. The application initializes the context and starts the main loop to handle terminal input and output. ```V import term.ui as tui struct App { mut: tui &tui.Context = unsafe { nil } } fn event(e &tui.Event, x voidptr) { if e.typ == .key_down && e.code == .escape { exit(0) } } fn frame(x voidptr) { mut app := unsafe { &App(x) } app.tui.clear() app.tui.set_bg_color(r: 63, g: 81, b: 181) app.tui.draw_rect(20, 6, 41, 10) app.tui.draw_text(24, 8, 'Hello from V!') app.tui.set_cursor_position(0, 0) app.tui.reset() app.tui.flush() } fn main() { mut app := &App{} app.tui = tui.init( user_data: app event_fn: event frame_fn: frame hide_cursor: true ) app.tui.run()! } ``` -------------------------------- ### Install PostgreSQL Server on Ubuntu/Debian Source: https://modules.vlang.io/db.pg.html Installs the PostgreSQL client and server packages on Ubuntu/Debian systems using apt. It also enables and starts the PostgreSQL service for automatic startup. ```shell sudo apt install postgresql postgresql-client sudo systemctl enable postgresql # to autostart on startup sudo systemctl start postgresql ``` -------------------------------- ### Install PostgreSQL Client Tools on Windows Source: https://modules.vlang.io/db.pg.html Guides users through installing PostgreSQL on Windows, emphasizing the selection of 'PostgreSQL Server' and 'Command Line Tools' to obtain necessary header files and DLLs. It also details adding the PostgreSQL 'bin' directory to the system PATH. ```plaintext Download the latest PostgreSQL version from the official website (currently https://www.enterprisedb.com/downloads/postgres-postgresql-downloads) In one of the steps in the installer, tick the following boxes: [X] PostgreSQL Server [ ] pgAdmin 4 [ ] Stack Builder [X] Command Line Tools We need PostgreSQL Server because it brings with it the C header files needed for building programs that link to `libpq.dll`. After finishing installation, add the folder `C:/Program Files/PostgreSQL//bin` to PATH. Any program that wants to use postgres client functionality require these DLLs found in `/bin`: - libcrypto-3-x64.dll - libiconv-2.dll - libintl-9.dll - libpq.dll - libssl-3-x64.dll - libwinpthread-1.dll If you want to compile with MSVC, you will need to copy `C:/Program Files/PostgreSQL//bin/libpq.lib` into the `@VEXEROOT/thirdparty/pg/win64/msvc` directory. Navigate to `C:/Program Files/PostgreSQL//include`. There you will find the files: - `libpq-fe.h` - `pg_config.h` - `postgres_ext.h` Copy the header files into `@VEXEROOT/thirdparty/pg/libpq`. You can now compile programs using the `db.pg` module. --- After building an executable that uses `db.pg`, you may want to distribute it to others who might not have the postgres DLLs installed on their machine. All you need to do is to make sure a copy of all the required DLLs are in the same folder as your executable. ``` -------------------------------- ### Quick Start: Connect, Set, Get, and Increment Redis Values Source: https://modules.vlang.io/db.redis.html Demonstrates the basic usage of the Redis client, including establishing a connection, setting string and integer values, retrieving them, and performing an increment operation. It highlights type-safe retrieval and basic error handling with the '!' operator. ```v module main import db.redis fn main() { // Connect to Redis // Uncomment passwod line if authentication is needed mut db := redis.connect(redis.Config{ // Available Config options (none of which need to be specified if you want the defauilts): // host: 'localhost' - default // password: 'your_password' - no default, you need to supply password if your redis server // is set up to need one // port: 6379 - default // tls: false - default, set to true for ssl connection })! println('Server supports RESP${db.version} protocol') // Set and get values db.set('name', 'Alice')! name := db.get[string]('name')! println('Name: ${name}') // Output: Name: Alice // Integer operations db.set('counter', 42)! db.incr('counter')! counter := db.get[int]('counter')! println('Counter: ${counter}') // Output: Counter: 43 // Clean up db.close()! } ``` -------------------------------- ### Start Golang Builder Source: https://modules.vlang.io/v.builder.golangbuilder.html Initializes the Golang builder process. This function serves as the entry point for starting the build or compilation sequence. ```v fn start() ``` -------------------------------- ### Convenience Benchmarking with start() and measure() in Vlang Source: https://modules.vlang.io/benchmark.html Illustrates the use of `start()` and `measure()` for concise benchmarking of code sections. This method simplifies timing small code snippets by automatically handling the start and stop of timers for labeled sections. It's a convenient alternative to manual step management for quick performance checks. ```vlang import time import benchmark mut b := benchmark.start() // your code section 1 ... time.sleep(1500 * time.millisecond) b.measure('code_1') // your code section 2 ... time.sleep(500 * time.millisecond) b.measure('code_2') ``` -------------------------------- ### Usage Examples Source: https://modules.vlang.io/goroutines.html Demonstrates how to use the `go` keyword for launching goroutines and `spawn` for OS threads. ```APIDOC ## Usage ```v // `go` launches a goroutine (lightweight, scheduled by GMP) go expensive_computation() // `spawn` launches an OS thread (traditional V behavior) spawn blocking_io_task() ``` ``` -------------------------------- ### Install PostgreSQL Server on Fedora Source: https://modules.vlang.io/db.pg.html Installs the PostgreSQL server and contrib packages on Fedora systems using dnf. It also enables and starts the PostgreSQL service for automatic startup. ```shell sudo dnf install postgresql-server postgresql-contrib sudo systemctl enable postgresql # to autostart on startup sudo systemctl start postgresql ``` -------------------------------- ### Benchmark Start Function in Vlang Source: https://modules.vlang.io/benchmark.html The `start()` function is a convenience method that returns a new, running `Benchmark` instance. It is equivalent to calling `new_benchmark().step()`, providing a quick way to begin a benchmark session. ```vlang fn start() Benchmark ``` -------------------------------- ### Register Controller with Hostname and Path in Veb Source: https://modules.vlang.io/veb.html Registers a controller to handle requests for a specific hostname and path prefix. This example registers the 'Example' controller to handle all routes starting with '/' on 'example.com'. ```vlang mut example_app := &Example{} // set the controllers hostname to 'example.com' and handle all routes starting with '/', // we handle requests with any route to 'example.com' app.register_controller[Example, Context]('example.com', '/', mut example_app)! ``` -------------------------------- ### Install PostgreSQL on macOS (Homebrew) Source: https://modules.vlang.io/db.pg.html Installs PostgreSQL using Homebrew on macOS and starts the service. Note that the service name might be versioned (e.g., postgresql@18) on newer setups. ```shell brew install postgresql brew services start postgresql ``` -------------------------------- ### Vlang sokol.sgl Setup and Shutdown Functions Source: https://modules.vlang.io/sokol.sgl.html Functions for initializing and de-initializing the sokol.sgl library. The `setup` function takes a descriptor, and `shutdown` performs cleanup. ```v fn setup(desc &Desc) ``` ```v fn shutdown() ``` -------------------------------- ### Initialize and Run Veb App with MemoryStore Source: https://modules.vlang.io/x.sessions.html Configures the application with a MemoryStore and a secret key to start the web server. ```V fn main() { mut app := &App{ store: sessions.MemoryStore[User]{} secret: 'my secret'.bytes() } veb.run[App, Context](mut app, 8080) } ``` -------------------------------- ### Perform Regex String Matching Source: https://modules.vlang.io/regex.html A complete example showing how to initialize a regex pattern, match it against a string, and extract captured groups by index or name. ```v import regex fn main() { txt := 'http://www.ciao.mondo/hello/pippo12_/pera.html' query := r'(?Phttps?)|(?Pftps?)://(?P[\w_]+.)+' mut re := regex.regex_opt(query) or { panic(err) } start, end := re.match_string(txt) if start >= 0 { println('Match (${start}, ${end}) => [${txt[start..end]}]') for g_index := 0; g_index < re.group_count; g_index++ { println('#${g_index} [${re.get_group_by_id(txt, g_index)}] bounds: ${re.get_group_bounds_by_id(g_index)}') } for name in re.group_map.keys() { println('group:"${name}" \t=> [${re.get_group_by_name(txt, name)}] bounds: ${re.get_group_bounds_by_name(name)}') } } else { println('No Match') } } ``` -------------------------------- ### Run HTTP Server Source: https://modules.vlang.io/fasthttp.html Starts the server instance and begins listening for incoming network connections. ```v fn (mut server Server) run() ! ``` -------------------------------- ### Custom Replace Function Example (Vlang) Source: https://modules.vlang.io/regex.html Provides a practical example of using `replace_by_fn`. It defines a custom callback `my_repl` that extracts specific captured groups and formats them into the replacement string. The example demonstrates replacing parts of a string based on a regex pattern and the custom logic. ```v import regex fn my_repl(re regex.RE, in_txt string, start int, end int) string { g0 := re.get_group_by_id(in_txt, 0) g1 := re.get_group_by_id(in_txt, 1) g2 := re.get_group_by_id(in_txt, 2) return '*${g0}*${g1}*${g2}*' } fn main() { txt := 'today [John] is gone to his house with (Jack) and [Marie].' query := r'(.)(\A\w+)(.)' mut re := regex.regex_opt(query) or { panic(err) } result := re.replace_by_fn(txt, my_repl) println(result) } ``` -------------------------------- ### Prepare Tool if Needed Source: https://modules.vlang.io/v.util.html The `prepare_tool_when_needed` function ensures that a specified tool is ready for use, performing any necessary setup or compilation. ```v fn prepare_tool_when_needed(source_name string) ``` -------------------------------- ### Veb.auth Module Usage Example Source: https://modules.vlang.io/veb.auth.html This example demonstrates how to integrate and use the veb.auth module within a Veb application. It covers setting up the application with a database connection, initializing the auth module, and implementing user registration and login functionalities. It also shows how to generate salts, hash passwords, compare hashes, and manage authentication tokens. ```v import veb import db.pg import veb.auth pub struct App { veb.StaticHandler pub mut: db pg.DB auth auth.Auth[pg.DB] // or auth.Auth[sqlite.DB] etc } const port = 8081 pub struct Context { veb.Context current_user User } struct User { id int @[primary; sql: serial] name string password_hash string salt string } fn main() { mut app := &App{ // Use your actual local PostgreSQL password here. db: pg.connect(host: 'localhost', user: 'postgres', password: 'password', dbname: 'postgres')! } app.auth = auth.new(app.db) veb.run[App, Context](mut app, port) } @[post] pub fn (mut app App) register_user(mut ctx Context, name string, password string) veb.Result { salt := auth.generate_salt() new_user := User{ name: name password_hash: auth.hash_password_with_salt(password, salt) salt: salt } user_id := sql app.db { insert new_user into User } or { 0 } // Generate and insert the token using user ID token := app.auth.add_token(user_id) or { '' } // Authenticate the user by adding the token to the cookies ctx.set_cookie(name: 'token', value: token) return ctx.redirect('/') } @[post] pub fn (mut app App) login_post(mut ctx Context, name string, password string) veb.Result { user := app.find_user_by_name(name) or { ctx.error('Bad credentials') return ctx.redirect('/login') } // Verify user password using veb.auth if !auth.compare_password_with_hash(password, user.salt, user.password_hash) { ctx.error('Bad credentials') return ctx.redirect('/login') } // Find the user token in the Token table token := app.auth.add_token(user.id) or { '' } // Authenticate the user by adding the token to the cookies ctx.set_cookie(name: 'token', value: token) return ctx.redirect('/') } pub fn (mut app App) find_user_by_name(name string) ?User { // ... db query return User{} } ``` -------------------------------- ### Event Publishing Example (V) Source: https://modules.vlang.io/eventbus.html Shows how to define custom event arguments and publish an event using the EventBus. This example includes the definition of structs for work and error data. ```v module main import eventbus const eb = eventbus.new[string]() struct Work { hours int } struct AnError { message string } fn do_work() { work := Work{20} // get a mutable Params instance & put some data into it error := &AnError{'Error: no internet connection.'} // publish the event eb.publish('error', work, error) } ``` -------------------------------- ### Server Run Method Source: https://modules.vlang.io/fasthttp.html Starts the HTTP server and begins listening for incoming network connections. ```APIDOC ## fn (Server) run ### Description Starts the server and begins listening for incoming connections. ### Method `run` (method on `Server` struct) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```v server.run() ``` ### Response #### Success Response None (server runs indefinitely until stopped or error) #### Response Example None ### Error Handling Throws an error if the server fails to start or encounters a critical issue during operation. ``` -------------------------------- ### begin Function Source: https://modules.vlang.io/orm.html Starts a new ORM transaction on a provided connection. ```APIDOC ## fn begin ```v fn begin(mut conn TransactionalConnection) !Tx ``` begin starts a new ORM transaction on the provided connection. ``` -------------------------------- ### Replace Matches with Groups Example (Vlang) Source: https://modules.vlang.io/regex.html Demonstrates the usage of the `replace` function with group references in the replacement string. The example shows how to replace matches using captured groups, specifically group 0 (the entire match). ```v txt := 'Today it is a good day.' query := r'(a\w)[ ,.]' mut re := regex.regex_opt(query)? res := re.replace(txt, r'__<0>__') println(res) ``` -------------------------------- ### Veb Web Server Basic Setup and Run Source: https://modules.vlang.io/veb.html Demonstrates the basic structure for a Veb web application, including defining User and Context structs, an App struct for shared data, and the main function to run the server. It shows how to import the 'veb' module and configure the application context. ```v module main import veb pub struct User { pub mut: name string id int } // Our context struct must embed `veb.Context`! pub struct Context { veb.Context pub mut: // In the context struct we store data that could be different // for each request. Like a User struct or a session id user User session_id string } pub struct App { pub: // In the app struct we store data that should be accessible by all endpoints. // For example, a database or configuration values. secret_key string } // This is how endpoints are defined in veb. This is the index route pub fn (app &App) index(mut ctx Context) veb.Result { return ctx.html('

Hello V!

The secret key is "${app.secret_key}"

') } fn main() { mut app := &App{ secret_key: 'secret' } // Pass the App and context type and start the web server on port 8080 veb.run[App, Context](mut app, 8080) } ``` -------------------------------- ### Initialize and Run a vweb Application Source: https://modules.vlang.io/vweb.html Demonstrates how to define an App struct embedding vweb.Context and start the server using vweb.run or vweb.run_at with specific parameters. ```v import vweb struct App { vweb.Context } fn main() { vweb.run(&App{}, 8080) // or // vweb.run_at(new_app(), vweb.RunParams{ // host: 'localhost' // port: 8099 // family: .ip // }) or { panic(err) } } ``` -------------------------------- ### Get Header Starting With Key (V) Source: https://modules.vlang.io/net.http.html Retrieves the first header that starts with the specified key. Returns an empty string if the key is not found. This function is part of the Header type. ```v fn (h Header) starting_with(key string) !string ``` -------------------------------- ### VLang Regex: Setting Flags Example Source: https://modules.vlang.io/regex.html Demonstrates how to set flags to modify the behavior of the VLang regex parser. The example shows setting the `f_bin` flag, which enables byte-level parsing and disables UTF-8 management. ```v // example of flag settings mut re := regex.new() re.flag = regex.f_bin ``` -------------------------------- ### launch_tool Source: https://modules.vlang.io/v.util.html Starts a V tool in a separate process, passing it the specified arguments. It includes an auto-recompilation mechanism to ensure tools are up-to-date. ```APIDOC ## fn launch_tool ### Description Starts a V tool in a separate process, passing it the `args`. All V tools are located in the `cmd/tools` folder, in files or folders prefixed by the letter `v`, followed by the tool name (e.g., `cmd/tools/vdoc/` or `cmd/tools/vpm.v`). The folder variant is suitable for larger and more complex tools like `v doc`, as it allows splitting source code into separate `.v` files and organizing resources like static CSS/text/JS files. `launch_tool` uses a timestamp-based detection mechanism, so after `v self`, each tool will be recompiled before use, guaranteeing it's up-to-date with V itself. This mechanism can be disabled by creating/touching a file named `.disable_autorecompilation` in `cmd/tools/` or by changing the timestamps of all executables in `cmd/tools/` to be less than 1024 seconds (Unix time). ### Method N/A (Internal function) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Audio Setup and Streaming Callbacks Source: https://modules.vlang.io/sokol.audio.html Functions to initialize the audio backend and define streaming callbacks. The streaming callbacks allow for custom audio data processing in a separate thread. ```V previously_parsed_wavfile_bytes := [f32(0),0,0,0]; mycallback := fn (buffer &f32, num_frames int, num_channels int, mut sb []f32) {}; mut soundbuffer := []f32{}; soundbuffer << previously_parsed_wavfile_bytes; audio.setup(stream_userdata_cb: mycallback, user_data: soundbuffer.data); ``` -------------------------------- ### Get Vorbis sample offset Source: https://modules.vlang.io/encoding.vorbis.html Returns the current offset in samples from the start of the file. Returns -1 if the offset is unknown. ```V fn C.stb_vorbis_get_sample_offset(f &C.stb_vorbis) i32 ``` -------------------------------- ### DoublyLinkedList: Get Backwards Iterator Instance Source: https://modules.vlang.io/datatypes.html Returns a new backwards iterator instance for traversing a DoublyLinkedList from end to start. ```v fn (mut list DoublyLinkedList[T]) back_iterator() DoublyListIterBack[T] ``` -------------------------------- ### Initialize and Run HTTP Server in V Source: https://modules.vlang.io/fasthttp.html Demonstrates how to create a new server instance with a custom request handler and start it on a specified port. The handler processes raw request buffers and returns formatted HTTP responses. ```V import fasthttp fn handle_request(req fasthttp.HttpRequest) ![]u8 { path := req.buffer[req.path.start..req.path.start + req.path.len].bytestr() mut body := '' mut status_line := '' if path == '/' { body = 'Hello, World!\n' status_line = 'HTTP/1.1 200 OK' } else { body ='${path} not found\n' status_line = 'HTTP/1.1 404 Not Found' } headers := [ status_line, 'Content-Type: text/plain', 'Content-Length: ${body.len}', 'Connection: close', ] header_string := headers.join('\r\n') return '${header_string}\r\n\r\n${body}'.bytes() } fn main() { mut server := fasthttp.new_server(fasthttp.ServerConfig{ port: 3000 handler: handle_request }) or { eprintln('Failed to create server: ${err}') return } println('Server listening on http://localhost:3000') server.run() or { eprintln('error: ${err}') } } ``` -------------------------------- ### Static File Server Source: https://modules.vlang.io/net.http.file.html Starts a static files web server to serve files from a specified directory. ```APIDOC ## POST /serve ### Description Starts a static files web server. By default, it serves files from the current directory on port 4001. ### Method POST ### Endpoint /serve ### Parameters #### Request Body - **folder** (string) - Optional - The directory to serve files from. Defaults to the current directory. - **index_file** (string) - Optional - The name of the index file to serve for directory requests. Defaults to 'index.html'. - **auto_index** (bool) - Optional - If true, lists files automatically when an index file is not present. Defaults to true. - **on** (string) - Optional - The address and port to listen on. Defaults to 'localhost:4001'. - **filter_myexe** (bool) - Optional - Whether to filter the executable name from automatic directory listings. Defaults to true. - **workers** (int) - Optional - The number of worker threads to use for serving responses. Defaults to the number of available cores. - **shutdown_after** (time.Duration) - Optional - The duration after which the web server will gracefully shut down. Defaults to infinite. ### Request Example ```json { "folder": "/tmp", "on": ":5002" } ``` ### Response #### Success Response (200) This endpoint does not return a specific JSON response upon success; it starts a server process. #### Response Example (No specific JSON response for success) ``` -------------------------------- ### Find String Between Delimiters (Vlang) Source: https://modules.vlang.io/builtin.html The `find_between` function extracts the substring located between a specified start and end delimiter. It returns the content found strictly between the first occurrence of `start` and the first occurrence of `end`. Example: `'hey [man] how you doin'.find_between('[', ']') == 'man'`. ```v fn (s string) find_between(start string, end string) string ``` -------------------------------- ### Vlang Gen: Get Array Depth Source: https://modules.vlang.io/v.gen.c.html Calculates and returns the depth of an array type. For example, an array of arrays would have a depth greater than 1. ```v fn (mut g Gen) get_array_depth(el_typ ast.Type) int ``` -------------------------------- ### Get Server Version String (Vlang) Source: https://modules.vlang.io/db.mysql.html Returns the MySQL server version as a string, for example, '8.0.24'. This provides a human-readable representation of the server's version. ```v fn (db &DB) get_server_info() string ``` -------------------------------- ### System and Module Management Source: https://modules.vlang.io/v.util.html Functions to manage module installations, retrieve build metadata, and handle system-level cache cleanup. ```v fn check_module_is_installed(modulename string, is_verbose bool, need_update bool) !bool fn ensure_modules_for_all_tools_are_installed(is_verbose bool) fn free_caches() fn get_build_time() time.Time fn get_timers() &Timers fn join_env_vflags_and_os_args() []string ``` -------------------------------- ### Find All Matches (Vlang) Source: https://modules.vlang.io/regex.html Finds all non-overlapping occurrences of the pattern in the input string. Returns a list of integers representing the start and end indices of each match. For example, `[3,4,6,8]` indicates matches at `[3,4]` and `[6,8]`. ```v pub fn (mut re RE) find_all(in_txt string) []int ``` -------------------------------- ### Get Total Physical Memory (Vlang) Source: https://modules.vlang.io/runtime.html Retrieves the total amount of physical memory (RAM) available on the system. This value represents the total installed memory capacity. ```Vlang fn total_memory() !usize ``` -------------------------------- ### Get current file cursor position with tell Source: https://modules.vlang.io/os.html Returns the current byte offset of the file cursor from the start of the file. Useful for tracking positions to be used later with seek operations. ```v fn (f &File) tell() !i64 ``` -------------------------------- ### Get Indentation Width (Vlang) Source: https://modules.vlang.io/builtin.html The `indent_width` function calculates the number of leading spaces or tabs at the beginning of a string. It returns an integer representing this indentation. Examples show how it counts spaces and tabs. ```v fn (s string) indent_width() int ``` ```v assert ' v'.indent_width() == 2 ``` ```v assert '\t\tv'.indent_width() == 2 ``` -------------------------------- ### V UI Context Initialization Source: https://modules.vlang.io/gg.html The `begin` function prepares the UI context for drawing operations. It is a prerequisite for rendering any UI elements within the application. ```v fn (ctx &Context) begin() ``` -------------------------------- ### Get String Representation of String Array (Vlang) Source: https://modules.vlang.io/builtin.html Returns a string representation of a string slice, formatted like `['a', 'b', 'c']`. Example: `['a', 'b', 'c'].str()` results in `'['a', 'b', 'c']'`. ```v fn (a []string) str() string ``` -------------------------------- ### Get Current Character Source: https://modules.vlang.io/strings.textscanner.html Returns the character code at the current scanner position. Returns -1 if at the start of the input and no character has been read yet. After calling `ts.next()`, `ts.current()` will return the same character code. ```Vlang fn (mut ss TextScanner) current() int ``` -------------------------------- ### Initialize ChaCha20 Cipher Instances Source: https://modules.vlang.io/x.crypto.chacha20.html Demonstrates how to create different variants of the ChaCha20 cipher, including standard IETF, original, and XChaCha20 constructions by providing appropriate key and nonce lengths. ```V import crypto.rand import x.crypto.chacha20 fn main() { // 1. Creates a standard IETF variant, supplied with 12-bytes nonce key0 := rand.read(32)! nonce0 := rand.read(12)! mut c0 := chacha20.new_cipher(key0, nonce0)! // 2. Creates an original (DJ Bernstein) variant, supplied with 8-bytes nonce key1 := rand.read(32)! nonce1 := rand.read(8)! mut c1 := chacha20.new_cipher(key1, nonce1)! // 3. Creates an eXtended ChaCha20 construction with 64-bit counter key2 := rand.read(32)! nonce2 := rand.read(24)! mut c2 := chacha20.new_cipher(key2, nonce2, use_64bit_counter: true)! } ``` -------------------------------- ### Vlang JSON-RPC Client Initialization and Notification Source: https://modules.vlang.io/net.jsonrpc.html Illustrates how to initialize a JSON-RPC client using `net.jsonrpc.new_client` and send a notification. The client can work with any `io.ReaderWriter`, and this example shows a basic setup connecting to a TCP address. ```v import net import net.jsonrpc addr := '127.0.0.1:42228' mut stream := net.dial_tcp(addr)! mut c := jsonrpc.new_client(jsonrpc.ClientConfig{ stream: stream }) c.notify('kv.create', { 'key': 'bazz' 'value': 'barr' })! ``` -------------------------------- ### V Method Signature: (Main) run Source: https://modules.vlang.io/v.pkgconfig.html Defines the `run` method for the `Main` struct. This method likely executes the logic of the command-line tool based on the provided options and arguments. ```v fn (mut m Main) run() !string ``` -------------------------------- ### Connect and Query SQL Server using db.mssql Source: https://modules.vlang.io/db.mssql.html Demonstrates how to initialize a connection using the Config helper and execute a SQL query. It requires a valid ODBC driver and proper server credentials. ```v import db.mssql fn test_example() ? { // connect to server config := mssql.Config{ driver: 'ODBC Driver 17 for SQL Server' server: 'tcp:localhost' uid: '' pwd: '' } mut conn := mssql.Connection{} conn.connect(config.get_conn_str())? defer { conn.close() } // get current db name mut query := 'SELECT DB_NAME()' mut res := conn.query(query)? assert res == mssql.Result{ rows: [mssql.Row{ vals: ['master'] }] num_rows_affected: -1 } } ``` -------------------------------- ### Get the byte length of a UTF-8 character Source: https://modules.vlang.io/builtin.html The `utf8_char_len` function determines the number of bytes a UTF-8 encoded codepoint occupies, given its starting byte. This is useful for iterating over UTF-8 strings byte by byte. ```v fn utf8_char_len(b u8) int ``` -------------------------------- ### Launch V Tool with Arguments Source: https://modules.vlang.io/v.util.html The `launch_tool` function starts a V tool in a separate process, providing it with specified arguments. Tools are located in `cmd/tools/` and are automatically recompiled if they are outdated. Autorecompilation can be disabled. ```v fn launch_tool(is_verbose bool, tool_name string, args []string) ``` -------------------------------- ### Get Server Version Integer (Vlang) Source: https://modules.vlang.io/db.mysql.html Returns the MySQL server version as an unsigned 64-bit integer. The format is XYYZZ, where X is major, YY is minor, and ZZ is sub-version. For example, 8.0.24 becomes 80024. ```v fn (db &DB) get_server_version() u64 ``` -------------------------------- ### Get Short Module Name (Vlang) Source: https://modules.vlang.io/v.fmt.html Returns a shortened version of a module name, typically by removing the parent module path. For example, 'foo.bar.baz' becomes 'bar.baz'. It takes a module name string and returns the shortened string. ```vlang fn (mut f Fmt) short_module(name string) string ``` -------------------------------- ### Initialize Clipboard Instances Source: https://modules.vlang.io/clipboard.dummy.html Functions to create new clipboard instances. new_clipboard creates a standard instance, while new_primary targets X11 primary selection. ```v fn new_clipboard() &Clipboard fn new_primary() &Clipboard ``` -------------------------------- ### Get Trimmed String Indices Source: https://modules.vlang.io/builtin.html Returns the new start and end indices of a string after removing characters specified in 'cutset' from its beginning and end. Useful as input for the substr() function. If the string only contains characters from 'cutset', both indices will be zero. ```v fn (s string) trim_indexes(cutset string) (int, int) left, right := '-hi-'.trim_indexes('-'); assert left == 1; assert right == 3 ``` -------------------------------- ### Initialize Web Controllers Source: https://modules.vlang.io/veb.html Functions to generate controller paths for the main application, including support for host-specific routing. ```V fn controller[A, X](path string, mut global_app A) !&ControllerPath fn controller_host[A, X](host string, path string, mut global_app A) &ControllerPath ``` -------------------------------- ### Check if String Starts with a Capital Letter (Vlang) Source: https://modules.vlang.io/builtin.html The `is_capital` function checks if the first character of a string is an uppercase letter and all subsequent characters are not. It returns `true` if this condition is met, and `false` otherwise. Examples illustrate correct and incorrect cases. ```v fn (s string) is_capital() bool ``` ```v assert 'Hello'.is_capital() == true ``` ```v assert 'HelloWorld'.is_capital() == false ``` -------------------------------- ### V Regex: Accessing Captured Groups by ID Source: https://modules.vlang.io/regex.html Illustrates how to access captured regex groups directly using their IDs in V. It shows the use of `get_group_by_id` to retrieve the group's string content and `get_group_bounds_by_id` to get its start and end indices within the original text. ```V txt := 'my used string....' for g_index := 0; g_index < re.group_count; g_index++ { println('#${g_index} [${re.get_group_by_id(txt, g_index)}] }] bounds: ${re.get_group_bounds_by_id(g_index)}' } ``` -------------------------------- ### FTP Connection and Initialization Source: https://modules.vlang.io/net.ftp.html Functions for creating an FTP instance and establishing a connection. ```APIDOC ## `new()` ### Description Creates and returns a new `FTP` instance. ### Method `new` ### Endpoint N/A (Constructor) ### Parameters None ### Request Example ```vlang ftp := net.ftp.new() ``` ### Response #### Success Response (200) - `FTP` (object) - An initialized FTP client instance. ### Response Example ```json { "instance": "" } ``` ## `connect(oaddress string)` ### Description Establishes an FTP connection to the specified host and port. ### Method `connect` ### Endpoint N/A (Method on FTP instance) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```vlang ftp := net.ftp.new() connected := ftp.connect("ftp.example.com:21") ``` ### Response #### Success Response (200) - `bool` - `true` if the connection was successful, `false` otherwise. #### Response Example ```json { "connected": true } ``` ``` -------------------------------- ### Veb Route Matching Order with Parameters Source: https://modules.vlang.io/veb.html Demonstrates how Veb matches routes based on definition order, prioritizing routes with parameters over simpler ones. This ensures dynamic paths are handled correctly before static paths. ```Veb @['/:path'] pub fn (app &App) with_parameter(mut ctx Context, path string) veb.Result { return ctx.text('from with_parameter, path: "${path}"') } @['/normal'] pub fn (app &App) normal(mut ctx Context) veb.Result { return ctx.text('from normal') } ``` -------------------------------- ### Disable Automatic Recompilation with disabling_file Source: https://modules.vlang.io/v.util.recompilation.html The `disabling_file` function returns the path to a file that, when present, prevents V from automatically recompiling itself. This is useful for package managers to disable features like `v up` and `v self`, guiding users to install V from source. ```v fn disabling_file(vroot string) string ``` -------------------------------- ### VLang PostgreSQL Event Loop with Polling Source: https://modules.vlang.io/db.pg.html Shows how to create an event loop for real-time PostgreSQL notifications using the socket file descriptor with polling. This example demonstrates getting the socket file descriptor and implementing a loop to continuously consume input and retrieve notifications. ```vlang import db.pg import time fn main() { db := pg.connect(pg.Config{ user: 'postgres', password: 'password', dbname: 'mydb' })! defer { db.close() or {} } db.listen('events')! // Get socket fd for polling (useful with select/epoll) socket_fd := db.socket() println('Socket FD: ${socket_fd}') // Simple polling loop for { db.consume_input()! for { notification := db.get_notification() or { break } println('Event: ${notification.channel} - ${notification.payload}') } time.sleep(100 * time.millisecond) } } ``` -------------------------------- ### Initialize WebSocket Client and Server Source: https://modules.vlang.io/net.websocket.html Functions to instantiate new WebSocket clients and servers. new_client requires an address and options, while new_server requires network family, port, route, and server options. ```V fn new_client(address string, opt ClientOpt) !&Client fn new_server(family net.AddrFamily, port int, route string, opt ServerOpt) &Server ``` -------------------------------- ### DB Pipeline Start Source: https://modules.vlang.io/db.redis.html Starts a new pipeline for batching commands. ```APIDOC ## POST /db/pipeline/start ### Description Starts a new pipeline for batching commands. ### Method POST ### Endpoint /db/pipeline/start ### Parameters None ### Request Example None ### Response #### Success Response (200) - **status** (string) - Indicates that the pipeline has started. #### Response Example ```json { "status": "Pipeline started" } ``` ``` -------------------------------- ### Platform and Architecture Utilities Source: https://modules.vlang.io/v.pref.html Helper functions to resolve architecture and operating system types from strings, and to retrieve current host environment details. ```v fn arch_from_string(arch_str string) !Arch fn os_from_string(os_str string) !OS fn get_host_arch() Arch fn get_host_os() OS ``` -------------------------------- ### Event Bus Initialization and Usage (V) Source: https://modules.vlang.io/eventbus.html Demonstrates how to initialize an EventBus instance and subscribe to events. It highlights the need to subscribe before publishing and the structure of event handlers. ```v module main import eventbus // initialize it globally const eb = eventbus.new[string]() fn main() { // get a mutable reference to the subscriber mut sub := eb.subscriber // subscribe to the 'error' event sub.subscribe('error', on_error) // start the work do_work() } // the event handler fn on_error(receiver voidptr, e &Error, work &Work) { println('error occurred on ${work.hours}. Error: ${e.message}') } ``` -------------------------------- ### Find Substring Index After a Start Position (Vlang - Returns -1 if not found) Source: https://modules.vlang.io/builtin.html The `index_after_` function searches for the first occurrence of a substring starting from a specified position. It returns the index as an integer, or `-1` if the substring is not found after the `start` index. ```v fn (s string) index_after_(p string, start int) int ``` -------------------------------- ### Initialize Build Environment Source: https://modules.vlang.io/v.build_constraint.html Creates a new Environment instance by processing lists of facts and user-defined build flags. The facts represent system-level properties, while defines represent custom build configurations. ```v fn new_environment(facts []string, defines []string) &Environment ``` -------------------------------- ### Find Substring Index After a Start Position (Vlang) Source: https://modules.vlang.io/builtin.html The `index_after` function searches for the first occurrence of a substring starting from a specified position. It returns an optional integer (`?int`) representing the index, or `none` if the substring is not found after the `start` index. ```v fn (s string) index_after(p string, start int) ?int ``` -------------------------------- ### Create and Drop Tables using V ORM Source: https://modules.vlang.io/orm.html Illustrates how to create and drop database tables by passing V structs to the `create table` and `drop table` commands within a `sql` block. ```v import models.Foo struct Bar { id int @[primary; sql: serial] } sql db { create table models.Foo drop table Bar }! ``` -------------------------------- ### Start ORM Transaction Source: https://modules.vlang.io/db.sqlite.html Starts a database transaction for ORM helper functions. Requires a mutable DB connection. ```V fn (mut db DB) orm_begin() ! ``` -------------------------------- ### Start Static File Server with net.http.file Source: https://modules.vlang.io/net.http.file.html The `serve` function initiates a static file web server. It can be configured with parameters like the folder to serve, the address and port to listen on, and an index file. By default, it serves files from the current directory on port 4001. ```v fn serve(params StaticServeParams) // Example: Serve files from current directory on default port 4001 v -e 'import net.http.file; file.serve()' // Example: Serve files from /tmp folder on default port 4001 v -e 'import net.http.file; file.serve(folder: "/tmp")' // Example: Serve files from ~/Projects folder on port 5002 v -e 'import net.http.file; file.serve(folder: "~/Projects", on: ":5002")' ``` -------------------------------- ### Define a Build Script in V Source: https://modules.vlang.io/build.html Demonstrates how to initialize a BuildContext and define various tasks including documentation generation, running, and production builds using the build module. ```v #!/usr/bin/env -S v run import build import os { system } const app_name = 'vlang' const program_args = 'World' mut context := build.context( default: 'release' ) context.task(name: 'doc', run: |self| system('v doc .')) context.task(name: 'run', run: |self| system('v run . ${program_args}')) context.task(name: 'build', run: |self| system('v .')) context.task(name: 'build.prod', run: |self| system('v -prod .')) context.task( name: 'release' depends: ['doc'] run: fn (self build.Task) ! { system('v -prod -o build/${app_name} .') } ) context.run() ``` -------------------------------- ### V pkgconfig Output Example Source: https://modules.vlang.io/v.pkgconfig.html Illustrates the typical output format for library flags when using the v.pkgconfig module to query package information. This output is commonly used for linking during the compilation process. ```text ['-L/usr/lib/x86_64-linux-gnu', '-lexpat'] ``` -------------------------------- ### Vlang Comptime: Initialize Comptime Instance Source: https://modules.vlang.io/v.comptime.html Provides functions to create new Comptime instances, with options for providing preferences or a pre-defined AST table and preferences. These are essential for setting up the comptime execution environment. ```v fn new_comptime(pref_ &pref.Preferences) &Comptime fn new_comptime_with_table(table &ast.Table, pref_ &pref.Preferences) &Comptime ``` -------------------------------- ### Find First Match (Vlang) Source: https://modules.vlang.io/regex.html Finds the first occurrence of the pattern within the input string. Returns the start and end indices of the match. If no match is found, the start index is returned as -1. ```v pub fn (mut re RE) find(in_txt string) (int, int) ``` -------------------------------- ### Manage help and finalization in V Source: https://modules.vlang.io/flag.html Methods to set the program description, generate usage screens, and finalize the parsing process to retrieve remaining arguments. ```v fn (mut fs FlagParser) arguments_description(description string) fn (fs &FlagParser) usage() string fn (mut fs FlagParser) finalize() ![]string ``` -------------------------------- ### Get Type Name (Vlang) Source: https://modules.vlang.io/v.ast.html Retrieves the name of a given type. This function provides a straightforward way to get the string representation of a type. ```Vlang fn (t &Table) get_type_name(typ Type) string ``` -------------------------------- ### Install PostgreSQL on macOS (MacPorts) Source: https://modules.vlang.io/db.pg.html Installs the PostgreSQL client library using MacPorts on macOS. This command requires specifying the PostgreSQL version and its configuration path. ```shell gem install pg -- --with-pg-config=/opt/local/lib/postgresql[version number]/bin/pg_config ``` -------------------------------- ### Start SSE Connection Source: https://modules.vlang.io/vweb.sse.html The `start` method is called on an `SSEConnection` instance to initiate the Server-Side Event response. It is a method that modifies the `SSEConnection` state and can return an error. ```vlang fn (mut sse SSEConnection) start() ! ``` -------------------------------- ### Benchmark Initialization Source: https://modules.vlang.io/benchmark.html Methods to initialize a new benchmark instance for tracking performance metrics. ```APIDOC ## Function: new_benchmark ### Description Returns a `Benchmark` instance on the stack. ### Signature `fn new_benchmark() Benchmark` --- ## Function: new_benchmark_pointer ### Description Returns a new `Benchmark` instance allocated on the heap. Useful for long-lived benchmark instances. ### Signature `fn new_benchmark_pointer() &Benchmark` ``` -------------------------------- ### Match String (Vlang) Source: https://modules.vlang.io/regex.html Attempts to match a given input string against a compiled regular expression. Returns the start and end indices of the first match found. If no match is found, the start index is returned as -1. ```v pub fn (mut re RE) match_string(in_txt string) (int, int) ``` -------------------------------- ### Configure Static File Serving Source: https://modules.vlang.io/vweb.html Demonstrates how to serve static assets like CSS and images by marking directories or specific files for the vweb server. ```v fn main() { mut app := &App{} app.serve_static('/favicon.ico', 'favicon.ico') os.chdir(os.dir(os.executable()))? app.handle_static('assets', true) vweb.run(app, port) } ```