Go - Study Note 1

发布时间 2023-09-19 21:44:25作者: ZhangZhihuiAAA

In general, for most server applications that would be built out there—most would be written with the struct approach. One of the main reasons would be thinking of how to pass vital components that are required to process the URL path, such as database connections or queue system connections, or cache system connections. We can keep it global, but that introduces various sets of issues where it makes it hard to unit testing on a specific struct.
An example of how this would look like for the definition of the struct could be something like this:

type DB interface {
    GetAllArtifacts() ([]string, error)
}

type Queue interface {
    SubmitJob() error
}

type Cache interface {
    Store(item string) error
}

type HandleViaStruct struct {
    queue Queue
    db    DB
    cache Cache
}

We can define a bunch of interfaces which we can then dump it into our HandleViaStruct struct. We would then require to initialize the various other structs that would implement said functionalities defined by the various interface before we are able to finally run the struct.