The service layer exists to separate business logic from technical concerns ( HTTP handling or database access ).
Examples of Business logic
api-go
|
|-------> internal
|------> dto
| |-----> websites.go
|
|------> handlers
| |-----> websites.go
|
|------> routes
| |-----> websites.go
|
|------> service
|-----> websites.go
WebsiteService is a service layer component. It groups :
This is similar to a class in other language like TS.
NewWebsiteService is a constructor function . Why this exists ?
New to create instances.What it does ?
WebsiteService struct.CreateWebsite is a method on WebsiteService
s *WebsiteService is called a method receiver.WebsiteServiceWebsiteService data and dependencies.CreateWebsite fn :
internal/service/websites.go
package service
import (
"errors"
"strings"
)
/*
WebsiteService is a service layer component.
It groups:
- Business logic related to websites
- (Later) dependencies like database, cache, logger, etc.
This is similar to a "class" in other languages.
*/
type WebsiteService struct {
}
/*p
NewWebsiteService is a constructor function.
Why this exists:
- Go does not have class constructors
- We use functions prefixed with `New` to create instances
- This allows controlled creation and future dependency injection
What it does:
1. Creates a WebsiteService struct
2. Returns a pointer to it
*/
func NewWebsiteService() *WebsiteService{ // Returns a pointer to created instance of WebsiteService object
return &WebsiteService{} // creates an instance of WebsiteService object
}
/*
CreateWebsite is a method on WebsiteService.
`s *WebsiteService` is called a method receiver.
It means:
- This function belongs to WebsiteService
- It can access WebsiteService's data and dependencies
The function:
- Accepts a raw URL
- Applies business rules
- Returns either:
- a normalized URL (success)
- an error (failure)
*/
func (s *WebsiteService ) CreateWebsite (url string) ( string, error ) {
normalisedUrl := strings.TrimSpace(url)
if strings.Contains(normalisedUrl,"localhost") {
return "",errors.New("Localhost URLs are not allowed")
}
// Duplicacy check
return normalisedUrl,nil
}
Why Dependency Injection is used here