### Install Gotils Package Source: https://github.com/dajooo/gotils/blob/main/README.md Command to install the gotils Go package using the go get command. ```bash go get dario.lol/gotils ``` -------------------------------- ### Base64 Encoding and Decoding (Go) Source: https://github.com/dajooo/gotils/blob/main/README.md Provides functions for encoding and decoding strings and byte slices to and from Base64 format. Includes URL-safe variants and options for padding. ```Go package main import "fmt" func main() { // String encoding and decoding encodedString := B64Encode("hello world") fmt.Println("Encoded string:", encodedString) decodedString, err := B64Decode(encodedString) if err != nil { fmt.Println("Error decoding string:", err) } else { fmt.Println("Decoded string:", decodedString) } // Bytes encoding and decoding dataBytes := []byte("hello world") encodedBytes := B64EncodeBytes(dataBytes) fmt.Println("Encoded bytes:", string(encodedBytes)) decodedBytes, err := B64DecodeBytes(encodedBytes) if err != nil { fmt.Println("Error decoding bytes:", err) } else { fmt.Println("Decoded bytes:", decodedBytes) } // URL-safe encoding and decoding urlSafeEncoded := B64URLEncode("hello/world+") fmt.Println("URL-safe encoded:", urlSafeEncoded) urlSafeDecoded, err := B64URLDecode(urlSafeEncoded) if err != nil { fmt.Println("Error URL-safe decoding:", err) } else { fmt.Println("URL-safe decoded:", urlSafeDecoded) } } ``` -------------------------------- ### Argon2id Password Hashing and Verification (Go) Source: https://github.com/dajooo/gotils/blob/main/README.md Implements Argon2id password hashing with configurable parameters for memory, iterations, parallelism, and key length. Supports hashing bytes and strings, with various output formats (bytes, formatted string) and includes verification functions. ```Go package main import "fmt" // Placeholder Argon2idParams struct type Argon2idParams struct { Memory uint32 Iterations uint32 Parallelism uint8 KeyLen uint32 } // Dummy Argon2id functions for demonstration func Argon2idBytes(password []byte) ([]byte, error) { return []byte("dummy_hash_bytes"), nil } func Argon2idBytesWithSalt(password, salt []byte) []byte { return []byte("dummy_hash_bytes_salt") } func Argon2idBytesWithParams(password, salt []byte, p Argon2idParams) []byte { return []byte("dummy_hash_bytes_params") } func Argon2idString(password string) ([]byte, error) { return []byte("dummy_hash_string_bytes"), nil } func Argon2idStringWithSalt(password string, salt []byte) []byte { return []byte("dummy_hash_string_salt") } func Argon2idStringWithParams(password string, salt []byte, p Argon2idParams) []byte { return []byte("dummy_hash_string_params") } func Argon2idBytesToString(password []byte) (string, error) { return "$argon2id$v=19$m=2048,t=3,p=1$c29tZXNhbHQ$c29tZWhhc2g=", nil } func Argon2idBytesToStringWithSalt(password, salt []byte) string { return "$argon2id$v=19$m=2048,t=3,p=1$c29tZXNhbHQ$c29tZWhhc2g=" } func Argon2idBytesToStringWithParams(password, salt []byte, p Argon2idParams) string { return "$argon2id$v=19$m=2048,t=3,p=1$c29tZXNhbHQ$c29tZWhhc2g=" } func Argon2idStringToString(password string) (string, error) { return "$argon2id$v=19$m=2048,t=3,p=1$c29tZXNhbHQ$c29tZWhhc2g=", nil } func Argon2idStringToStringWithSalt(password string, salt []byte) string { return "$argon2id$v=19$m=2048,t=3,p=1$c29tZXNhbHQ$c29tZWhhc2g=" } func Argon2idStringToStringWithParams(password string, salt []byte, p Argon2idParams Argon2idParams) string { return "$argon2id$v=19$m=2048,t=3,p=1$c29tZXNhbHQ$c29tZWhhc2g=" } func VerifyArgon2id(hashedPassword string, password []byte) (bool, error) { return true, nil } func VerifyArgon2idString(hashedPassword, password string) (bool, error) { return true, nil } func MustVerifyArgon2id(hashedPassword string, password []byte) bool { return true } func MustVerifyArgon2idString(hashedPassword, password string) bool { return true } func main() { password := "mysecretpassword" passwordBytes := []byte(password) salt := []byte("somesalt") params := Argon2idParams{ Memory: 2048, // 2 KB Iterations: 32768, Parallelism: 4, KeyLen: 32, } // Hashing examples hashedBytes, err := Argon2idBytes(passwordBytes) if err != nil { fmt.Println("Error hashing bytes:", err) } else { fmt.Println("Hashed bytes (default):", string(hashedBytes)) } hashedWithSalt := Argon2idStringWithSalt(password, salt) fmt.Println("Hashed string with salt:", hashedWithSalt) hashedWithParams := Argon2idStringToStringWithParams(password, salt, params) fmt.Println("Hashed string with params:", hashedWithParams) // Verification examples matchBytes, err := VerifyArgon2id(hashedWithParams, passwordBytes) if err != nil { fmt.Println("Error verifying bytes:", err) } else { fmt.Println("Password match (bytes)?", matchBytes) } matchString := VerifyArgon2idString(hashedWithParams, password) fmt.Println("Password match (string)?", matchString) } ``` -------------------------------- ### Argon2id Hashing and Verification Source: https://github.com/dajooo/gotils/blob/main/README.md Provides functions for Argon2id password hashing with configurable parameters and verification. ```APIDOC ## Argon2id Hashing and Verification ### Description Functions for hashing passwords using Argon2id with configurable parameters, and for verifying hashed passwords. ### Argon2id Parameters ```go type Argon2idParams struct { Memory uint32 // Memory usage in KB Iterations uint32 // Number of iterations Parallelism uint8 // Degree of parallelism KeyLen uint32 // Length of the hash in bytes } ``` ### Hashing Operations #### Byte Operations - `Argon2idBytes(password []byte) ([]byte, error)` - Hash password bytes with default parameters. - `Argon2idBytesWithSalt(password, salt []byte) []byte` - Hash password bytes with custom salt. - `Argon2idBytesWithParams(password, salt []byte, p Argon2idParams) []byte` - Hash password bytes with custom salt and parameters. #### String Input Operations - `Argon2idString(password string) ([]byte, error)` - Hash password string, output bytes. - `Argon2idStringWithSalt(password string, salt []byte) []byte` - Hash password string with custom salt. - `Argon2idStringWithParams(password string, salt []byte, p Argon2idParams) []byte` - Hash password string with custom salt and parameters. #### String Output Operations - `Argon2idBytesToString(password []byte) (string, error)` - Hash password bytes, output formatted string. - `Argon2idBytesToStringWithSalt(password, salt []byte) string` - Hash password bytes with custom salt, output formatted string. - `Argon2idBytesToStringWithParams(password, salt []byte, p Argon2idParams) string` - Hash password bytes with custom salt and parameters, output formatted string. #### String Input/Output Operations - `Argon2idStringToString(password string) (string, error)` - Hash password string, output formatted string. - `Argon2idStringToStringWithSalt(password string, salt []byte) string` - Hash password string with custom salt, output formatted string. - `Argon2idStringToStringWithParams(password string, salt []byte, p Argon2idParams) string` - Hash password string with custom salt and parameters, output formatted string. ### Verification Operations - `VerifyArgon2id(hashedPassword string, password []byte) (bool, error)` - Verify password bytes against a hashed password. - `VerifyArgon2idString(hashedPassword, password string) (bool, error)` - Verify password string against a hashed password. - `MustVerifyArgon2id(hashedPassword string, password []byte) bool` - Same as VerifyArgon2id but panics on error. - `MustVerifyArgon2idString(hashedPassword, password string) bool` - Same as VerifyArgon2idString but panics on error. ### Default Parameters - Memory: 2 KB - Iterations: 32,768 - Parallelism: 4 - Key Length: 32 bytes ### String Output Format `$argon2id$v=19$m=memory,t=iterations,p=parallelism$salt$hash` ``` -------------------------------- ### Go Slice Creation Utilities Source: https://github.com/dajooo/gotils/blob/main/README.md Functions for generating slices in Go, including repeating elements a specified number of times or generating elements using a function. Also includes stream-based generation using channels. ```Go package main import "fmt" // Repeat creates a slice with repeated elements. func Repeat[T any](count int, elem T) []T { if count <= 0 { return nil } result := make([]T, count) for i := 0; i < count; i++ { result[i] = elem } return result } // RepeatStream creates a channel stream with repeated elements. func RepeatStream[T any](count int, elem T) <-chan T { ch := make(chan T, count) go func() { defer close(ch) for i := 0; i < count; i++ { ch <- elem } }() return ch } func main() { // Repeat a string 3 times repeatedStrings := Repeat(3, "hello") fmt.Printf("Repeated strings: %v\n", repeatedStrings) // Consume a stream of repeated integers for val := range RepeatStream(4, 100) { fmt.Printf("Stream value: %d\n", val) } } ``` -------------------------------- ### Base64 Encoding and Decoding Source: https://github.com/dajooo/gotils/blob/main/README.md Provides functions for encoding and decoding strings and byte slices to and from Base64 format, including URL-safe variants. ```APIDOC ## Base64 Operations ### Description Functions for Base64 encoding and decoding of strings and byte slices. ### String Operations - `B64Encode(data string, padding ...rune) string` - Encodes string to base64 string. - `B64Decode(data string) (string, error)` - Decodes base64 string to string. - `MustB64Decode(data string) string` - Same as B64Decode but panics on error. ### Bytes Operations - `B64EncodeBytes(data []byte, padding ...rune) string` - Encodes bytes to base64 string. - `B64DecodeBytes(data []byte) (string, error)` - Decodes base64 bytes to string. - `B64EncodeBytesToBytes(data []byte, padding ...rune) []byte` - Encodes bytes to base64 bytes. - `B64DecodeBytesToBytes(data []byte) ([]byte, error)` - Decodes base64 bytes to bytes. ### URL-safe Variants - `B64URLEncode(data string, padding ...rune) string` - URL-safe base64 encoding. - `B64URLDecode(data string) (string, error)` - URL-safe base64 decoding. - `B64URLEncodeBytes(data []byte, padding ...rune) string` - URL-safe base64 encoding of bytes. - `B64URLDecodeBytes(data []byte) (string, error)` - URL-safe base64 decoding to string. ``` -------------------------------- ### String Case Utilities Source: https://github.com/dajooo/gotils/blob/main/README.md Utility functions for detecting, parsing, and converting string case styles. ```APIDOC ## String Case Utilities ### Description Functions to detect, parse, and convert string case styles. ### Case Detection and Parsing - `DetectCase(s string) StringCaseKind` - Detects the case style of a string. - `ParseCase(s string) StringCase` - Parses a string into its case parts. ### Case Conversion - `(StringCase) ToCamelCase() string` - Converts to camelCase. - `(StringCase) ToPascalCase() string` - Converts to PascalCase. - `(StringCase) ToSnakeCase() string` - Converts to snake_case. - `(StringCase) ToKebabCase() string` - Converts to kebab-case. - `(StringCase) ToScreamingSnakeCase() string` - Converts to SCREAMING_SNAKE_CASE. ### Supported Case Types - CamelCase (e.g. "camelCase") - PascalCase (e.g. "PascalCase") - SnakeCase (e.g. "snake_case") - KebabCase (e.g. "kebab-case") - ScreamingSnakeCase (e.g. "SCREAMING_SNAKE_CASE") ``` -------------------------------- ### Go Pointer Utilities Source: https://github.com/dajooo/gotils/blob/main/README.md Functions for creating and safely dereferencing pointers in Go. Handles nil pointers gracefully by providing default values or panicking. ```Go package main import "fmt" // Of creates a pointer from a value. func Of[T any](v T) *T { return &v } // OfOk creates a pointer from a value if ok is true, nil otherwise. func OfOk[T any](v T, ok bool) *T { if !ok { return nil } return &v } // Resolve safely resolves a pointer to its value. func Resolve[T any](v *T) T { return *v } // ResolveOrDefault resolves a pointer or returns the zero value if nil. func ResolveOrDefault[T any](v *T) T { if v == nil { var zero T return zero } return *v } // ResolveOr resolves a pointer or returns the provided default value if nil. func ResolveOr[T any](v *T, defaultValue T) T { if v == nil { return defaultValue } return *v } func main() { // Example Usage: num := 5 numPtr := Of(num) resolvedNum := Resolve(numPtr) fmt.Printf("Resolved value: %d\n", resolvedNum) var nilPtr *int defaultVal := ResolveOr(nilPtr, 10) fmt.Printf("Resolved with default: %d\n", defaultVal) } ``` -------------------------------- ### String Joining Source: https://github.com/dajooo/gotils/blob/main/README.md Function to join strings received from a channel with a specified separator. ```APIDOC ## String Joining ### Description Joins strings from a channel with a specified separator. ### JoinStream - `JoinStream(sep string, stringChan <-chan string) string` - Joins strings from a channel with separator. ``` -------------------------------- ### String Case Detection and Conversion (Go) Source: https://github.com/dajooo/gotils/blob/main/README.md Utilities for detecting the case style of a string and converting it between various formats like camelCase, PascalCase, snake_case, kebab-case, and SCREAMING_SNAKE_CASE. ```Go package main import "fmt" type StringCaseKind int const ( Unknown StringCaseKind = iota CamelCase PascalCase SnakeCase KebabCase ScreamingSnakeCase ) // Placeholder types and methods for demonstration type StringCase struct {} func (sc StringCase) ToCamelCase() string { return "camelCase" } func (sc StringCase) ToPascalCase() string { return "PascalCase" } func (sc StringCase) ToSnakeCase() string { return "snake_case" } func (sc StringCase) ToKebabCase() string { return "kebab-case" } func (sc StringCase) ToScreamingSnakeCase() string { return "SCREAMING_SNAKE_CASE" } func DetectCase(s string) StringCaseKind { return CamelCase } // Dummy implementation func ParseCase(s string) StringCase { return StringCase{} } // Dummy implementation func main() { testString := "someExampleString" caseKind := DetectCase(testString) fmt.Printf("Detected case kind for '%s': %v\n", testString, caseKind) parsed := ParseCase(testString) fmt.Println("CamelCase:", parsed.ToCamelCase()) fmt.Println("PascalCase:", parsed.ToPascalCase()) fmt.Println("SnakeCase:", parsed.ToSnakeCase()) fmt.Println("KebabCase:", parsed.ToKebabCase()) fmt.Println("ScreamingSnakeCase:", parsed.ToScreamingSnakeCase()) } ``` -------------------------------- ### Go File Writing Utilities Source: https://github.com/dajooo/gotils/blob/main/README.md Functions for writing data to files in Go. Supports writing bytes, strings, slices of strings, and marshaling Go types into JSON format. ```Go package main import ( "encoding/json" "fmt" os "os" ) // WriteString writes a string to a file. func WriteString(path, data string) error { return os.WriteFile(path, []byte(data), 0644) } // WriteLines writes a slice of strings to a file, each on a new line. func WriteLines(path string, lines []string) error { content := "" for i, line := range lines { content += line if i < len(lines)-1 { content += "\n" } } return os.WriteFile(path, []byte(content), 0644) } // WriteJson writes a Go type to a file as JSON. func WriteJson[T any](path string, data T, indent ...string) error { var jsonData []byte var err error if len(indent) > 0 { jsonData, err = json.MarshalIndent(data, "", indent[0]) } else { jsonData, err = json.Marshal(data) } if err != nil { return err } return os.WriteFile(path, jsonData, 0644) } func main() { // Write string to file fileNameStr := "output_string.txt" WriteString(fileNameStr, "This is a test string.") fmt.Printf("Wrote string to %s\n", fileNameStr) // Write lines to file fileNameLines := "output_lines.txt" lines := []string{"Line 1", "Line 2", "Line 3"} WriteLines(fileNameLines, lines) fmt.Printf("Wrote lines to %s\n", fileNameLines) // Write JSON to file type Person struct { Name string `json:"name"` Age int `json:"age"` } person := Person{Name: "Alice", Age: 30} fileNameJson := "output.json" WriteJson(fileNameJson, person, " ") // Use 2 spaces for indentation fmt.Printf("Wrote JSON to %s\n", fileNameJson) // Clean up dummy files os.Remove(fileNameStr) os.Remove(fileNameLines) os.Remove(fileNameJson) } ``` -------------------------------- ### Go Slice Pointer Conversion Source: https://github.com/dajooo/gotils/blob/main/README.md Utility functions for converting between slices of values and slices of pointers in Go. Includes methods to convert slices to pointers and vice-versa. ```Go package main import "fmt" // ToPtr converts a slice of values to a slice of pointers. func ToPtr[T any](slice []T) []*T { result := make([]*T, len(slice)) for i, v := range slice { result[i] = &v } return result } // FromPtr converts a slice of pointers to a slice of values. func FromPtr[T any](slice []*T) []T { result := make([]T, 0, len(slice)) for _, v := range slice { if v != nil { result = append(result, *v) } } return result } func main() { values := []int{10, 20, 30} // Convert values to pointers pointers := ToPtr(values) fmt.Printf("Slice of pointers: %v\n", pointers) // Convert pointers back to values valuesFromPtr := FromPtr(pointers) fmt.Printf("Slice from pointers: %v\n", valuesFromPtr) } ``` -------------------------------- ### Go Map to Slice Conversion Source: https://github.com/dajooo/gotils/blob/main/README.md Utilities for converting Go maps into slices of key-value entries or slices of keys/values. Includes functions to create maps from entries and filter map entries. ```Go package main import "fmt" type Entry[K comparable, V any] struct { Key K Value V } // Entries converts a map into a slice of key-value entries. func Entries[K comparable, V any](m map[K]V) []Entry[K, V] { if m == nil { return nil } result := make([]Entry[K, V], 0, len(m)) for k, v := range m { result = append(result, Entry[K, V]{Key: k, Value: v}) } return result } // Keys extracts all keys from a map into a slice. func Keys[K comparable, V any](m map[K]V) []K { if m == nil { return nil } result := make([]K, 0, len(m)) for k := range m { result = append(result, k) } return result } func main() { myMap := map[string]int{ "apple": 1, "banana": 2, "cherry": 3, } // Convert map to entries mapEntries := Entries(myMap) fmt.Printf("Map entries: %+v\n", mapEntries) // Get map keys mapKeys := Keys(myMap) fmt.Printf("Map keys: %v\n", mapKeys) } ``` -------------------------------- ### Generate Secure Passwords with Gotils Source: https://github.com/dajooo/gotils/blob/main/README.md Generates secure passwords using configurable options for length, character types (uppercase, lowercase, numbers, special characters), custom character sets, and excluded characters. It includes functions for generating passwords and options to customize the generation process. ```go type GenerateConfig struct { Length int // Password length UseUpper bool // Include uppercase letters UseLower bool // Include lowercase letters UseNumbers bool // Include numbers UseSpecial bool // Include special characters CustomCharset string // Custom character set ExcludeChars string // Characters to exclude } // Generate(options ...GenerateOption) (string, error) // MustGenerate(options ...GenerateOption) string // GenerateWithLengthOption(length int) // GenerateWithoutUpperOption() // GenerateWithoutLowerOption() // GenerateWithoutNumbersOption() // GenerateWithoutSpecialOption() // GenerateWithCustomCharsetOption(charset string) // GenerateWithExcludedCharsOption(chars string) ``` -------------------------------- ### Go Slice Mapping and Filtering Source: https://github.com/dajooo/gotils/blob/main/README.md Provides functions for transforming and filtering elements within Go slices. Supports mapping to different types, filtering based on predicates, and handling pointers within slices. ```Go package main import "fmt" // Map maps a slice to another type using a provided function. func Map[T, R any](slice []T, fn func(T) R) []R { result := make([]R, len(slice)) for i, v := range slice { result[i] = fn(v) } return result } // Filter filters slice elements based on a predicate function. func Filter[T any](s []T, f func(T) bool) []T { result := []T{} for _, v := range s { if f(v) { result = append(result, v) } } return result } func main() { numbers := []int{1, 2, 3, 4, 5} // Map to strings strings := Map(numbers, func(n int) string { return fmt.Sprintf("num_%d", n) }) fmt.Printf("Mapped strings: %v\n", strings) // Filter even numbers evenNumbers := Filter(numbers, func(n int) bool { return n%2 == 0 }) fmt.Printf("Filtered even numbers: %v\n", evenNumbers) } ``` -------------------------------- ### Join Strings from Channel (Go) Source: https://github.com/dajooo/gotils/blob/main/README.md A utility function to join strings received from a string channel into a single string, using a specified separator. This is useful for processing streamed data. ```Go package main import ( "fmt" "time" ) // Dummy JoinStream function for demonstration func JoinStream(sep string, stringChan <-chan string) string { result := "" first := true for s := range stringChan { if !first { result += sep } result += s first = false } return result } func main() { dataChan := make(chan string, 3) go func() { dataChan <- "apple" dataChan <- "banana" dataChan <- "cherry" close(dataChan) }() joinedString := JoinStream(", ", dataChan) fmt.Println("Joined string:", joinedString) // Example with different separator dataChan2 := make(chan string, 2) go func() { dataChan2 <- "first" dataChan2 <- "second" close(dataChan2) }() joinedString2 := JoinStream(" | ", dataChan2) fmt.Println("Joined string 2:", joinedString2) } ``` -------------------------------- ### Go File Reading Utilities Source: https://github.com/dajooo/gotils/blob/main/README.md Functions for reading content from files in various formats. Supports reading as bytes, strings, lines, or unmarshaling JSON directly into a Go type. ```Go package main import ( "fmt" "os" ) // ReadString reads a file as a string. func ReadString(path string) (string, error) { data, err := os.ReadFile(path) if err != nil { return "", err } return string(data), nil } // ReadLines reads a file into a slice of strings, one per line. func ReadLines(path string) ([]string, error) { data, err := os.ReadFile(path) if err != nil { return nil, err } lines := []string{} for _, line := range bytes.Split(data, []byte("\n")) { lines = append(lines, string(line)) } return lines, nil } func main() { // Create a dummy file for reading fileName := "test.txt" content := "Hello,\nWorld!\nThis is a test." os.WriteFile(fileName, []byte(content), 0644) // Read file as string strContent, err := ReadString(fileName) if err != nil { fmt.Printf("Error reading string: %v\n", err) } else { fmt.Printf("File content as string:\n%s\n", strContent) } // Read file as lines linesContent, err := ReadLines(fileName) if err != nil { fmt.Printf("Error reading lines: %v\n", err) } else { fmt.Printf("File content as lines: %v\n", linesContent) } // Clean up the dummy file os.Remove(fileName) } ``` -------------------------------- ### Go Error Handling Utilities Source: https://github.com/dajooo/gotils/blob/main/README.md Functions for simplifying error handling in Go by allowing values to be returned directly or panicking on error. Useful for critical operations where errors must be handled immediately. ```Go package main import "fmt" // Must returns value or panics if error occurs. func Must[T any](value T, err error) T { if err != nil { panic(err) } return value } // MustOk returns value or panics if ok is false. func MustOk[T any](value T, ok bool) T { if !ok { panic("operation failed") } return value } func main() { // Example Usage: result := Must("success", nil) fmt.Printf("Must result: %s\n", result) // This would panic: // Must("fail", fmt.Errorf("an error occurred")) value := MustOk("ok", true) fmt.Printf("MustOk result: %s\n", value) // This would panic: // MustOk("not ok", false) } ``` -------------------------------- ### Verify Passwords with Gotils Source: https://github.com/dajooo/gotils/blob/main/README.md Validates passwords against common security criteria including minimum length, maximum length, and the requirement for specific character types (uppercase, lowercase, numbers, special characters). It provides verification functions and options to customize the validation rules. ```go type VerifyConfig struct { MinLength int // Minimum length required MaxLength int // Maximum length allowed UseUpper bool // Require uppercase letters UseLower bool // Require lowercase letters UseNumbers bool // Require numbers UseSpecial bool // Require special characters } // Verify(password string, options ...VerifyOption) error // MustVerify(password string, options ...VerifyOption) // VerifyWithMinLengthOption(length int) // VerifyWithMaxLengthOption(length int) // VerifyWithoutUpperOption() // VerifyWithoutLowerOption() // VerifyWithoutNumbersOption() // VerifyWithoutSpecialOption() ``` -------------------------------- ### Go JSON Marshaling and Unmarshaling Source: https://github.com/dajooo/gotils/blob/main/README.md Utilities for marshaling Go types to JSON and unmarshaling JSON data back into Go types. Supports custom marshaler/unmarshaler functions and provides panic-on-error variants. ```Go package main import ( "encoding/json" "fmt" ) // MarshalJSON marshals a Go type into JSON bytes. func MarshalJSON[T any](v T, marshaler ...json.Marshaler) ([]byte, error) { // Note: The `json.Marshaler` interface is not directly usable like this. // This signature might imply a custom marshaling logic is intended, // but standard `json.Marshal` is used here for demonstration. // For custom marshaling, the type T would typically implement json.Marshaler. return json.Marshal(v) } // MustMarshalJSON is similar to MarshalJSON but panics on error. func MustMarshalJSON[T any](v T, marshaler ...json.Marshaler) []byte { data, err := MarshalJSON(v, marshaler...) if err != nil { panic(err) } return data } // UnmarshalJSON unmarshals JSON bytes into a Go type. func UnmarshalJSON[T any](data []byte, unmarshaler ...json.Unmarshaler) (T, error) { // Note: Similar to MarshalJSON, `json.Unmarshaler` is an interface // implemented by types. Standard `json.Unmarshal` is used. var result T err := json.Unmarshal(data, &result) if err != nil { return result, err } return result, nil } // MustUnmarshalJSON is similar to UnmarshalJSON but panics on error. func MustUnmarshalJSON[T any](data []byte, unmarshaler ...json.Unmarshaler) T { result, err := UnmarshalJSON[T](data, unmarshaler...) if err != nil { panic(err) } return result } func main() { type Item struct { Name string `json:"name"` Value int `json:"value"` } item := Item{Name: "Gadget", Value: 123} // Marshal to JSON jsonData, err := MarshalJSON(item) if err != nil { fmt.Printf("Marshal error: %v\n", err) } else { fmt.Printf("Marshaled JSON: %s\n", jsonData) // Unmarshal from JSON var unmarshaledItem Item unmarshaledItem, err := UnmarshalJSON[Item](jsonData) if err != nil { fmt.Printf("Unmarshal error: %v\n", err) } else { fmt.Printf("Unmarshaled item: %+v\n", unmarshaledItem) } } // Example using MustMarshalJSON mustJson := MustMarshalJSON(item) fmt.Printf("MustMarshalJSON: %s\n", mustJson) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.