Skip to content
hakk
  • Home
  • Blog
  • Docs
  • DSA
  • Snippets

Golang

  • Pick a random element in an array or slice in Go (Golang) 2023-01-01

    Using the ‘math/rand’ package of golang to generate a pseudo-random number between [x,n). The bracket at the end means that n is exclusive and x could be any number 0 or greater. The package contains a function Intn which can be utilized to pick a random element in an array or slice of int or string. This example also uses the time package to seed the generator. Otherwise the it would be seeded with a 1 and the generated numbers wouldn’t be random.

  • A quick HTTP file server example in Go 2022-11-04

    Basic example to serve directory.

    package main
    
    import (
        "flag"
        "fmt"
        "log"
        "net/http"
    )
    
    func main() {
        // Simple static webserver:
        pathPtr := flag.String("d", ".", "Directory path to serve")
        portPtr := flag.String("p", "8080", "Port to listen on")
        interfacePtr := flag.String("i", "", "Interface to listen on (default all)")
        flag.Parse()
        log.Printf("Serving %s on %s:%s", *pathPtr, *interfacePtr, *portPtr)
        err := http.ListenAndServe(fmt.Sprintf("%s:%s", *interfacePtr, *portPtr), http.FileServer(http.Dir(*pathPtr)))
        if err != nil {
            log.Fatal(err)
        }
    }
    

    Example with ability to set custom headers

    package main
    
    import (
        "flag"
        "fmt"
        "log"
        "net/http"
    )
    
    func main() {
        // Simple static webserver:
        pathPtr := flag.String("d", ".", "Directory path to serve")
        portPtr := flag.String("p", "8080", "Port to listen on")
        interfacePtr := flag.String("i", "", "Interface to listen on (default all)")
        flag.Parse()
        log.Printf("Serving %s on %s:%s", *pathPtr, *interfacePtr, *portPtr)
        fs := http.FileServer(http.Dir(*pathPtr))
        err := http.ListenAndServe(fmt.Sprintf("%s:%s", *interfacePtr, *portPtr), customHeaders(fs))
        if err != nil {
            log.Fatal(err)
        }
    }
    
    func customHeaders(fs http.Handler) http.HandlerFunc {
        // found at https://stackoverflow.com/a/65905091
        return func(w http.ResponseWriter, r *http.Request) {
            // add headers etc here
            // return if you do not want the FileServer handle a specific request
            w.Header().Set("Cache-Control", "no-cache")
            w.Header().Set("x-server", "hello, world!")
            fs.ServeHTTP(w, r)
        }
    }
    

  • HTML templating in Go 2022-11-04

    Within the Go Standard library HTML package there’s a template package which enables generating HTML page from a rich templating engine with the output safe against code injection. This means there is no need to worry about XSS attacks as Go parses the HTML template and escapes all inputs before displaying it to the browser.

    Let’s take a look at a simple example. This example will use a couple of structs to store data about some people and then display that data in an HTML table.

  • How to list files in a directory using Go [2023] 2022-10-25

    In Go there are a couple of options to list the files of a directory using the standard library. In this article you will find a list of three different methods.

    Note: Be aware that ioutil.ReadDir is deprecated since Go 1.16. Instead os.ReadDir should be used (shown in this article).

    os.ReadDir

    os.ReadDir is included in the standard library in the os package. Check out the documentation for more information. It’s a drop in replacement from ioutil.ReadDir.

  • Golang Convert from Int to Hex 2021-01-10

    Converting from an Integer to hex is easy in Golang. Since a hex is really just an Integer literal, you can ask the fmt package for a string representation of that integer, using fmt.Sprintf(), and the %x or %X format.

    package main
    
    import (
    	"fmt"
    )
    
    func main() {
    	for i := 1; i < 20; i++ {
    		h := fmt.Sprintf("0x%x", i)
    		fmt.Println(h)
    	}
    }
    

    Golang Play

    Output:

    0x1
    0x2
    0x3
    0x4
    0x5
    0x6
    0x7
    0x8
    0x9
    0xa
    0xb
    0xc
    0xd
    0xe
    0xf
    0x10
    0x11
    0x12
    0x13
    

    Convert back to int

    package main
    
    import (
    	"fmt"
    	"strconv"
    )
    	
    var hex = []string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "10", "11", "12", "13"}
    
    func main() {
    	for _, h := range hex {
    		i, _ := strconv.ParseInt(h, 16, 64)
    		fmt.Println(i)
    	}
    }
    

    Output:

  • Golang Split Host Port to Separate Variables 2021-01-10

    Getting just the host or port from the “host:port” form is easy using the SplitHostPort function from the net package.

    Below are some example uses of the function. As seen below, IPv6 addresses in hostport must be enclosed in square brackets.

    package main
    
    import (
    	"fmt"
    	"net"
    )
    
    func main() {
    	// IPv4
    	host, port, err := net.SplitHostPort("172.217.7.14:443")
    	if err != nil {
    		fmt.Println(err)
    	}
    	fmt.Println(host, port)
    	
    	// IPv6
    	host, port, err = net.SplitHostPort("[2607:f8b0:4006:800::200e]:443")
    	if err != nil {
    		fmt.Println(err)
    	}
    	fmt.Println(host, port)
    	
    	// Domain
    	host, port, err = net.SplitHostPort("example.com:80")
    	if err != nil {
    		fmt.Println(err)
    	}
    	fmt.Println(host, port)
    }
    

    Output:

  • Golang Convert File Size to a human friendly format 2020-06-09

    Get file size in human-readable units like kilobytes (KB), Megabytes (MB) or GigaBytes (GB)

    1 KilloByte == 1024 Bytes

    1 Megabyte == 1024*1024 Bytes

    1 GigaByte == 102410241024 Bytes

    package main
    
    import (
    	"fmt"
    	"log"
    	"math"
    	"os"
    	"strconv"
    )
    
    var (
    	suffixes [5]string
    )
    
    func Round(val float64, roundOn float64, places int ) (newVal float64) {
    	var round float64
    	pow := math.Pow(10, float64(places))
    	digit := pow * val
    	_, div := math.Modf(digit)
    	if div >= roundOn {
    		round = math.Ceil(digit)
    	} else {
    		round = math.Floor(digit)
    	}
    	newVal = round / pow
    	return
    }
    
    func HumanFileSize(size float64) string {
    	fmt.Println(size)
    	suffixes[0] = "B"
    	suffixes[1] = "KB"
    	suffixes[2] = "MB"
    	suffixes[3] = "GB"
    	suffixes[4] = "TB"
    	
    	base := math.Log(size)/math.Log(1024)
    	getSize := Round(math.Pow(1024, base - math.Floor(base)), .5, 2)
    	fmt.Println(int(math.Floor(base)))
    	getSuffix := suffixes[int(math.Floor(base))]
    	return strconv.FormatFloat(getSize, 'f', -1, 64)+" "+string(getSuffix)
    }
    
    func main() {
    	files, err := os.ReadDir(".")
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	for _, file := range files {
    		fs := float64( file.Size() )
    		fmt.Println(file.Name(), HumanFileSize(fs), file.ModTime())
    	}
    }
    

  • Golang Listing Directory Contents and Sorting by File Modified Time 2020-06-09

    In this example we will be listing the contents of a directory in go and sorting by date.

    To get the list of files we will use the os.ReadDir function from the os package. This function returns a slice sorted by file name which contains elements of os.FileInfo type which will enable us to get the last modified time.

    To sort the files we will use the modification time with the sort package along with the After and Before functions from the time package.

  • Golang Listing Directory Contents and Sorting by File Name 2020-06-09

    Listing the contents of a directory in go and sorting by filename.

    To get the list of file we will use the ReadDir function from the os package.

    To sort the files we will use the sort package to arrange the filenames alphabetically ascending or descending.

    package main
    
    import (
    	"fmt"
    	"io/fs"
    	"log"
    	"os"
    	"sort"
    )
    
    func checkErr(err error) {
    	if err != nil {
    		log.Fatal(err)
    	}
    }
    
    // this is the default sort order of golang ReadDir
    func SortFileNameAscend(files []fs.DirEntry) {
    	sort.Slice(files, func(i, j int) bool {
    		return files[i].Name() < files[j].Name()
    	})
    }
    
    func SortFileNameDescend(files []fs.DirEntry) {
    	sort.Slice(files, func(i, j int) bool {
    		return files[i].Name() > files[j].Name()
    	})
    }
    
    func printFiles(files []fs.DirEntry) {
    	for _, file := range files {
    		fileInfo, err := file.Info()
    		checkErr(err)
    		fmt.Println(file.Name(), fileInfo.Size(), fileInfo.ModTime())
    	}
    }
    
    func main() {
    	files, err := os.ReadDir(".")
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	//SortFileNameAscend(files)
    	printFiles(files)
    
    	fmt.Println("\n-----------------------------------\n")
    
    	SortFileNameDescend(files)
    
    	printFiles(files)
    }
    

  • Golang Listing Directory Contents and Sorting by File Size 2020-06-09

    Listing the contents of a directory in go and sorting by file size.

    To get the list of file we will use the ReadDir function from os package.

    To sort the files we will use the sort package and compare the file sizes to arrange them in ascending or descending order.

    package main
    
    import (
    	"fmt"
    	"io/ioutil"
    	"log"
    	"os"
    	"sort"
    )
    
    func SortFileSizeAscend(files []os.FileInfo) {
    	sort.Slice(files, func(i, j int) bool {
    		return files[i].Size() < files[j].Size()
    	})
    }
    
    func SortFileSizeDescend(files []os.FileInfo) {
    	sort.Slice(files, func(i, j int) bool {
    		return files[i].Size() > files[j].Size()
    	})
    }
    
    func printFiles(files []os.FileInfo) {
    	for _, file := range files {
    		fmt.Println(file.Name(), file.Size(), file.ModTime())
    	}
    }
    
    func main() {
    	files, err := ioutil.ReadDir(".")
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	SortFileSizeAscend(files)
    
    	printFiles(files)
    
    	fmt.Println("\n-----------------------------------\n")
    
    	SortFileSizeDescend(files)
    
    	printFiles(files)
    }
    

Recent posts
  • Understanding the ss Command: A Modern Alternative to netstat
  • Understanding HTTP from Scratch with Python Sockets
  • When Environment Variables Mysteriously Reset...
  • How to Generate a 32-byte Key for AES Encryption
  • Streamlining Deployment: Installing Docker, Gitea, Gitea Act Runner, and Nginx on Ubuntu
© 2025 hakk
  • Home
  • Blog
  • Docs
  • DSA
  • Snippets