Package walletdb provides a namespaced database interface for btcwallet. A wallet essentially consists of a multitude of stored data such as private and public keys, key derivation bits, pay-to-script-hash scripts, and various metadata. One of the issues with many wallets is they are tightly integrated. Designing a wallet with loosely coupled components that provide specific functionality is ideal, however it presents a challenge in regards to data storage since each component needs to store its own data without knowing the internals of other components or breaking atomicity. This package solves this issue by providing a pluggable driver, namespaced database interface that is intended to be used by the main wallet daemon. This allows the potential for any backend database type with a suitable driver. Each component, which will typically be a package, can then implement various functionality such as address management, voting pools, and colored coin metadata in their own namespace without having to worry about conflicts with other packages even though they are sharing the same database that is managed by the wallet. A quick overview of the features walletdb provides are as follows: The main entry point is the DB interface. It exposes functionality for creating, retrieving, and removing namespaces. It is obtained via the Create and Open functions which take a database type string that identifies the specific database driver (backend) to use as well as arguments specific to the specified driver. The Namespace interface is an abstraction that provides facilities for obtaining transactions (the Tx interface) that are the basis of all database reads and writes. Unlike some database interfaces that support reading and writing without transactions, this interface requires transactions even when only reading or writing a single key. The Begin function provides an unmanaged transaction while the View and Update functions provide a managed transaction. These are described in more detail below. The Tx interface provides facilities for rolling back or commiting changes that took place while the transaction was active. It also provides the root bucket under which all keys, values, and nested buckets are stored. A transaction can either be read-only or read-write and managed or unmanaged. A managed transaction is one where the caller provides a function to execute within the context of the transaction and the commit or rollback is handled automatically depending on whether or not the provided function returns an error. Attempting to manually call Rollback or Commit on the managed transaction will result in a panic. An unmanaged transaction, on the other hand, requires the caller to manually call Commit or Rollback when they are finished with it. Leaving transactions open for long periods of time can have several adverse effects, so it is recommended that managed transactions are used instead. The Bucket interface provides the ability to manipulate key/value pairs and nested buckets as well as iterate through them. The Get, Put, and Delete functions work with key/value pairs, while the Bucket, CreateBucket, CreateBucketIfNotExists, and DeleteBucket functions work with buckets. The ForEach function allows the caller to provide a function to be called with each key/value pair and nested bucket in the current bucket. As discussed above, all of the functions which are used to manipulate key/value pairs and nested buckets exist on the Bucket interface. The root bucket is the upper-most bucket in a namespace under which data is stored and is created at the same time as the namespace. Use the RootBucket function on the Tx interface to retrieve it. The CreateBucket and CreateBucketIfNotExists functions on the Bucket interface provide the ability to create an arbitrary number of nested buckets. It is a good idea to avoid a lot of buckets with little data in them as it could lead to poor page utilization depending on the specific driver in use. This example demonstrates creating a new database, getting a namespace from it, and using a managed read-write transaction against the namespace to store and retrieve data.
Package walletdb provides a namespaced database interface for lbcwallet. A wallet essentially consists of a multitude of stored data such as private and public keys, key derivation bits, pay-to-script-hash scripts, and various metadata. One of the issues with many wallets is they are tightly integrated. Designing a wallet with loosely coupled components that provide specific functionality is ideal, however it presents a challenge in regards to data storage since each component needs to store its own data without knowing the internals of other components or breaking atomicity. This package solves this issue by providing a pluggable driver, namespaced database interface that is intended to be used by the main wallet daemon. This allows the potential for any backend database type with a suitable driver. Each component, which will typically be a package, can then implement various functionality such as address management, voting pools, and colored coin metadata in their own namespace without having to worry about conflicts with other packages even though they are sharing the same database that is managed by the wallet. A quick overview of the features walletdb provides are as follows: The main entry point is the DB interface. It exposes functionality for creating, retrieving, and removing namespaces. It is obtained via the Create and Open functions which take a database type string that identifies the specific database driver (backend) to use as well as arguments specific to the specified driver. The Namespace interface is an abstraction that provides facilities for obtaining transactions (the Tx interface) that are the basis of all database reads and writes. Unlike some database interfaces that support reading and writing without transactions, this interface requires transactions even when only reading or writing a single key. The Begin function provides an unmanaged transaction while the View and Update functions provide a managed transaction. These are described in more detail below. The Tx interface provides facilities for rolling back or commiting changes that took place while the transaction was active. It also provides the root bucket under which all keys, values, and nested buckets are stored. A transaction can either be read-only or read-write and managed or unmanaged. A managed transaction is one where the caller provides a function to execute within the context of the transaction and the commit or rollback is handled automatically depending on whether or not the provided function returns an error. Attempting to manually call Rollback or Commit on the managed transaction will result in a panic. An unmanaged transaction, on the other hand, requires the caller to manually call Commit or Rollback when they are finished with it. Leaving transactions open for long periods of time can have several adverse effects, so it is recommended that managed transactions are used instead. The Bucket interface provides the ability to manipulate key/value pairs and nested buckets as well as iterate through them. The Get, Put, and Delete functions work with key/value pairs, while the Bucket, CreateBucket, CreateBucketIfNotExists, and DeleteBucket functions work with buckets. The ForEach function allows the caller to provide a function to be called with each key/value pair and nested bucket in the current bucket. As discussed above, all of the functions which are used to manipulate key/value pairs and nested buckets exist on the Bucket interface. The root bucket is the upper-most bucket in a namespace under which data is stored and is created at the same time as the namespace. Use the RootBucket function on the Tx interface to retrieve it. The CreateBucket and CreateBucketIfNotExists functions on the Bucket interface provide the ability to create an arbitrary number of nested buckets. It is a good idea to avoid a lot of buckets with little data in them as it could lead to poor page utilization depending on the specific driver in use. This example demonstrates creating a new database, getting a namespace from it, and using a managed read-write transaction against the namespace to store and retrieve data.
Package version provides functionality for parsing and comparing version strings. It supports semantic versioning and includes methods for version comparison, manipulation, and formatting.
Various operations for string slices for Go Package strarr is a collection of functions to manipulate string arrays/slices. Some functions were adapted from the strings package to work with string slices, other were ported from PHP 'array_*' function equivalents. This example shows basic usage of various functions by manipulating the array 'arr'.
Copyright Philippe Thomassigny 2004-2023. Use of this source code is governed by a MIT licence. license that can be found in the LICENSE file. XDominion for GO v0 ============================= xdominion is a Go library for creating a database layer that abstracts the underlying database implementation and allows developers to interact with the database using objects rather than SQL statements. It supports multiple database backends, including PostgreSQL, MySQL, SQLite, and Microsoft SQL Server, among others. If you need a not yet supported database, please open a ticket on github.com. The library provides a set of high-level APIs for interacting with databases. It allows developers to map database tables to Go structs, allowing them to interact with the database using objects. The library also provides an intuitive and chainable API for querying the database, similar to the structure of SQL statements, but without requiring developers to write SQL code directly. xdominion uses a set of interfaces to abstract the database operations, making it easy to use different database backends with the same code. The library supports transactions, allowing developers to perform multiple database operations in a single transaction. The xdominion library uses reflection to map Go structs to database tables, and also allows developers to specify custom column names and relationships between tables. Overall, xdominion provides a simple and intuitive way to interact with databases using objects and abstracts the underlying database implementation. It is a well-designed library with a clear API and support for multiple database backends. 1. Overview ------------------------ XDominion is a database abstraction layer, to build and use objects of data instead of building SQL queries. The code is portable between databases with changing the implementation, since you don't use direct incompatible SQL sentences. The library is build over 3 main objects: - XBase: database connector and cursors to build queries and manipulation language - - Other included objects: XCursor - XTable: the table definition, data access function/structures and definition manipulation language - - Other included objects: XField*, XConstraints, XContraint, XOrderby, XConditions, XCondition - XRecord: the results and data to interchange with the database - - Other included objects: XRecords 2. Some example code to start working rapidly: ------------------------ Creates the connector to the database and connect: ``` ``` Executes a direct query: ``` ``` Creates a table definition: ``` t := xdominion.NewXTable("test", "t_") t.AddField(xdominion.XFieldText{Name: "f3"}) t.AddField(xdominion.XFieldDate{Name: "f4"}) t.AddField(xdominion.XFieldDateTime{Name: "f5"}) t.AddField(xdominion.XFieldFloat{Name: "f6"}) t.SetBase(base) ``` Synchronize the table with DB (create it if it does not exist) ``` ``` Some Insert: ``` ``` With an error (f2 is mandatory based on table definition): ``` ``` General query (select ALL): ``` ``` Query by Key: ``` ``` Query by Where: ``` ``` Transactions: ``` tx, err := base.BeginTransaction() res1, err := tb.Insert(XRecord{"f1": 5, "f2": "Data line 1"}, tx) res2, err := tb.Update(2, XRecord{"f1": 5, "f2": "Data line 1"}, tx) res3, err := tb.Delete(3, tx) // Note that the transaction is always passed as a parameter to the insert, update, delete operations tx.Commit() ``` 3. Reference ------------------------ XBase ----- The xbase package in xdominion provides a set of functions for working with relational databases in Go. Here is a reference manual for the package: Constants VERSION: A constant string that represents the version of XDominion. DB_Postgres: A constant string that represents the PostgreSQL database. DB_MySQL: A constant string that represents the MySQL database. DB_Localhost: A constant string that represents the local host. Variables DEBUG: A boolean variable used to enable/disable debug mode. Structs XBase DB: A pointer to an instance of sql.DB, representing the database connection. Logged: A boolean indicating whether the database connection has been established. DBType: A string representing the type of database being used. Username: A string representing the username for the database connection. Password: A string representing the password for the database connection. Database: A string representing the name of the database being connected to. Host: A string representing the host for the database connection. SSL: A boolean indicating whether to use SSL for the database connection. Logger: A pointer to a logger for debugging purposes. XTransaction DB: A pointer to an instance of XBase, representing the database connection. TX: A pointer to an instance of sql.Tx, representing a transaction. Functions Logon() The Logon() function establishes a connection to the database. go Copy code func (b *XBase) Logon() Logoff() The Logoff() function closes the database connection. go Copy code func (b *XBase) Logoff() Exec() The Exec() function executes a SQL query on the database and returns a cursor. go Copy code func (b *XBase) Exec(query string, args ...interface{}) (*sql.Rows, error) Cursor() The Cursor() function returns a new instance of Cursor, which provides methods for working with database records. go Copy code package main import ( ) In this example, we first create a new instance of the xdominion.XBase struct with the connection details to the database we want to connect to. We then call the Logon() method of the XBase struct to establish a connection to the database. Next, we define an SQL query to insert a new user into the users table, and then call the Exec() method of the XBase struct with the query and the values we want to insert. The Exec() function returns a cursor, which we don't need in this example, so we ignore it using the blank identifier (_). If there's an error executing the query, we print an error message to the console. Finally, we close the database connection by calling the Logoff() method of the XBase struct. Note that this is just a simple example, and you should always make sure to properly handle errors and sanitize user input when working with databases. package main import ( ) In this example, we first create a new instance of the xdominion.XBase struct with the connection details to the database we want to connect to. We then call the Logon() method of the XBase struct to establish a connection to the database. Next, we define an SQL query to select a user from the users table with the id equal to 1. We then call the Exec() method of the XBase struct with the query and the value we want to use for the id parameter. The Exec() function returns a cursor that we can iterate over to get the results of the query. We use a for loop to iterate over the rows returned by the Exec() function. Inside the loop, we use the Scan() method of the rows object to read the values of the name and email columns into variables. We then print the values of these variables to the console. If there's an error executing the query or reading a row, we print an error message to the console. Finally, we close the rows object and the database connection by calling the Close() and Logoff() methods of the XBase struct, respectively. Note that this is just a simple example, and you should always make sure to properly handle errors and sanitize user input when working with databases. go Copy code func (b *XBase) Cursor() *Cursor BeginTransaction() The BeginTransaction() function starts a new transaction on the database. go Copy code func (b *XBase) BeginTransaction() (*XTransaction, error) Commit() The Commit() function commits a transaction to the database. go Copy code func (t *XTransaction) Commit() error Rollback() The Rollback() function rolls back a transaction on the database. go Copy code func (t *XTransaction) Rollback() error Notes The Logon() function must be called before using any other functions in the xbase package. The Logoff() function should be called when finished using the database connection. The Exec() function should be used for executing arbitrary SQL queries. The Cursor() function should be used for performing CRUD operations on database records. The BeginTransaction(), Commit(), and Rollback() functions should be used for transactions. Note that this is just a brief overview of the xbase package. For more information and examples, please refer to the documentation in the xdominion GitHub repository: https://github.com/webability-go/xdominion. Create a new instance of the xdominion.XBase struct, which represents a database connection. The XBase struct provides methods for interacting with the database, such as querying, inserting, updating, and deleting records. In this example, &xdominion.XBase{} is the instance of the XBase struct, and the properties of the struct are set to the database connection details. The DBType property specifies the type of database being used, Username and Password specify the username and password for the database connection, Database specifies the name of the database being connected to, Host specifies the host for the database connection, and SSL specifies whether to use SSL for the database connection. Use the Logon() method of the XBase struct to connect to the database. base.Logon() The Logon() method establishes a connection to the database using the details provided in the XBase struct. Note that this is just a simple example, and the XBase library provides many more features for working with databases using objects. You can find more information and examples in the xdominion GitHub repository: https://github.com/webability-go/xdominion. XTable definition ----------------- XTable operations ----------------- XRecord ------- XRecords -------- Conditions ---------- Orderby ------- Fields ------ Limits ------ Groupby ------- Having ------ */
Package stringtool is a colllection of functions to manipulate string
Package goutils provides utility functions to manipulate strings in various ways. The code snippets below show examples of how to use goutils. Some functions return errors while others do not, so usage would vary as a result. Example:
Package goutils provides utility functions to manipulate strings in various ways. The code snippets below show examples of how to use goutils. Some functions return errors while others do not, so usage would vary as a result. Example:
Copying All nodes (since they implement the Node interface) also implement the NodeCopier interface which provides the ShallowCopy() function. A shallow copy returns a new node with all the same properties, but no children. On the other hand there is a DeepCopy function which returns a new node with all recursive children also copied. This ensures that the new returned node can be manipulated without affecting the original node or any of its children. Dates in GEDCOM files can be very complex as they can cater for many scenarios: 1. Incomplete, like "Dec 1943" 2. Anchored, like "Aft. 3 Sep 2003" or "Before 1923" 3. Ranges, like "Bet. 4 Apr 1823 and 8 Apr 1823" 4. Phrases, like "(Foo Bar)" This package provides a very rich API for dealing with all kind of dates in a meaningful and sensible way. Some notable features include: 1. All dates, even though that specify an specific day have a minimum and maximum value that are their true bounds. This is especially important for larger date ranges like the whole month of "Jun 1945". 2. Upper and lower bounds of dates can be converted to the native Go time.Time object. 3. There is a Years function that provides a convenient way to normalise a date range into a number for easier distance and comparison measurements. 4. Algorithms for calculating the similarity of dates on a configurable parabola. Decoding a GEDCOM stream: If you are reading from a file you can use NewDocumentFromGEDCOMFile: Package gedcom contains functionality for encoding, decoding, traversing, manipulating and comparing of GEDCOM data. You can download the latest binaries for macOS, Windows and Linux on the Releases page: https://github.com/elliotchance/gedcom/releases This will not require you to install Go or any other dependencies. If you wish to build it from source you must install the dependencies with: On top of the raw document is a powerful API that takes care of the complex traversing of the Document. Here is a simple example: Some of the nodes in a GEDCOM file have been replaced with more function rich types, such as names, dates, families and more. Encoding a Document If you need the GEDCOM data as a string you can simply using fmt.Stringer: The Filter function recursively removes or manipulates nodes with a FilterFunction: Some examples of Filter functions include BlacklistTagFilter, OfficialTagFilter, SimpleNameFilter and WhitelistTagFilter. There are several functions available that handle different kinds of merging: - MergeNodes(left, right Node) Node: returns a new node that merges children from both nodes. - MergeNodeSlices(left, right Nodes, mergeFn MergeFunction) Nodes: merges two slices based on the mergeFn. This allows more advanced merging when dealing with slices of nodes. - MergeDocuments(left, right *Document, mergeFn MergeFunction) *Document: creates a new document with their respective nodes merged. You can use IndividualBySurroundingSimilarityMergeFunction with this to merge individuals, rather than just appending them all. The MergeFunction is a type that can be received in some of the merging functions. The closure determines if two nodes should be merged and what the result would be. Alternatively it can also describe when two nodes should not be merged. You may certainly create your own MergeFunction, but there are some that are already included: - IndividualBySurroundingSimilarityMergeFunction creates a MergeFunction that will merge individuals if their surrounding similarity is at least minimumSimilarity. - EqualityMergeFunction is a MergeFunction that will return a merged node if the node are considered equal (with Equals). Node.Equals performs a shallow comparison between two nodes. The implementation is different depending on the types of nodes being compared. You should see the specific documentation for the Node. Equality is not to be confused with the Is function seen on some of the nodes, such as Date.Is. The Is function is used to compare exact raw values in nodes. DeepEqual tests if left and right are recursively equal. CompareNodes recursively compares two nodes. For example: Produces a *NodeDiff than can be rendered with the String method:
Package dig provides a map[string]any Mapping type that has ruby-like "dig" functionality. It can be used for example to access and manipulate arbitrary nested YAML/JSON structures.
Package goutils provides utility functions to manipulate strings in various ways. The code snippets below show examples of how to use goutils. Some functions return errors while others do not, so usage would vary as a result. Example:
Package goutils provides utility functions to manipulate strings in various ways. The code snippets below show examples of how to use goutils. Some functions return errors while others do not, so usage would vary as a result. Example:
Package goutils provides utility functions to manipulate strings in various ways. The code snippets below show examples of how to use goutils. Some functions return errors while others do not, so usage would vary as a result. Example:
Package goutils provides utility functions to manipulate strings in various ways. The code snippets below show examples of how to use goutils. Some functions return errors while others do not, so usage would vary as a result. Example:
Package goutils provides utility functions to manipulate strings in various ways. The code snippets below show examples of how to use goutils. Some functions return errors while others do not, so usage would vary as a result. Example:
Package goutils provides utility functions to manipulate strings in various ways. The code snippets below show examples of how to use goutils. Some functions return errors while others do not, so usage would vary as a result. Example:
Package goutils provides utility functions to manipulate strings in various ways. The code snippets below show examples of how to use goutils. Some functions return errors while others do not, so usage would vary as a result. Example:
Package goutils provides utility functions to manipulate strings in various ways. The code snippets below show examples of how to use goutils. Some functions return errors while others do not, so usage would vary as a result. Example:
Package slices ... Package slices is a collection of functions to operate with string slices. Some functions were adapted from the strings package to work with slices, other were ported from PHP 'array_*' function equivalents. This example shows basic usage of various functions by manipulating the slice 'slc'.
Package database provides a block and metadata storage database. This package provides a database layer to store and retrieve block data and arbitrary metadata in a simple and efficient manner. The default backend, ffldb, has a strong focus on speed, efficiency, and robustness. It makes use leveldb for the metadata, flat files for block storage, and strict checksums in key areas to ensure data integrity. A quick overview of the features database provides are as follows: The main entry point is the DB interface. It exposes functionality for transactional-based access and storage of metadata and block data. It is obtained via the Create and Open functions which take a database type string that identifies the specific database driver (backend) to use as well as arguments specific to the specified driver. The Namespace interface is an abstraction that provides facilities for obtaining transactions (the Tx interface) that are the basis of all database reads and writes. Unlike some database interfaces that support reading and writing without transactions, this interface requires transactions even when only reading or writing a single key. The Begin function provides an unmanaged transaction while the View and Update functions provide a managed transaction. These are described in more detail below. The Tx interface provides facilities for rolling back or committing changes that took place while the transaction was active. It also provides the root metadata bucket under which all keys, values, and nested buckets are stored. A transaction can either be read-only or read-write and managed or unmanaged. A managed transaction is one where the caller provides a function to execute within the context of the transaction and the commit or rollback is handled automatically depending on whether or not the provided function returns an error. Attempting to manually call Rollback or Commit on the managed transaction will result in a panic. An unmanaged transaction, on the other hand, requires the caller to manually call Commit or Rollback when they are finished with it. Leaving transactions open for long periods of time can have several adverse effects, so it is recommended that managed transactions are used instead. The Bucket interface provides the ability to manipulate key/value pairs and nested buckets as well as iterate through them. The Get, Put, and Delete functions work with key/value pairs, while the Bucket, CreateBucket, CreateBucketIfNotExists, and DeleteBucket functions work with buckets. The ForEach function allows the caller to provide a function to be called with each key/value pair and nested bucket in the current bucket. As discussed above, all of the functions which are used to manipulate key/value pairs and nested buckets exist on the Bucket interface. The root metadata bucket is the upper-most bucket in which data is stored and is created at the same time as the database. Use the Metadata function on the Tx interface to retrieve it. The CreateBucket and CreateBucketIfNotExists functions on the Bucket interface provide the ability to create an arbitrary number of nested buckets. It is a good idea to avoid a lot of buckets with little data in them as it could lead to poor page utilization depending on the specific driver in use. This example demonstrates creating a new database and using a managed read-write transaction to store and retrieve metadata. This example demonstrates creating a new database, using a managed read-write transaction to store a block, and using a managed read-only transaction to fetch the block.
Package walletdb provides a namespaced database interface for vclwallet. A wallet essentially consists of a multitude of stored data such as private and public keys, key derivation bits, pay-to-script-hash scripts, and various metadata. One of the issues with many wallets is they are tightly integrated. Designing a wallet with loosely coupled components that provide specific functionality is ideal, however it presents a challenge in regards to data storage since each component needs to store its own data without knowing the internals of other components or breaking atomicity. This package solves this issue by providing a pluggable driver, namespaced database interface that is intended to be used by the main wallet daemon. This allows the potential for any backend database type with a suitable driver. Each component, which will typically be a package, can then implement various functionality such as address management, voting pools, and colored coin metadata in their own namespace without having to worry about conflicts with other packages even though they are sharing the same database that is managed by the wallet. A quick overview of the features walletdb provides are as follows: The main entry point is the DB interface. It exposes functionality for creating, retrieving, and removing namespaces. It is obtained via the Create and Open functions which take a database type string that identifies the specific database driver (backend) to use as well as arguments specific to the specified driver. The Namespace interface is an abstraction that provides facilities for obtaining transactions (the Tx interface) that are the basis of all database reads and writes. Unlike some database interfaces that support reading and writing without transactions, this interface requires transactions even when only reading or writing a single key. The Begin function provides an unmanaged transaction while the View and Update functions provide a managed transaction. These are described in more detail below. The Tx interface provides facilities for rolling back or commiting changes that took place while the transaction was active. It also provides the root bucket under which all keys, values, and nested buckets are stored. A transaction can either be read-only or read-write and managed or unmanaged. A managed transaction is one where the caller provides a function to execute within the context of the transaction and the commit or rollback is handled automatically depending on whether or not the provided function returns an error. Attempting to manually call Rollback or Commit on the managed transaction will result in a panic. An unmanaged transaction, on the other hand, requires the caller to manually call Commit or Rollback when they are finished with it. Leaving transactions open for long periods of time can have several adverse effects, so it is recommended that managed transactions are used instead. The Bucket interface provides the ability to manipulate key/value pairs and nested buckets as well as iterate through them. The Get, Put, and Delete functions work with key/value pairs, while the Bucket, CreateBucket, CreateBucketIfNotExists, and DeleteBucket functions work with buckets. The ForEach function allows the caller to provide a function to be called with each key/value pair and nested bucket in the current bucket. As discussed above, all of the functions which are used to manipulate key/value pairs and nested buckets exist on the Bucket interface. The root bucket is the upper-most bucket in a namespace under which data is stored and is created at the same time as the namespace. Use the RootBucket function on the Tx interface to retrieve it. The CreateBucket and CreateBucketIfNotExists functions on the Bucket interface provide the ability to create an arbitrary number of nested buckets. It is a good idea to avoid a lot of buckets with little data in them as it could lead to poor page utilization depending on the specific driver in use. This example demonstrates creating a new database, getting a namespace from it, and using a managed read-write transaction against the namespace to store and retrieve data.
Package goav contains the codecs (decoders and encoders) provided by the libavcodec library Provides some generic global options, which can be set on all the encoders and decoders. Package goav deals with the input and output devices provided by the libavdevice library The libavdevice library provides the same interface as libavformat. Namely, an input device is considered like a demuxer, and an output device like a muxer, and the interface and generic device options are the same provided by libavformat Package goav contains methods that deal with ffmpeg filters filters in the same linear chain are separated by commas, and distinct linear chains of filters are separated by semicolons. FFmpeg is enabled through the "C" libavfilter library Package goav provides some generic global options, which can be set on all the muxers and demuxers. In addition each muxer or demuxer may support so-called private options, which are specific for that component. Supported formats (muxers and demuxers) provided by the libavformat library Package goav ... Use of this source code is governed by a MIT license that can be found in the LICENSE file. Giorgis (habtom@giorgis.io) Package goav is a utility library to aid portable multimedia programming. It contains safe portable string functions, random number generators, data structures, additional mathematics functions, cryptography and multimedia related functionality. Some generic features and utilities provided by the libavutil library Package goav provides some generic global options, which can be set on all the muxers and demuxers. In addition each muxer or demuxer may support so-called private options, which are specific for that component. Supported formats (muxers and demuxers) provided by the libavformat library Package goav is a utility library to aid portable multimedia programming. It contains safe portable string functions, random number generators, data structures, additional mathematics functions, cryptography and multimedia related functionality. Some generic features and utilities provided by the libavutil library Package goav is a utility library to aid portable multimedia programming. It contains safe portable string functions, random number generators, data structures, additional mathematics functions, cryptography and multimedia related functionality. Some generic features and utilities provided by the libavutil library Package goav contains golang binding for FFmpeg. A comprehensive binding to the ffmpeg video/audio manipulation library: https://www.ffmpeg.org/ Contains: Package goav contains the codecs (decoders and encoders) provided by the libavcodec library Provides some generic global options, which can be set on all the encoders and decoders. Package goav contains the codecs (decoders and encoders) provided by the libavcodec library Provides some generic global options, which can be set on all the encoders and decoders. Package goav provides a high-level interface to the libswresample library audio resampling utilities The process of changing the sampling rate of a discrete signal to obtain a new discrete representation of the underlying continuous signal. Package goav performs highly optimized image scaling and colorspace and pixel format conversion operations. Rescaling: is the process of changing the video size. Several rescaling options and algorithms are available. Pixel format conversion: is the process of converting the image format and colorspace of the image.
Package luar provides a convenient interface between Lua and Go. It uses Alessandro Arzilli's golua (https://github.com/aarzilli/golua). Most Go values can be passed to Lua: basic types, strings, complex numbers, user-defined types, pointers, composite types, functions, channels, etc. Conversely, most Lua values can be converted to Go values. Composite types are processed recursively. Methods can be called on user-defined types. These methods will be callable using _dot-notation_ rather than colon notation. Arrays, slices, maps and structs can be copied as tables, or alternatively passed over as Lua proxy objects which can be naturally indexed. In the case of structs and string maps, fields have priority over methods. Use 'luar.method(<value>, <method>)(<params>...)' to call shadowed methods. Unexported struct fields are ignored. The "lua" tag is used to match fields in struct conversion. You may pass a Lua table to an imported Go function; if the table is 'array-like' then it is converted to a Go slice; if it is 'map-like' then it is converted to a Go map. Pointer values encode as the value pointed to when unproxified. Usual operators (arithmetic, string concatenation, pairs/ipairs, etc.) work on proxies too. The type of the result depends on the type of the operands. The rules are as follows: - If the operands are of the same type, use this type. - If one type is a Lua number, use the other, user-defined type. - If the types are different and not Lua numbers, convert to a complex proxy, a Lua number, or a Lua string according to the result kind. Channel proxies can be manipulated with the following methods: - close(): Close the channel. - recv() value: Fetch and return a value from the channel. - send(x value): Send a value in the channel. Complex proxies can be manipulated with the following attributes: - real: The real part. - imag: The imaginary part. Slice proxies can be manipulated with the following methods/attributes: - append(x ...value) sliceProxy: Append the elements and return the new slice. The elements must be convertible to the slice element type. - cap: The capacity of the slice. - slice(i, j integer) sliceProxy: Return the sub-slice that ranges from 'i' to 'j' excluded, starting from 1. String proxies can be browsed rune by rune with the pairs/ipairs functions. These runes are encoded as strings in Lua. Indexing a string proxy (starting from 1) will return the corresponding byte as a Lua string. String proxies can be manipulated with the following method: - slice(i, j integer) sliceProxy: Return the sub-string that ranges from 'i' to 'j' excluded, starting from 1. Pointers to structs and structs within pointers are automatically dereferenced. Slices must be looped over with 'ipairs'.
Package morestrings implements additional functions to manipulate UTF-8 encoded strings, beyond what is provided in the standard "strings" package.
Sprig: Template functions for Go. This package contains a number of utility functions for working with data inside of Go `html/template` and `text/template` files. To add these functions, use the `template.Funcs()` method: Note that you should add the function map before you parse any template files. Date Functions String Functions String Slice Functions: Integer Slice Functions: Conversions: Defaults: OS: File Paths: Encoding: Reflection: typeOf: Takes an interface and returns a string representation of the type. For pointers, this will return a type prefixed with an asterisk(`*`). So a pointer to type `Foo` will be `*Foo`. typeIs: Compares an interface with a string name, and returns true if they match. Note that a pointer will not match a reference. For example `*Foo` will not match `Foo`. typeIsLike: Compares an interface with a string name and returns true if the interface is that `name` or that `*name`. In other words, if the given value matches the given type or is a pointer to the given type, this returns true. kindOf: Takes an interface and returns a string representation of its kind. kindIs: Returns true if the given string matches the kind of the given interface. Note: None of these can test whether or not something implements a given interface, since doing so would require compiling the interface in ahead of time. Data Structures: Lists Functions: These are used to manipulate lists: '{{ list 1 2 3 | reverse | first }}' Dict Functions: These are used to manipulate dicts. Math Functions: Integer functions will convert integers of any width to `int64`. If a string is passed in, functions will attempt to convert with `strconv.ParseInt(s, 1064)`. If this fails, the value will be treated as 0. Crypto Functions: SemVer Functions: These functions provide version parsing and comparisons for SemVer 2 version strings.
objx - Go package for dealing with maps, slices, JSON and other data. Objx provides the `objx.Map` type, which is a `map[string]interface{}` that exposes a powerful `Get` method (among others) that allows you to easily and quickly get access to data within the map, without having to worry too much about type assertions, missing data, default values etc. Objx uses a preditable pattern to make access data from within `map[string]interface{}'s easy. Call one of the `objx.` functions to create your `objx.Map` to get going: NOTE: Any methods or functions with the `Must` prefix will panic if something goes wrong, the rest will be optimistic and try to figure things out without panicking. Use `Get` to access the value you're interested in. You can use dot and array notation too: Once you have sought the `Value` you're interested in, you can use the `Is*` methods to determine its type. Or you can just assume the type, and use one of the strong type methods to extract the real value: If there's no value there (or if it's the wrong type) then a default value will be returned, or you can be explicit about the default value. If you're dealing with a slice of data as a value, Objx provides many useful methods for iterating, manipulating and selecting that data. You can find out more by exploring the index below. A simple example of how to use Objx: Since `objx.Map` is a `map[string]interface{}` you can treat it as such. For example, to `range` the data, do what you would expect:
Package envconf parses environment variables into structs. It supports multiple types, however the core type is always a string. Translators are available which manipulate the string value before setting, e.g. `!base64:SGVsbG8gV29ybGQ=` will cast to a string as "Hello World". There is no specific handling for bytes when using this method, it is handled as a string entirely, if you are expecting actual bytes use a type like Hex or Base64 which will directly translate the env var string to bytes Standard conversion from string to int, bool etc work, as well as custom types which satisfy `SetterFromEnv` (on a pointer, like JSON) Combining translators and custom types is perfectly fine. The string translations will happen first, then the output will be passed into FromEnvString
The motivation behind this package is that the StructTag implementation shipped with Go's standard library is very limited in detecting a malformed StructTag and each time StructTag.Get(key) gets called, it results in the StructTag being parsed again. Another problem is that the StructTag can not be easily manipulated because it is basically a string. This package provides a way to parse the StructTag into a Tag map, which allows for fast lookups and easy manipulation of key value pairs within the Tag.
Some of the older elements of GMA (which used to be entirely written in the Tcl language, after it was ported from the even older C++ code) use Tcl list objects as their data representation. Notably the biggest example is the mapper(6) tool (which is still written in Tcl itself), whose map file format and TCP/IP communications protocl include mar‐ shalled data structures represented as Tcl lists. While this is obviously convenient for Tcl programs in that they can take such strings and natively use them as lists of values, it is also useful generally in that it is a simple string representation of a sim‐ ple data structure. The actual definition of this string format is included below. The tcllist Go package provides an easy interface to manipulate Tcl lists as Go types. As of yet, this only converts to and from slices of strings. We will extend this to manage mixed-types and nested lists if necessary, but that might not be needed for this application. We'll see. In a nutshell, a Tcl list (as a string representation) is a space- delimited list of values. Any value which includes spaces is enclosed in curly braces. An empty string (empty list) as an element in a list is represented as “{}”. (E.g., “1 {} 2” is a list of three elements, the middle of which is an empty string.) An entirely empty Tcl list is represented as an empty string “”. A list value must have balanced braces. A balanced pair of braces that happen to be inside a larger string value may be left as-is, since a string that happens to contain spaces or braces is only distinguished from a deeply-nested list value when you attempt to interpret it as one or another in the code. Thus, the list has three elements: “a”, “b”, and “this {is a} string”. Otherwise, a lone brace that's part of a string value should be escaped with a back‐ slash: Literal backslashes may be escaped with a backslash as well. While extra spaces are ignored when parsing lists into elements, a properly formed string representation of a list will have the miminum number of spaces and braces needed to describe the list structure.
Package linq provides methods for querying and manipulating slices, arrays, maps, strings, channels and collections. Authors: Alexander Kalankhodzhaev (kalan), Ahmet Alp Balkan, Cleiton Marques Souza.
Package sqlr is designed to reduce the effort required to work with SQL databases. It is intended for programmers who are comfortable with writing SQL, but would like assistance with the sometimes tedious process of preparing SQL queries for tables that have a large number of columns, or have a variable number of input parameters. This GoDoc summary provides an overview of how to use this package. For more detailed documentation, see https://jjeffery.github.io/sqlr. Preparing SQL queries with many placeholder arguments is tedious and error-prone. The following insert query has a dozen placeholders, and it is difficult to match up the columns with the placeholders. It is not uncommon to have tables with many more columns than this example, and the level of difficulty increases with the number of columns in the table. This package uses reflection to simplify the construction of SQL queries. Supplementary information about each database column is stored in the structure tag of the associated field. The calling program creates a schema, which describes rules for generating SQL statements. These rules include specifying the SQL dialect (eg MySQL, Postgres, SQLite) and the naming convention used to convert Go struct field names into column names (eg "GivenName" => "given_name"). The schema is usually created during program initialization. Once created, a schema is immutable and can be called concurrently from multiple goroutines. A session is created using a context, a database connection (eg *sql.DB, *sql.Tx, *sql.Conn), and a schema. A session is inexpensive to create, and is intended to last no longer than a single request (which might be a HTTP request, in the case of a HTTP server). A session is bounded by the lifetime of its context. Once a session has been created, it is possible to create simple row insert/update statements with minimal effort. The Exec method parses the SQL query and replaces occurrences of "{}" with the column names or placeholders that make sense for the SQL clause in which they occur. In the example above, the insert and update statements would look like: If the schema is created with a different dialect then the generated SQL will be different. For example if the Postgres dialect was used the insert and update queries would look more like: Inserting and updating a single row are common enough operations that the session has methods that make it very simple: Select queries can be performed using the session's Select method: The SQL queries prepared in the above example would look like the following: The examples are using a MySQL dialect. If the schema had been setup for, say, a Postgres dialect, a generated query would look more like: It is an important point to note that this feature is not about writing the SQL for the programmer. Rather it is about "filling in the blanks": allowing the programmer to specify as much of the SQL query as they want without having to write the tiresome bits. When inserting rows, if a column is defined as an autoincrement column, then the generated value will be retrieved from the database server, and the corresponding field in the row structure will be updated. Autoincrement column values work for all supported databases (PostgreSQL, MySQL, Microsoft SQL Server and SQLite). Most SQL database tables have columns that are nullable, and it can be tiresome to always map to pointer types or special nullable types such as sql.NullString. In many cases it is acceptable to map the zero value for the field a database NULL in the corresponding database column. Where it is acceptable to map a zero value to a NULL database column, the Go struct field can be marked with the "null" keyword in the field's struct tag. In the above example the `manager_id` column can be null, but if all valid IDs are non-zero, it is unambiguous to map the zero value to a database NULL. Similarly, if the `phone` column an empty string it will be stored as a NULL in the database. Care should be taken, because there are cases where a zero value and a database NULL do not represent the same thing. There are many cases, however, where this feature can be applied, and the result is simpler code that is easier to read. It is not uncommon to serialize complex objects as JSON text for storage in an SQL database. Native support for JSON is available in some database servers: in partcular Postgres has excellent support for JSON. It is straightforward to use this package to serialize a structure field to JSON: In the example above the `Cmplx` field will be marshaled as JSON text when writing to the database, and unmarshaled into the struct when reading from the database. While most SQL queries accept a fixed number of parameters, if the SQL query contains a `WHERE IN` clause, it requires additional string manipulation to match the number of placeholders in the query with args. This package simplifies queries with a variable number of arguments. When processing an SQL query, it detects if any of the arguments are slices: In the above example, the number of placeholders ("?") in the query will be increased to match the number of values in the `ids` slice. The expansion logic can handle any mix of slice and scalar arguments. A session can create type-safe query functions. This is a very powerful feature and makes it very easy to create type-safe data access. See the Session.MakeQuery function for examples.
Package Filenamer provides a set of methods for filename manipulation. It's a very simple API for adding custom prefixes and suffixes to your base filename such as timestamps, random strings etc. Very useful when working with file uploads and you need to genereate unique filenames for your uploads. Basic usage example This example shows basic usage when given file name is just cleaned up from characters that should not be used in general This example shows how to add prefix to a file name This example shows how to hash file name This example shows how to hash file name and add suffix to it
Package squalor provides SQL utility routines, such as validation of models against table schemas, marshalling and unmarshalling of model structs into table rows and programmatic construction of SQL statements. While squalor uses the database/sql package, the SQL it utilizes is MySQL specific (e.g. REPLACE, INSERT ON DUPLICATE KEY UPDATE, etc). Given a simple table definition: And a model for a row of the table: The BindModel method will validate that the model and the table definition are compatible. For example, it would be an error for the User.ID field to have the type string. The table definition is loaded from the database allowing custom checks such as verifying the existence of indexes. While fields are often primitive types such as int64 or string, it is sometimes desirable to use a custom type. This can be accomplished by having the type implement the sql.Scanner and driver.Valuer interfaces. For example, you might create a GzippedText type which automatically compresses the value when it is written to the database and uncompressed when it is read: The Insert method is used to insert one or more rows in a table. You can pass either a struct or a pointer to a struct. Multiple rows can be inserted at once. Doing so offers convenience and performance. When multiple rows are batch inserted the returned error corresponds to the first SQL error encountered which may make it impossible to determine which row caused the error. If the rows correspond to different tables the order of insertion into the tables is undefined. If you care about the order of insertion into multiple tables and determining which row is causing an insertion error, structure your calls to Insert appropriately (i.e. insert into a single table or insert a single row). After a successful insert on a table with an auto increment primary key, the auto increment will be set back in the corresponding field of the object. For example, if the user table was defined as: Then we could create a new user by doing: The Replace method replaces a row in table, either inserting the row if it doesn't exist, or deleting and then inserting the row. See the MySQL docs for the difference between REPLACE, UPDATE and INSERT ON DUPLICATE KEY UPDATE (Upsert). The Update method updates a row in a table, returning the number of rows modified. The Upsert method inserts or updates a row. The Get method retrieves a single row by primary key and binds the result columns to a struct. The delete method deletes rows by primary key. See the documentation for DB.Delete for performance limitations when batch deleting multiple rows from a table with a primary key composed of multiple columns. To support optimistic locking with a column storing the version number, one field in a model object can be marked to serve as the lock. Modifying the example above: Now, the Update method will ensure that the object has not been concurrently modified when writing, by constraining the update by the version number. If the update is successful, the version number will be both incremented on the model (in-memory), as well as in the database. Programmatic construction of SQL queries prohibits SQL injection attacks while keeping query construction both readable and similar to SQL itself. Support is provided for most of the SQL DML (data manipulation language), though the constructed queries are targetted to MySQL. DB provides wrappers for the sql.Query and sql.QueryRow interfaces. The Rows struct returned from Query has an additional StructScan method for binding the columns for a row result to a struct. QueryRow can be used to easily query and scan a single value: In addition to the convenience of inserting, deleting and updating table rows using a struct, attention has been paid to performance. Since squalor is carefully constructing the SQL queries for insertion, deletion and update, it eschews the use of placeholders in favor of properly escaping values in the query. With the Go MySQL drivers, this saves a roundtrip to the database for each query because queries with placeholders must be prepared before being executed. Marshalling and unmarshalling of data from structs utilizes reflection, but care is taken to minimize the use of reflection in order to improve performance. For example, reflection data for models is cached when the model is bound to a table. Batch operations are utilized when possible. The Delete, Insert, Replace, Update and Upsert operations will perform multiple operations per SQL statement. This can provide an order of magnitude speed improvement over performing the mutations one row at a time due to minimizing the network overhead.
Package morestrings implements additional functions to manipulate UTF-8 encoded strings, beyond what is provided in the standard "strings" package.
Package goutils provides utility functions to manipulate strings in various ways. The code snippets below show examples of how to use goutils. Some functions return errors while others do not, so usage would vary as a result. Example:
Package linq provides methods for querying and manipulating slices, arrays, maps, strings, channels and collections. Authors: Alexander Kalankhodzhaev (kalan), Ahmet Alp Balkan, Cleiton Marques Souza.
Package nlp provides implementations of selected machine learning algorithms for natural language processing of text corpora. The primary focus is the statistical semantics of plain-text documents supporting semantic analysis and retrieval of semantically similar documents. The package makes use of the Gonum (http://http//www.gonum.org/) library for linear algebra and scientific computing with some inspiration taken from Python's scikit-learn (http://scikit-learn.org/stable/) and Gensim(https://radimrehurek.com/gensim/) The primary intended use case is to support document input as text strings encoded as a matrix of numerical feature vectors called a `term document matrix`. Each column in the matrix corresponds to a document in the corpus and each row corresponds to a unique term occurring in the corpus. The individual elements within the matrix contain the frequency with which each term occurs within each document (referred to as `term frequency`). Whilst textual data from document corpora are the primary intended use case, the algorithms can be used with other types of data from other sources once encoded (vectorised) into a suitable matrix e.g. image data, sound data, users/products, etc. These matrices can be processed and manipulated through the application of additional transformations for weighting features, identifying relationships or optimising the data for analysis, information retrieval and/or predictions. Typically the algorithms in this package implement one of three primary interfaces: One of the implementations of Vectoriser is Pipeline which can be used to wire together pipelines composed of a Vectoriser and one or more Transformers arranged in serial so that the output from each stage forms the input of the next. This can be used to construct a classic LSI (Latent Semantic Indexing) pipeline (vectoriser -> TF.IDF weighting -> Truncated SVD): Whilst they take different inputs, both Vectorisers and Transformers have 3 primary methods:
Package dom provides GopherJS bindings for the JavaScript DOM APIs. This package is an in progress effort of providing idiomatic Go bindings for the DOM, wrapping the JavaScript DOM APIs. The API is neither complete nor frozen yet, but a great amount of the DOM is already useable. While the package tries to be idiomatic Go, it also tries to stick closely to the JavaScript APIs, so that one does not need to learn a new set of APIs if one is already familiar with it. One decision that hasn't been made yet is what parts exactly should be part of this package. It is, for example, possible that the canvas APIs will live in a separate package. On the other hand, types such as StorageEvent (the event that gets fired when the HTML5 storage area changes) will be part of this package, simply due to how the DOM is structured – even if the actual storage APIs might live in a separate package. This might require special care to avoid circular dependencies. The documentation for some of the identifiers is based on the MDN Web Docs by Mozilla Contributors (https://developer.mozilla.org/en-US/docs/Web/API), licensed under CC-BY-SA 2.5 (https://creativecommons.org/licenses/by-sa/2.5/). The usual entry point of using the dom package is by using the GetWindow() function which will return a Window, from which you can get things such as the current Document. The DOM has a big amount of different element and event types, but they all follow three interfaces. All functions that work on or return generic elements/events will return one of the three interfaces Element, HTMLElement or Event. In these interface values there will be concrete implementations, such as HTMLParagraphElement or FocusEvent. It's also not unusual that values of type Element also implement HTMLElement. In all cases, type assertions can be used. Example: Several functions in the JavaScript DOM return "live" collections of elements, that is collections that will be automatically updated when elements get removed or added to the DOM. Our bindings, however, return static slices of elements that, once created, will not automatically reflect updates to the DOM. This is primarily done so that slices can actually be used, as opposed to a form of iterator, but also because we think that magically changing data isn't Go's nature and that snapshots of state are a lot easier to reason about. This does not, however, mean that all objects are snapshots. Elements, events and generally objects that aren't slices or maps are simple wrappers around JavaScript objects, and as such attributes as well as method calls will always return the most current data. To reflect this behaviour, these bindings use pointers to make the semantics clear. Consider the following example: The above example will print `true`. Some objects in the JS API have two versions of attributes, one that returns a string and one that returns a DOMTokenList to ease manipulation of string-delimited lists. Some other objects only provide DOMTokenList, sometimes DOMSettableTokenList. To simplify these bindings, only the DOMTokenList variant will be made available, by the type TokenList. In cases where the string attribute was the only way to completely replace the value, our TokenList will provide Set([]string) and SetString(string) methods, which will be able to accomplish the same. Additionally, our TokenList will provide methods to convert it to strings and slices. This package has a relatively stable API. However, there will be backwards incompatible changes from time to time. This is because the package isn't complete yet, as well as because the DOM is a moving target, and APIs do change sometimes. While an attempt is made to reduce changing function signatures to a minimum, it can't always be guaranteed. Sometimes mistakes in the bindings are found that require changing arguments or return values. Interfaces defined in this package may also change on a semi-regular basis, as new methods are added to them. This happens because the bindings aren't complete and can never really be, as new features are added to the DOM.
Package morestrings implements additional functions to manipulate UTF-8 encoded strings, beyond what is provided in the standard "strings" package.
Package jsonfs provides a JSON marshal/unmarshaller that treats JSON objects as directories and JSON values (bools, numbers or strings) as files. This is an alternative to various other structures for dealing with JSON that either use maps or structs to represent data. This is particularly great for doing discovery on JSON data or manipulating JSON. Each file is read-only. You can switch out files in a directory in order to make updates. A File represents a JSON basic value of bool, integer, float, null or string. A Directory represents a JSON object or array. Because a directory can be an object or array, a directory that represents an array has _.array._ appened to the name in some filesystems. If creating an array using filesytem tools, use ArrayDirName("name_of_your_array"), which will append the correct suffix. You always opened the file with simply the name. This also means that naming an object (not array) _.array._ will cause unexpected results. This is a thought experiment. However, it is quite performant, but does have the unattractive nature of being more verbose. Also, you may find problems if your JSON dict keys have invalid characters for the filesystem you are running on AND you use the diskfs filesystem. For the memfs, this is mostly not a problem, except for /. You cannot use / in your keys. We are slower and allocate more memory. I'm going to have to spend some time optimising the memory use. I had some previous benchmarks that showed this was faster. But I had a mistake that became obvious with using a large file, (unless I was 700,000x faster on unmarshal, and I'm not that good). Example of unmarshalling a JSON file: Example of creating a JSON object via the library: Example of marshaling a Directory: Example of getting a JSON value by field name: Same example, but we are okay with zero values if the field doesn't exist: Get the type a File holds: Get a value the easiest way when you aren't sure what it is: Get a value from a Directory when you care about all the details (uck): Get a value from a Directory when zero values will do if set to null or doesn't exist: Put the value in an fs.FS and walk the JSON:
Package dom provides GopherJS bindings for the JavaScript DOM APIs. This package is an in progress effort of providing idiomatic Go bindings for the DOM, wrapping the JavaScript DOM APIs. The API is neither complete nor frozen yet, but a great amount of the DOM is already useable. While the package tries to be idiomatic Go, it also tries to stick closely to the JavaScript APIs, so that one does not need to learn a new set of APIs if one is already familiar with it. One decision that hasn't been made yet is what parts exactly should be part of this package. It is, for example, possible that the canvas APIs will live in a separate package. On the other hand, types such as StorageEvent (the event that gets fired when the HTML5 storage area changes) will be part of this package, simply due to how the DOM is structured – even if the actual storage APIs might live in a separate package. This might require special care to avoid circular dependencies. The documentation for some of the identifiers is based on the MDN Web Docs by Mozilla Contributors (https://developer.mozilla.org/en-US/docs/Web/API), licensed under CC-BY-SA 2.5 (https://creativecommons.org/licenses/by-sa/2.5/). The usual entry point of using the dom package is by using the GetWindow() function which will return a Window, from which you can get things such as the current Document. The DOM has a big amount of different element and event types, but they all follow three interfaces. All functions that work on or return generic elements/events will return one of the three interfaces Element, HTMLElement or Event. In these interface values there will be concrete implementations, such as HTMLParagraphElement or FocusEvent. It's also not unusual that values of type Element also implement HTMLElement. In all cases, type assertions can be used. Example: Several functions in the JavaScript DOM return "live" collections of elements, that is collections that will be automatically updated when elements get removed or added to the DOM. Our bindings, however, return static slices of elements that, once created, will not automatically reflect updates to the DOM. This is primarily done so that slices can actually be used, as opposed to a form of iterator, but also because we think that magically changing data isn't Go's nature and that snapshots of state are a lot easier to reason about. This does not, however, mean that all objects are snapshots. Elements, events and generally objects that aren't slices or maps are simple wrappers around JavaScript objects, and as such attributes as well as method calls will always return the most current data. To reflect this behaviour, these bindings use pointers to make the semantics clear. Consider the following example: The above example will print `true`. Some objects in the JS API have two versions of attributes, one that returns a string and one that returns a DOMTokenList to ease manipulation of string-delimited lists. Some other objects only provide DOMTokenList, sometimes DOMSettableTokenList. To simplify these bindings, only the DOMTokenList variant will be made available, by the type TokenList. In cases where the string attribute was the only way to completely replace the value, our TokenList will provide Set([]string) and SetString(string) methods, which will be able to accomplish the same. Additionally, our TokenList will provide methods to convert it to strings and slices. This package has a relatively stable API. However, there will be backwards incompatible changes from time to time. This is because the package isn't complete yet, as well as because the DOM is a moving target, and APIs do change sometimes. While an attempt is made to reduce changing function signatures to a minimum, it can't always be guaranteed. Sometimes mistakes in the bindings are found that require changing arguments or return values. Interfaces defined in this package may also change on a semi-regular basis, as new methods are added to them. This happens because the bindings aren't complete and can never really be, as new features are added to the DOM. If you depend on none of the APIs changing unexpectedly, you're advised to vendor this package.
Sprig: Template functions for Go. This package contains a number of utility functions for working with data inside of Go `html/template` and `text/template` files. To add these functions, use the `template.Funcs()` method: Note that you should add the function map before you parse any template files. Date Functions String Functions String Slice Functions: Integer Slice Functions: Conversions: Defaults: OS: File Paths: Encoding: Reflection: typeOf: Takes an interface and returns a string representation of the type. For pointers, this will return a type prefixed with an asterisk(`*`). So a pointer to type `Foo` will be `*Foo`. typeIs: Compares an interface with a string name, and returns true if they match. Note that a pointer will not match a reference. For example `*Foo` will not match `Foo`. typeIsLike: Compares an interface with a string name and returns true if the interface is that `name` or that `*name`. In other words, if the given value matches the given type or is a pointer to the given type, this returns true. kindOf: Takes an interface and returns a string representation of its kind. kindIs: Returns true if the given string matches the kind of the given interface. Note: None of these can test whether or not something implements a given interface, since doing so would require compiling the interface in ahead of time. Data Structures: Lists Functions: These are used to manipulate lists: '{{ list 1 2 3 | reverse | first }}' Dict Functions: These are used to manipulate dicts. Math Functions: Integer functions will convert integers of any width to `int64`. If a string is passed in, functions will attempt to convert with `strconv.ParseInt(s, 1064)`. If this fails, the value will be treated as 0. Crypto Functions: SemVer Functions: These functions provide version parsing and comparisons for SemVer 2 version strings.
Package dom provides GopherJS and Go bindings for the JavaScript DOM APIs. This package is an in progress effort of providing idiomatic Go bindings for the DOM, wrapping the JavaScript DOM APIs. The API is neither complete nor frozen yet, but a great amount of the DOM is already useable. While the package tries to be idiomatic Go, it also tries to stick closely to the JavaScript APIs, so that one does not need to learn a new set of APIs if one is already familiar with it. One decision that hasn't been made yet is what parts exactly should be part of this package. It is, for example, possible that the canvas APIs will live in a separate package. On the other hand, types such as StorageEvent (the event that gets fired when the HTML5 storage area changes) will be part of this package, simply due to how the DOM is structured – even if the actual storage APIs might live in a separate package. This might require special care to avoid circular dependencies. The documentation for some of the identifiers is based on the MDN Web Docs by Mozilla Contributors (https://developer.mozilla.org/en-US/docs/Web/API), licensed under CC-BY-SA 2.5 (https://creativecommons.org/licenses/by-sa/2.5/). The usual entry point of using the dom package is by using the GetWindow() function which will return a Window, from which you can get things such as the current Document. The DOM has a big amount of different element and event types, but they all follow three interfaces. All functions that work on or return generic elements/events will return one of the three interfaces Element, HTMLElement or Event. In these interface values there will be concrete implementations, such as HTMLParagraphElement or FocusEvent. It's also not unusual that values of type Element also implement HTMLElement. In all cases, type assertions can be used. Example: Several functions in the JavaScript DOM return "live" collections of elements, that is collections that will be automatically updated when elements get removed or added to the DOM. Our bindings, however, return static slices of elements that, once created, will not automatically reflect updates to the DOM. This is primarily done so that slices can actually be used, as opposed to a form of iterator, but also because we think that magically changing data isn't Go's nature and that snapshots of state are a lot easier to reason about. This does not, however, mean that all objects are snapshots. Elements, events and generally objects that aren't slices or maps are simple wrappers around JavaScript objects, and as such attributes as well as method calls will always return the most current data. To reflect this behaviour, these bindings use pointers to make the semantics clear. Consider the following example: The above example will print `true`. Some objects in the JS API have two versions of attributes, one that returns a string and one that returns a DOMTokenList to ease manipulation of string-delimited lists. Some other objects only provide DOMTokenList, sometimes DOMSettableTokenList. To simplify these bindings, only the DOMTokenList variant will be made available, by the type TokenList. In cases where the string attribute was the only way to completely replace the value, our TokenList will provide Set([]string) and SetString(string) methods, which will be able to accomplish the same. Additionally, our TokenList will provide methods to convert it to strings and slices. This package has a relatively stable API. However, there will be backwards incompatible changes from time to time. This is because the package isn't complete yet, as well as because the DOM is a moving target, and APIs do change sometimes. While an attempt is made to reduce changing function signatures to a minimum, it can't always be guaranteed. Sometimes mistakes in the bindings are found that require changing arguments or return values. Interfaces defined in this package may also change on a semi-regular basis, as new methods are added to them. This happens because the bindings aren't complete and can never really be, as new features are added to the DOM. If you depend on none of the APIs changing unexpectedly, you're advised to vendor this package.