The service layer exists to separate business logic from technical concerns ( HTTP handling or database access ).

Examples of Business logic

  1. Certain URLs are not allowed { in my example }
  2. Input must be normalised
  3. Duplicate entities are not permitted
  4. Limits or permissions ( auth ) must be checked
api-go
	|
	|-------> internal 
								|------> dto
								|					|-----> websites.go
								|
								|------> handlers
								|					|-----> websites.go
								|
								|------> routes
								|					|-----> websites.go
								|
								|------> service
													|-----> websites.go					

internal/service/websites.go

1. Writing service layer

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