Deprecated: Array and string offset access syntax with curly braces is deprecated in /customers/1/2/4/mrwaggel.be/httpd.www/admin/kernel/helpers/text.class.php on line 171 Notice: Trying to access array offset on value of type null in /customers/1/2/4/mrwaggel.be/httpd.www/admin/kernel/db/db_posts.class.php on line 390 Notice: Trying to access array offset on value of type null in /customers/1/2/4/mrwaggel.be/httpd.www/admin/kernel/db/db_pages.class.php on line 337 Notice: Trying to access array offset on value of type null in /customers/1/2/4/mrwaggel.be/httpd.www/admin/kernel/db/db_comments.class.php on line 283 Deprecated: Function get_magic_quotes_runtime() is deprecated in /customers/1/2/4/mrwaggel.be/httpd.www/admin/boot/rules/4-remove_magic.bit on line 18 Deprecated: Function get_magic_quotes_gpc() is deprecated in /customers/1/2/4/mrwaggel.be/httpd.www/admin/boot/rules/4-remove_magic.bit on line 23 - goMr.Waggel's blog

Golang human readable byte sizes

31 March, 2020

Here is a function that prints out byte sizes, like the return from len() function, into human readable units.

Function and example

package main

import (
	"fmt"
	"strconv"
)

const (
	TB = 1000000000000
	GB = 1000000000
	MB = 1000000
	KB = 1000
)

func lenReadable(length int, decimals int) (out string) {
	var unit string
	var i int
	var remainder int

	// Get whole number, and the remainder for decimals
	if length > TB {
		unit = "TB"
		i = length / TB
		remainder = length - (i * TB)
	} else if length > GB {
		unit = "GB"
		i = length / GB
		remainder = length - (i * GB)
	} else if length > MB {
		unit = "MB"
		i = length / MB
		remainder = length - (i * MB)
	} else if length > KB {
		unit = "KB"
		i = length / KB
		remainder = length - (i * KB)
	} else {
		return strconv.Itoa(length) + " B"
	}

	if decimals == 0 {
		return strconv.Itoa(i) + " " + unit
	}

	// This is to calculate missing leading zeroes
	width := 0
	if remainder > GB {
		width = 12
	} else if remainder > MB {
		width = 9
	} else if remainder > KB {
		width = 6
	} else {
		width = 3
	}

	// Insert missing leading zeroes
	remainderString := strconv.Itoa(remainder)
	for iter := len(remainderString); iter < width; iter++ {
		remainderString = "0" + remainderString
	}
	if decimals > len(remainderString) {
		decimals = len(remainderString)
	}

	return fmt.Sprintf("%d.%s %s", i, remainderString[:decimals], unit)
}

func main() {
	test := []int{425005, 8741208, 114448910, 557891, 557,
		114710, 8933578, 5849684981, 12033687, 742289, 678007439}

	for _, v := range test {
		fmt.Println(v, "\t = ", lenReadable(v, 2))
	}
}

Output

425005          =  425.00 KB
8741208         =  8.74 MB
114448910       =  114.44 MB
557891          =  557.89 KB
557             =  557 B
114710          =  114.71 KB
8933578         =  8.93 MB
5849684981      =  5.84 GB
12033687        =  12.03 MB
742289          =  742.28 KB
678007439       =  678.00 MB

Golang serving resume able file downloads with net/http

30 March, 2020

Here is a fully commented example golang function on how to serve and transmit files to clients with the go net/http package. It supports the "Accept-Ranges" header, which allows for downloads to be paused or interrupted and resumed later on. This is very useful for clients who don't have stable connections to download larger files. However this function does not support Multipart downloads, if you wish to have that functionality check this function in the net/http source code for implementation.

This function is written with the following sources RFC 7233 section 3.1MDN Range Requests and Content Range.

Linux Mint Xapp missing library package fix

12 March, 2020

Errors

Some errors which I encountered during building 'systray' (github.com/getlantern/systray)

Package xapp was not found in the pkg-config search path.
Perhaps you should add the directory containing `xapp.pc'
to the PKG_CONFIG_PATH environment variable
running gcc failed: exit status 1
/usr/bin/ld: cannot find -lxapp
collect2: error: ld returned 1 exit status

Solution

Simply install the missing package with

sudo apt-get install libxapp-dev 

Golang reflect if initialized struct has member method or fields

12 April, 2018

In Go it is possible to check if any pointer to an initialized struct has a given method or field. The use of this is to make sure that you can call a given method, or access a given field without receiving a runtime panic.

Serialize structures in Golang

04 April, 2018

In this blogpost I'll show you one of the many ways to serialize structures in Go.

Golang Beego implementing and using CAPTCHA

19 January, 2017

In this small tutorial I'll show you how to use CAPTCHA validation inside your application. We won't be using the builtin CAPTCHA of Beego but instead use another package of GitHub user dchest, and his package captcha.

Golang Beego how to use sessions

18 January, 2017

The official documentation on using sessions in Beego is besides being outdated quite unclear. I'll show you how to use sessions inside your Beego application.

Golang string to int

02 January, 2017

The built in 'strconv' package contains a function named 'Atoi' (ASCII to integer). Which is just a wrapper for the 'ParseInt' function.

Golang creating a worker thread pool using maps

24 July, 2016

This example will show you how to create a worker thread that waits for jobs and working them one by one. We use maps to create a list where we add jobs too. This tutorial will process strings and create bcrypt hashes of it, for simulating purposes.

Golang mgo append to a nested array in a document

24 May, 2016

Small tutorial on how to add/push/append a new element to an array/list inside a document, based on my previous post.

Golang mgo retrieve nested structured arrays

24 May, 2016

Small tutorial on how to retrieve nested arrays/lists from a 'mgo.Find()' result.

Golang transfer a file over a TCP socket

21 May, 2016

In this tutorial I'll demonstrate how to send a file in Go over a TCP connection using a server that sends the file and a client that receives it, I'll try to go into detail as much as possible.

You can download the source code here.

Comments and remarks are more than welcome.

Golang mgo findAndModify auto increment id tutorial

17 May, 2016

Here is a brief explanation for the 'findAndModify()' equivalent for mgo. Instead of 'findAndModify()' we will use 'mgo.Find().Apply()'. I will demonstrate how to use auto incremented ids instead of random unique generated IDs for documents, since mongdb does not have a native way of doing this (because MongoDB is not a relational database).

It work's like this, we create a collection, insert a document in that collection that contains the last generated ID. Every time we call 'findAndModify()', mongoDB will increment the value and we get that new value back, which you should use to insert a new document with.

Generate CRC32 hash of a file in Golang turorial

17 April, 2016

In previous posts I showed how to make a MD5 hash and a SHA1 hash of a file, generating a CRC checksum on a file is however a bit more complicated since it uses a polynomial table. I'll explain everything in depth.

Generate SHA1 hash of a file in Golang example

08 April, 2016

This function is based on my previous post but adapted for the SHA1 algorithm.

Generate MD5 hash of a file in Golang

07 April, 2016

Why generate a MD5 hash of a file?

You may have noticed before on some websites where you download a file, there is some strange string of text around the download link, named "checksum", for example "md5 checksum: dcdfb1413d7fa48c3cab920c0448f236". Now this may look like a bunch of random characters to you but don't be fooled, it's a one-way mathematical hash that correspondents to the file you want to download.

Home