Skip to content

Instantly share code, notes, and snippets.

@marcoslhc
Created October 3, 2023 16:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcoslhc/e64fba010a123bfd0dd9cfcc368a1fa0 to your computer and use it in GitHub Desktop.
Save marcoslhc/e64fba010a123bfd0dd9cfcc368a1fa0 to your computer and use it in GitHub Desktop.
Golang Service Provision Pattern
package main
// Service Provision Pattern
// taken from https://github.com/andygrunwald/go-jira/blob/main/cloud/jira.go
// test this code in
// https://go.dev/play/p/-BUVpELm5u8
import (
"log"
"os"
)
// Concrete type that provides access
// to the shared client
// It will be cast to the actual service
// providing some kind of struct polymorphism
type service struct {
client *Client
}
// Client that will aggregate the services
type Client struct {
// common service that will provide
// a shared instance of the client
common service
// dependencies
// this are private to hide them
// from other instances
logger *log.Logger
http *log.Logger
// services instantiated with the
// common instance
ServiceA *ServiceA
ServiceB *ServiceB
}
func (c *Client) Log(origin string, message string) {
oldPrefix := c.logger.Prefix()
c.logger.SetPrefix(origin + " ")
defer c.logger.SetPrefix(oldPrefix)
c.logger.Printf("%s", message)
}
func (c *Client) Do(url string) {
c.http.Printf("%s", url)
}
type ServiceA service
type ServiceB service
func (s *ServiceA) LogA(msg string) {
s.client.Log("A", msg)
}
func (s *ServiceB) LogB(msg string) {
s.client.Log("B", msg)
}
func (s *ServiceA) CallAPI() {
s.client.Do("http://example.com/api/v1/")
}
func NewClient() *Client {
c := &Client{
logger: log.New(os.Stdout, "", log.LstdFlags),
http: log.New(os.Stdout, "HTTP ", log.LstdFlags),
}
c.ServiceA = (*ServiceA)(&c.common)
c.ServiceB = (*ServiceB)(&c.common)
c.common.client = c
return c
}
func main() {
c := NewClient()
c.ServiceA.LogA("hello")
c.ServiceB.LogB("hello")
c.ServiceA.CallAPI()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment