Share & grow the world's code base!

Delve into a community where programmers unite to discover code snippets, exchange skills, and enhance their programming proficiency. With abundant resources and a supportive community, you'll find everything essential for your growth and success.

39 snippets
  • Copy file in Go

    package main
    
    import (
        "io"
        "fmt"
        "os"
    )
    
    // copy file using os package
    func copyFileUsingOsPackage(src, dst string) error {
        bytesRead, err := os.ReadFile(src)
        if err != nil {
            return err
        }
    
        return os.WriteFile(dst, bytesRead, 0644)
    }
    
    // copy file using io package
    func copyFileUsingIoPackage(src, dst string) (int64, error) {
            source, err := os.Open(src)
            if err != nil {
                    return 0, err
            }
            defer source.Close()
    
            destination, err := os.Create(dst)
            if err != nil {
                    return 0, err
            }
            defer destination.Close()
            
            nBytes, err := io.Copy(destination, source)
            
            return nBytes, err
    }
    
    func main() {
        src := "/tmp/file-src.txt"
        dst := "/tmp/file-dst.txt"
    
        n, err := copyFileUsingIoPackage(src, dst)
    
        if err != nil {
            panic(err)
        }
    
        fmt.Printf("Copied %d bytes", n)
        fmt.Println()
    
        err = copyFileUsingOsPackage(src, dst)
    
        if err != nil {
            panic(err)
        }
    }

    This example shows how to copy a file in Golang.

  • Filename without extension in Go

    package main
    
    import (
        "fmt"
        "path/filepath"
        "strings"
    )
    
    func main() {
        filePath := "/tmp/file.ext"
    
        // get file name with extension
        fileName := filepath.Base(filePath)
    
        // get file extension
        fileExt := filepath.Ext(filePath)
    
        // truncate file name extension
        fileNameWithoutExt := strings.TrimSuffix(fileName, fileExt)
    
        fmt.Println("File name without extension: " + fileNameWithoutExt)
    }
    
    // $ go run main.go
    // File name without extension: file

    Here is an example of how to get filename without extension in go.

  • Base64 encoding and decoding in Go

    package main
    
    import (
    	b64 "encoding/base64"
    	"fmt"
    )
    
    func main() {
    	str := "text123321!?$*&()'-=@~"
    
    	// Encode using the standard encoder
    	strEnc := b64.StdEncoding.EncodeToString([]byte(str))
    	fmt.Println(strEnc)
    
    	strDec, err := b64.StdEncoding.DecodeString(strEnc)
    
    	if err != nil {
    		panic(err)
    	}
    
    	fmt.Println(string(strDec))
    	fmt.Println()
    
    	// Encode using a URL-compatible base64 format
    	strEnc = b64.URLEncoding.EncodeToString([]byte(str))
    	fmt.Println(strEnc)
    
    	strDec, err = b64.URLEncoding.DecodeString(strEnc)
    
    	if err != nil {
    		panic(err)
    	}
    
    	fmt.Println(string(strDec))
    }
    
    // $ go run main.go
    // dGV4dDEyMzMyMSE/JComKCknLT1Afg==
    // text123321!?$*&()'-=@~
    
    // dGV4dDEyMzMyMSE_JComKCknLT1Afg==
    // text123321!?$*&()'-=@~

    Here is an example of base64 encoding and decoding. Go supports both standard and URL-compatible base64.

  • Parse URL in Go

    package main
    
    import (
    	"fmt"
    	"net"
    	"net/url"
    )
    
    func main() {
    	s := "mysql://user:pass@host.com:3306/path?key=value#fragment"
    
    	u, err := url.Parse(s)
    
    	if err != nil {
    		panic(err)
    	}
    
    	fmt.Println("Scheme: " + u.Scheme)
    
    	fmt.Println("Username: " + u.User.Username())
    	p, _ := u.User.Password()
    	fmt.Println("Password: " + p)
    
    	fmt.Println("Host with port: " + u.Host)
    
    	host, port, err := net.SplitHostPort(u.Host)
    
    	if err != nil {
    		panic(err)
    	}
    
    	fmt.Println("Host: " + host)
    	fmt.Println("Port: " + port)
    
    	fmt.Println("Path: " + u.Path)
    	fmt.Println("Fragment: " + u.Fragment)
    
    	fmt.Println("Raw query: " + u.RawQuery)
    
    	m, err := url.ParseQuery(u.RawQuery)
    
    	if err != nil {
    		panic(err)
    	}
    
    	fmt.Println("Value: " + m["key"][0])
    }
    
    // $ go run main.go 
    // Scheme: mysql
    // Username: user
    // Password: pass
    // Host with port: host.com:3306
    // Host: host.com
    // Port: 3306
    // Path: /path
    // Fragment: fragment
    // Raw query: key=value
    // Value: value

    Here is an example of how to parse URL, which includes a scheme, authentication info, host, port, path, query params, and query fragment.

  • Goroutines in Go

    package main
    
    import (
    	"fmt"
    	"time"
    )
    
    func print(from string) {
    	for i := 0; i < 3; i++ {
    		fmt.Println(from, ":", i)
    	}
    }
    
    func main() {
    	// Synchronous function call
    	print("synchronous call")
    
    	// Asynchronous function call
    	// To run this function in a goroutine, use go f(s)
    	// This new goroutine will execute concurrently with the calling main goroutine
    	go print("asynchronous call")
    
    	// Goroutine can also be execute as an anonymous function
    	go func(msg string) {
    		fmt.Println(msg)
    	}("asynchronous anonymous call")
    
    	// Two previous function calls are now running asynchronously in separate goroutines
    	// Wait for them to finish
    	time.Sleep(time.Second)
    	fmt.Println("done")
    }
    
    // $ go run main.go
    // synchronous call : 0
    // synchronous call : 1
    // synchronous call : 2
    // asynchronous anonymous call
    // asynchronous call : 0
    // asynchronous call : 1
    // asynchronous call : 2
    // done

    Here is an example of goroutines in Golang.

  • Buffered and unbuffered channels in Go

    package main
    
    import "fmt"
    
    func main() {
        // Create unbuffered channel
    	unbufferedChannel := make(chan string)
    
    	go func() {
            // Send a value into a channel using the channel<- syntax
    		unbufferedChannel <- "unbuffered channel"
    	}()
    
        // The <-channel syntax receives a value from the channel
    	fmt.Println(<-unbufferedChannel)
    
        // Create buffered channel with size 2
    	bufferedChannel := make(chan string, 2)
    
        // Send a value to a buffered channel. The operation in non blocking
    	bufferedChannel <- "buffered"
    	bufferedChannel <- "channel"
    
    	fmt.Println(<-bufferedChannel)
    	fmt.Println(<-bufferedChannel)
    }
    
    // go run main.go 
    // unbuffered channel
    // buffered
    // channel

    Channels serve as pipes for communication between concurrent goroutines. They allow one goroutine to send values and another goroutine to receive those values. By default, sending and receiving operations block until both the sender and receiver are ready. This feature enabled us to wait for the "unbuffered channel" message at the end of our program without needing any additional synchronization mechanisms. Buffered channels can hold a limited number of values without requiring an immediate receiver.

  • Environment variables in Go

    package main
    
    import (
    	"fmt"
    	"os"
    	"strings"
    )
    
    func main() {
    	os.Setenv("FOO", "1")
    	fmt.Println("FOO:", os.Getenv("FOO"))
    	fmt.Println("BAR:", os.Getenv("BAR"))
    
    	fmt.Println("----------------------")
    
    	for _, env := range os.Environ() {
    		pair := strings.SplitN(env, "=", 2)
    		fmt.Println(pair[0])
    	}
    }
    
    // FOO: 1
    // BAR: 
    // ----------------------
    // HOSTNAME
    // PWD
    // HOME
    // LANG
    // SHLVL
    // PATH
    // _
    // FOO

    Here's an example how you can manage environment variables. To assign a value to a key, utilize os.Setenv. Retrieve a value by key using os.Getenv, which will yield an empty string if the key isn't found. Use os.Environ to list all key/value pairs, returned as a string slice formatted as KEY=value. You can split these strings using strings.SplitN to separate keys and values.

  • Removing all files from a folder using PHP

    <?php 
    
    $folderPath = "/tmp/test-folder"; 
    
    // List of files inside the folder 
    $files = glob($folderPath.'/*'); 
     
    foreach($files as $file) { 
    	if(is_file($file)) 
    		// Delete the given file 
    		unlink($file); 
    } 
    
    echo "Files deleted";
    
    // php main.php
    // Files deleted

    PHP program to delete all files from a specified folder.

  • Example of recursion in golang

    package main
    
    import "fmt"
    
    func factorial(n int) int {
    	if n == 0 {
    		return 1
    	}
    
    	return n * factorial(n-1)
    }
    
    func main() {
    	fmt.Println(factorial(5))
    }
    
    // $ go run main.go 
    // 120

    Recursion in Go using the example of factorial calculation.

  • Example of closures in Golang

    package main
    
    import "fmt"
    
    // The function createCounter returns anonymous function defined within its body.
    // The returned function encapsulates the variable count, creating a closure.
    func createCounter() func() int {
    	count := 0
    
    	return func() int {
    		count++
    
    		return count
    	}
    }
    
    func main() {
        // We invoke createCounter, storing the result (a function) in counter variable.
        // This function captures and retains its own count value,
        // which updates with each subsequent invocation of createCounter.
    	counter := createCounter()
    
    	fmt.Println(counter())
    	fmt.Println(counter())
    	fmt.Println(counter())
    
    	newCounter := createCounter()
    	
        fmt.Println(newCounter())
    }
    
    // $ go run main.go 
    // 1
    // 2
    // 3
    // 1

    A simple example of using closures in Go.

  • Detect OS in Go

    package main
    
    import (
        "fmt"
        "runtime"
    )
    
    func main() {
        // The runtime.GOOS constant can be used to detect the OS at runtime,
        // since this constant is only set at runtime.
        os := runtime.GOOS
    
        switch os {
        case "windows":
            fmt.Println("Windows")
        case "darwin":
            fmt.Println("MacOS")
        case "linux":
            fmt.Println("Linux")
        default:
            fmt.Printf("%s.\n", os)
        }
    
        // The runtime.GOARCH constant can be used to determine the target architecture of a running program.
        fmt.Println(runtime.GOARCH)
    }
    
    // Output:
    // Linux
    // amd64

    GOOS constant to determine the operating system your Go program is running on. Here's an example of how to check the operating system in Go.

  • Create temporary file or directory in Go

    package main
    
    import (
        "fmt"
        "os"
        "path/filepath"
    )
    
    func checkErr(err error) {
        if err != nil {
            panic(err)
        }
    }
    
    func main() {
        // The simplest way to create a temporary file is to call os.CreateTemp.
        // It will create and open the file for reading and writing.
        // We used "" as the first argument, so os.CreateTemp will create a file in the default directory.
        tmpFile, err := os.CreateTemp("", "tmpfile")
        checkErr(err)
        defer os.Remove(tmpFile.Name())
    
        fmt.Println("Temp file name:", tmpFile.Name())
    
        // Write some data to the temporary file
        _, err = tmpFile.Write([]byte{1, 2, 3, 4, 5})
        checkErr(err)
    
        // If we intend to write a lot of temporary files, we may prefer to create a temporary directory.
        // The arguments to os.MkdirTemp are the same as for os.CreateTemp, but it returns the directory name rather than the opened file.
        dName, err := os.MkdirTemp("", "tmpdir")
        checkErr(err)
        defer os.RemoveAll(dName)
        
        fmt.Println("Temp directory name:", dName)
    
        fName := filepath.Join(dName, "testFile")
        err = os.WriteFile(fName, []byte{1, 2, 3, 4, 5}, 0666)
        checkErr(err)
        defer os.Remove(fName)
    }
    
    // Output:
    // Temp file name: /tmp/tmpfile3400905374
    // Temp directory name: /tmp/tmpdir2812568099

    During program execution, we often want to create data that is not needed after the program exits. Temporary files and directories are useful for this purpose because they do not pollute the file system over time.

  • Panic recovery in Go

    package main
    
    import "fmt"
    
    func main() {
        // Recover function must be called inside a deferred function.
        // When the enclosing function panics, defer is activated and the restore call inside it catches the panic.
        defer func() {
            if r := recover(); r != nil {
                fmt.Printf("recovered: %s\n", r)
            }
        }()
    
        panic("some fatal error")
        
        // This code won't run because of panic.
        // Basic operations stop during a panic and resume during a deferred close.
        fmt.Println("after panic")
    }

    Go allows you to recover from a panic with a built-in recover function. Recovery can prevent a panic from causing the program to abort and instead allow it to continue executing.

  • Writing JSON to a file in Python

    import json
    import os
    import uuid
    
    filename = str(uuid.uuid4()) # create random file name
    
    # JSON data to be written
    jsonDict ={
        "firstname" : "John",
        "lastname" : "Doe",
        "age" : 30,
        "phonenumber" : "9976770500"
    }
    
    # write JSON to file
    with open(filename, "w") as f:
        json.dump(jsonDict, f)
    
    # read JSON string from file
    f = open(filename, "r")
    print(f.read())
    f.close()
    os.remove(filename)
    
    # Output:
    # {"firstname": "John", "lastname": "Doe", "age": 30, "phonenumber": "9976770500"}

    You can write JSON to a file using the json.dump() function from the JSON module combined with file handling in Python. In thisexample, we open a file in writing mode. If the file doesn't exist, it will be created. The json.dump() function converts the Python dictionary into a JSON string, which is then saved in the file.

  • Read JSON file using Python

    import json
    import uuid
     
    jsonString = '{"firstname": "John", "lastname": "Doe"}'
    
    # Create random file name and write json to file
    filename = str(uuid.uuid4())
    
    with open(filename, "w") as f:
        f.write(jsonString)
    
    # Parse JSON string
    # Deserializes json string into dict
    print("Parse JSON string")
    jsonDict = json.loads(jsonString)
    
    # Iterating through the json
    for key, value in jsonDict.items():
        print(key, value)
    
    print()
    #----------------------------------------------------#
    
    print("Read JSON file")
    f = open (filename, "r")
     
    # Reading from file
    jsonDict = json.loads(f.read())
     
    # Iterating through the json
    for key, value in jsonDict.items():
        print(key, value)
     
    # Closing file
    f.close()
    
    # Output
    # Parse JSON string
    # firstname John
    # lastname Doe
    #
    # Read JSON file
    # firstname John
    # lastname Doe

    This exampleillustrates how to read from both a string and a JSON file. Initially, we have a JSON string stored in the variable 'jsonString'. We convert this JSON string into a Python dictionary using json.loads() method, which is then stored in the variable 'jsonDict'. Next, we read a JSON string stored in a file using json.loads(). To achieve this, we first convert the JSON file into a string using file handling, similar to the previous example. Then, we convert it into a string using the read() function. The subsequent steps mirror those followed earlier, utilizing the json.loads() method.

  • Read a file line by line in Python

    import os
    import uuid
    
    filename = str(uuid.uuid4()) # create random file name
    wLines = ["First line\n", "Second line\n", "Third line\n"]
    
    # writing lines to file
    f = open(filename, 'w')
    f.writelines(wLines)
    f.close()
    
    #--------------------------------------------------------#
    
    print("-----Read lines using 'readlines' method-----")
    f = open(filename, 'r')
    rLines = f.readlines()
    
    for lineNumber, line in enumerate(rLines, 1):
    	print("Line {}: {}".format(lineNumber, line.strip()))
    
    #--------------------------------------------------------#
    
    print("-----Read lines using 'readline' method-----")
    f = open(filename, 'r')
    lineNumber = 1
     
    while True:
        lineNumber += 1
     
        # Get next line from file
        line = f.readline()
     
        # if line is empty
        # end of file is reached
        if not line:
            break
        print("Line {}: {}".format(lineNumber, line.strip()))
     
    f.close()
    
    #--------------------------------------------------------#
    
    print("-----Read lines via file object iteration-----")
    f = open(filename, 'r')
    
    for lineNumber, line in enumerate(f, 1):
        print("Line {}: {}".format(lineNumber, line.strip()))
    
    #--------------------------------------------------------#
    
    print("-----Read lines via file contex manager-----")
    with open(filename, "r") as f:
        for lineNumber, line in enumerate(f, 1):
            print("Line {}: {}".format(lineNumber, line.strip()))
    
    os.remove(filename) # remove file
    
    # Output example:
    
    # Read lines using 'readlines' method
    # Line 1: First line
    # Line 2: Second line
    # Line 3: Third line

    Here's an example of reading from a file line by line in Python.

  • Context manager in Python

    # File management using context manager
    class FileManager():
        def __init__(self, filename, mode):
            self.filename = filename
            self.mode = mode
            self.file = None
      
        # The __enter__ method opens the file and returns a file object
        def __enter__(self):
            print('Open file: {}'.format(self.filename))
            self.file = open(self.filename, self.mode)
            return self.file
    
        # The __exit__ method takes care of closing the file on exiting the with block 
        def __exit__(self, etype, value, traceback):
            print('Close file: {}'.format(self.filename))
            self.file.close()
    
    # A FileManager object is created with test.txt as the filename and "write" mode
    # when __init__ method is executed
    with FileManager('test.txt', 'w') as f:
        f.write('First line\n')
        f.write('Second line\n')
    
    # The file is already closed thanks to the automatic call to the __exit__ method
    print('File closed: {}\n'.format(f.closed))
    
    with FileManager('test.txt', 'r') as f:
        for line in f:
            print(line.rstrip())
    
    # Output
    #Open file: test.txt
    #Close file: test.txt
    #File closed: True
    #
    #Open file: test.txt
    #First line
    #Second line
    #Close file: test.txt

    When creating context managers using classes, be sure to ensure that the class includes methods: __enter__() and __exit__(). The __enter__() method provides a resource to be managed, and __exit__() performs cleanup operations without returning any value. To understand the basic structure of building context managers using classes, let's look at a simple FileManager class for managing files.

  • Writing files in Go

    package main
    
    import (
        "bufio"
        "fmt"
        "os"
    )
    
    func checkErr(err error) {
        if err != nil {
            panic(err)
        }
    }
    
    func main() {
        content := "Some content"
        // write a string (or just bytes) into a file
        err := os.WriteFile("/tmp/dfile1", []byte(content), 0644)
        checkErr(err)
    
        // open a file for writing
        file, err := os.Create("/tmp/dfile2")
        checkErr(err)
        // defer a Close immediately after opening a file
        defer file.Close()
    
        bytesCount, err := file.Write([]byte(content))
        checkErr(err)
        fmt.Printf("wrote %d bytes\n", bytesCount)
    
        bytesCount, err = file.WriteString("Some other content\n")
        checkErr(err)
        fmt.Printf("wrote %d bytes\n", bytesCount)
        // flush writes to a stable storage (file system for example)
        file.Sync()
    
        // bufio provides buffered writers
        writer := bufio.NewWriter(file)
        bytesCount, err = writer.WriteString("Some othe buffered content\n")
        checkErr(err)
        fmt.Printf("wrote %d bytes\n", bytesCount)
        // ensure all buffered operations have been applied to the underlying writer
        writer.Flush()
    }

    Here are examples of writing data to files using Go.

  • Generate random hash or token in Go

    package main
    
    import (
    	"crypto/rand"
    	"crypto/sha256"
    	"encoding/hex"
    	"fmt"
    )
    
    func GenerateRandomHash(n int) (string, error) {
    	b := make([]byte, n)
    	_, err := rand.Read(b)
    
    	// Note that err == nil only if we read len(b) bytes.
    	if err != nil {
    		return "", err
    	}
    
    	hasher := sha256.New()
    	hasher.Write(b)
    	sha := hex.EncodeToString(hasher.Sum(nil))
    
    	return sha, nil
    }
    
    func main() {
    	hash, err := GenerateRandomHash(512)
    
    	if err != nil {
    		panic(err)
    	}
    
    	fmt.Println(hash)
    }
    
    // go run main.go 
    // 34c0fb393623843e56719b5d9d66385a55b4b4d3393187b7b1a76aee46c421c5

    Here is an example of randomly generating a hash or token in Go.

  • SHA256 hashes in Go

    package main
    
    import (
        "crypto/sha256"
        "fmt"
    )
    
    func main() {
        str := "some string to calculate hash"
        hash := sha256.New()
    
        hash.Write([]byte(str))
        sum := hash.Sum(nil) // the argument can be used to append to an existing byte slice
    
        fmt.Println(str)
        fmt.Printf("%x\n", sum)
    }
    
    // go run main.go 
    // some string to calculate hash
    // 7aad383b9ad516fa67057adc283ce2cf71858aff317a5e267adebfdbd5dda5fd

    SHA256 hashes are commonly used to generate short identifiers for binary or text data. This example shows how to calculate SHA256 hashes for string in Go.