Archives for October, 2017

Reading from standard input with Go

published on October 30, 2017.

Last year I started learning Go, then I stopped, and now I don’t remember anything what I learned.

Going to try it a bit different this time, by writing down what I do, learn, experiment.

As I don’t have a specific thing I want to build with Go, I’m just going to do simple scripts and examples, to get to know Go’s language specification and built-ins as much as possible.

Hopefully, there won’t be too much mistakes in my code samples. I’ve set up a golearn repository just for this, so feel free to create issues/PRs telling me where I went wrong.

Setting up the Go environment

I installed Go to the location that the official docs recommend — /usr/local, and I created the “Go workspace” in ~/projects/gocode and then I put my code under ~/projects/gocode/src/

I do find it kinda weird that everything lives in one “workspace”. But, whatever.

As for the editor, I’m using Visual Studio Code with the Go plugin.

I first tried using the vim-go plugin, but I couldn’t make it work in a custom runtimepath. I didn’t want to brick the Vim setup I have for my day-to-day work, so that’s why I tried a custom location.

Next I tried the Gogland from JetBrains, but when I ran it, my laptop sounded like a jet when the fans kicked off, so… yeah.

Then I tried Visual Studio Code, installed the Go plugin and I was pleasantly surprised when the editor figured out I was missing some Go programs like gofmt, golint, etc., and offered me to install them all. Great user experience for newcomers to Go.

About those docs…

After printing out the required “Hello, world!” to the terminal, I set out to figure out how to read in stuff from the standard input.

I would really love to say I figured it out all on my own how to do it, just by reading the official documentation, but I couldn’t. Maybe I don’t know how to use Go’s docs, maybe I’m spoiled by PHP’s excellent documentation, but after an hour or so flipping through the docs, I ended up Googling the solution.

From the documentation, I couldn’t figure out does the solution lie within the io, or the bufio package. Maybe both? I’ll have to tinker with them some more to understand the difference between the two.

From all the answers I found on the internet about this, I went with what seems the simplest way of reading from standard input: using a bufio.Scanner. Again, I’ll have to poke more around this, to see all the different ways I can accomplish this and compare the solutions.

The first “program”

The goal is to read whatever the user types in to standard input, line by line.

First, I have a slice of strings. Not an array, but a slice. I believe the main difference is that an array has a set size, while a slice’s size can change during execution.

// Inputs holds the inputs read in from stdin
type Inputs []string

I’m not yet 100% sure does this create a new type “Inputs” which is composed of a slice of strings, or is it just a slice of strings named “Inputs”? I think it’s the former, because I can use it as a return type-hint in a function.

Then in the main() I get a new scanner for the standard input:

scanner := bufio.NewScanner(os.Stdin)

It returns a pointer to the Scanner, so I pass it as such to my ReadInput function:

is := ReadInput(*scanner)

The ReadInput function takes a scanner of bufio.Scanner type and returns Inputs:

func ReadInput(scanner bufio.Scanner) Inputs

I declare two variables, one to hold the string read in from stdin, the other to “collect” all the input strings:

	var t string
	var i Inputs

