Created
April 2, 2022 10:47
-
-
Save kben19/b41243358b82718fc54ce8025d0f0250 to your computer and use it in GitHub Desktop.
Wrapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ( | |
"net/http" | |
"time" | |
) | |
func main() { | |
httpClient := &http.Client{Timeout: time.Duration(3) * time.Second} | |
cacheService := NewCache() | |
service := NewService(httpClient, cacheService) | |
// call service with wrapper attached | |
stock, err := service.GetProductStock(1) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import "net/http" | |
type Service struct { | |
httpClient *http.Client | |
} | |
func (service *Service) GetProductStock(id int) (int, error) { | |
// Requesting Stock from Product service | |
} | |
// --- WRAPPER --- // | |
type CacheItf interface { | |
Get(key string) (string, error) | |
Set(key string, value string) error | |
} | |
// Includes any services that are used in wrapper executions | |
// without changing the original structure | |
type ServiceWrapper struct { | |
service *Service | |
cache CacheItf | |
} | |
func NewService(httpClient *http.Client, cache CacheItf) *ServiceWrapper { | |
service := &Service{ httpClient } | |
return &ServiceWrapper { | |
service: service, | |
cache: cache, | |
} | |
} | |
// Implement any instructions like caching, validation, authorization or logging in here | |
// without disrupting the original flow or structure. | |
func (wrapper *ServiceWrapper) GetProductStock(id int) (int, error) { | |
// Do Pre-function executions | |
defer func () { | |
// Do Post-function executions | |
} () | |
return wrapper.service.GetProductStock(id) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment