CodeBlanks Logo Icon CodeBlanks

Service skeleton

Design the microservice skeleton and layers.

Project: a product service

In this project you will build a small microservice that lists and adds products. The code is split into three layers:

  • handler: reads the HTTP request and writes a JSON response.
  • service: applies business rules (e.g. price can't be negative).
  • repository: stores the data (database or memory).

Each layer uses the one below through an interface, so tests don't need a real database.

Folder layout

A common layout:

urun-servisi/
  cmd/server/main.go     // wires dependencies, starts the server
  internal/urun/model.go // the Urun type
  internal/urun/repo.go  // Repository interface and implementation
  internal/urun/service.go
  internal/urun/handler.go
  go.mod

Packages under internal/ can't be imported from outside the module, which keeps service code private.

Practice Model and interface

Define type Urun struct { ID int; Ad string; Fiyat float64 } and type Repo interface { Ekle(u Urun) error; Liste() []Urun }. In main, print Urun{1, "Kalem", 12.5} with %+v.

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

type Urun struct {
    ID    int
    Ad    string
    Fiyat float64
}

type Repo interface {
    Ekle(u Urun) error
    Liste() []Urun
}

func main() {
    fmt.Printf("%+v\n", Urun{1, "Kalem", 12.5})
}

Expected output

{ID:1 Ad:Kalem Fiyat:12.5}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which layer does the rule "price can't be negative" belong to?

  • repository
  • main
  • service Correct answer
  • handler

Explanation: Business rules live in the service layer; the handler only knows HTTP and the repository only storage.

2 Private packages

Question
urun-servisi/
  ____/urun/service.go
Answer
urun-servisi/
  internal/urun/service.go

Explanation: The internal folder allows its packages to be imported only from the same module.

3 Layer and role

Term Meaning
handler HTTP and JSON
service Business rules
repository Data storage
cmd/server Wires everything

All lessons in Advanced