/ software

Notes on my Go HTTP server

I'm currently building a Single Page App in Angular (TypeScript) which is backed by a bundle of services provided via HTTP. Rather typical I'd say.

It's a good opportunity to brush up on my Go skills, which are rather basic so far. So to make sure I won't forget the things I learned today, some journaling is in order.

To make sure that internal data structures are properly initialized before use, Go code typically employs the Factory pattern. That way the struct can be private (ie lowerCaseInitial), and the object is generated by a function which can make sure that it's consistent before being passed to any consumer:

type thatStructTho struct {
    privateField int
}

func NewStruct() *thatStructTho {
    s := new(thatStructTho)
    // init s
    return s
}

The problem is that this struct can only be assigned to immediately created variables (foo := NewStruct()).

Therefore, also define a public interface (UpperCaseInitial) and use that (and use better names. much better names):

type thatStructTho struct {
    privateField int
}

type ThatStructInterface interface {
    DoThis()
    DoThat(foo int) bool
}

func NewStruct() ThatStructInterface {
    // use the struct internally
    s := new(thatStructTho)
    // init s
    return s
}

// implement ThatStructInterface for thatStructTho:
func (s *thatStructTho) DoThis() {
    ...
}

Now thatStructTho is private, always created through NewStruct() (and therefore can be initialized always), and it's possible to assign NewStruct()'s result to variables and fields of type ThatStructInterface.

Patrick Georgi

Patrick Georgi

Von der Stadt aufs Land. Freund des retro computings und des inneren Exils. Die Gedanken sind frei. Dieses Recht findet seine Schranken in den Vorschriften der allgemeinen Gesetze.

Read More