Then I create an endless for loop, from which I break out when the user enters a new line only. In this loop the Scanner scans the stdin, and gets the text from it. If the text entered is not empty, I append it to the Inputs, as it is a slice of strings:

	for true {
		fmt.Print("Add a new todo [empty to stop reading]: ")
		t = scanner.Text()

		if err := scanner.Err(); err != nil {
			fmt.Println("Error reading from input: ", err)

		// scanner.Text() strips new lines
		// so in case of just a new line
		// it's actually an empty string
		if t == "" {

		i = append(i, t)

and finally I return the Inputs from the ReadInput function:

    return i

Back in main I do a “sanity” check by printing out the number of lines read in, and printing them out one by one:

	fmt.Printf("Got %d inputs from stdin:\n", len(is))

	for _, v := range is {

When executed, it looks something like this:

$ go run readstdin.go 
Hello, world!
Add a new todo [empty to stop reading]: Learn go
Add a new todo [empty to stop reading]: Write blog posts
Add a new todo [empty to stop reading]: 
Got 2 inputs from stdin:
Learn go
Write blog posts

The entire file is available here.

With this I learned a bit about Go’s types, creating functions, using the for loop, pointers, slices vs. arrays, and, of course, reading stuff from the standard input.

Happy hackin’!

P.S.: It feels good to have a beginners mind, again, about something.

I think I understand bounded contexts

published on October 24, 2017.

Earlier this year I started reading the DDD book by Eric Evans. Together with the Eventsourcery videos from Shawn McCool, the first three chapters of the book were… easy to understand, even. Lots of “A-ha!” and “Oh!” moments, followed by “That makes perfect sense.” statements, and a couple of excited “I knew that!”-ones. Then I got to the chapter with the bounded contexts. I read the first few pages, thought about them… Then read them again, and thought some more. Then I put the book back on the shelf for a few months.

Last night I read it again, and then…


A bounded context is a point of view.

A bounded context defines how a section of a business sees, thinks, talks about a subject that is important to that section of the business. And we represent that business subject with a model. That same business subject can be present in different sections of a business, but every section views it differently. To some extent, at least. That is the reason why the context of a model is important — we need to know how to model a subject for that specific business section.

And we need to put boundaries on those models — we must prevent the mixing of, what might seem same, models between these contexts.

A book is a book, right?

Depends on who you ask.

If you ask a publisher, a book has a title, a writer, a cost, a price, and a category. If you ask a seller, a book has a title, a writer, a cost, a price, and a category. They talk about the same things, right?

For a publisher a book has a working title, and a published title. For a seller a book has a title. For a publisher a book has a writer, who needs to be payed. For a seller a book has a writer, which is just a name on the front cover of the book. For a publisher the cost of a book includes the cost of the writer, the editor, the designer, the printing, the binding. For a seller the cost of a book includes the buying price, maybe some discounts from the publisher on the quantity purchased, the paychecks of the store clerks, bills for running the store, taxes… For a publisher the price includes the producing cost plus the profit they want to make. For a seller the price includes the buying cost plus the profit they want to make, and maybe some discounts they want to give to buyers. For a publisher the category can be fiction and non-fiction books. For a seller the category can be epic fantasy, sci-fi, horror, thriller, programming, design, recipe books…

See where am I going with this?

Depending on the point of view, depending on the context, the same book can mean two different things for two different business sections in the business of selling books. Even if at first we might think there is no difference, once we start talking to the business people, these differences will pop-up.

We should also respect the boundaries between these two contexts, so that we always know about what cost or what price we are talking about. Otherwise, the seller would quickly run out of business if they’d sell books at the publisher’s price.

This is just a model

Of course, there is more to bounded contexts, models, DDD, etc., than what I wrote here. More to read, more to learn, more to think, more to write.

Happy hackin’!

Creating datetimes from a format with a timezone

published on October 16, 2017.

I wouldn’t be writing this blog post, if I’d read all the “fineprints” in the PHP manual. Alas, here we are.

The DateTime and DateTimeImmutable classes have a createFromFormat method. As you can probably guess from it’s name, it creates a datetime object from a datetime string formatted in the specified format. Something like this:


$dtString = '2017-10-16 07:50:00';
$format = 'Y-m-d H:i:s';

$dt = \DateTimeImmutable::createFromFormat($format, $dtString);


gives an immutable datetime object:

DateTimeImmutable Object (
    [date] => 2017-10-16 07:50:00.000000
    [timezone_type] => 3
    [timezone] => Europe/Belgrade

Nothing wrong with that. The timezone is Europe/Belgrade, as we didn’t provide the third parameter to the createFromFormat method, which is the optional timezone, and in this case PHP defaulted to the server’s timezone. Business as usual.

If we tell it to use a specific timezone, it’ll use that one instead of the server’s timezone:


$dtString = '2017-10-16 07:50:00';
$format = 'Y-m-d H:i:s';
$timezone = new \DateTimeZone('America/New_York');

$dt = \DateTimeImmutable::createFromFormat($format, $dtString, $timezone);


and an expected result of:

DateTimeImmutable Object (
    [date] => 2017-10-16 07:50:00.000000
    [timezone_type] => 3
    [timezone] => America/New_York

Again, business as usual, because we told PHP in what timezone the datetime string is, America/New_York.

A format with a timezone offset

When the format has a timezone offset though, that’s… the part I skipped in the manual:


$dtString = '2017-10-16T07:50:00+00:00';
$format = 'Y-m-d\TH:i:sP';
$timezone = new \DateTimeZone('America/New_York');

$dt = \DateTimeImmutable::createFromFormat($format, $dtString, $timezone);


and a result of:

DateTimeImmutable Object (
    [date] => 2017-10-16 07:50:00.000000
    [timezone_type] => 1
    [timezone] => +00:00

Errr… Not really what I wanted, but okay. I guess.

The createFromFormat method ignores the provided timezone (or the server’s timezone if there’s none provided), if the datetime string and it’s format have a timezone offset.

It’s noted in the manual, my bad for not reading carefully, but this still caught me by surprise.

Not being aware of this can cause some hard to track down bugs in applications. While the DateTime objects are being created without an error, they are being created with a different timezone_type from what I originally expected and can potentially lead to a loss of information as the timezone identifier can’t be retrieved from the timezone offset.

Happy hackin’!

Robert Basic

Robert Basic

Software engineer, consultant, open source contributor.

Let's work together!

If you require outsourcing or consulting help on your projects, I'm available!

Robert Basic © 2008 — 2018
Get the feed