Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 39 ยท Getting Started

Structuring a Gin Project

Organize a Gin application with cmd and internal folders, handler structs, services and repositories, dependency injection through interfaces, and a routes function you can test.

Gin does not impose a project layout. That freedom is useful for a ten-line demo and dangerous for a real service: if every handler opens its own database connection and reads global variables, nothing can be tested and every change touches everything. This lesson shows a layout that scales from a small API to a large one, and the one idea that makes it work: handlers receive their dependencies instead of reaching for them.

You should already be comfortable with your first Gin app and configuration.

A layout that works

TEXT
myapp/
  go.mod
  cmd/
    api/
      main.go          // wiring only: load config, build dependencies, run
  internal/
    config/            // Config struct and loader
    http/
      router.go        // builds the *gin.Engine and registers routes
      user_handler.go  // gin handlers for users
      middleware.go    // custom middleware
    user/
      service.go       // business rules
      repository.go    // database access (interface + implementation)
      model.go         // the User type
  migrations/          // SQL files
  web/
    templates/
    static/

Why these folders?

  • cmd/api/main.go contains no logic. It reads configuration, creates a database connection, builds the service and handler, and starts the server. Putting main under cmd/ leaves room for a second binary later, such as cmd/worker.
  • internal/ is special in Go: packages inside it can only be imported by code in the same module. Your application code is not an importable library, which is exactly what you want.
  • handler / service / repository layers. Handlers translate HTTP into function calls and back (parse input, call the service, choose a status code). Services contain rules ("an email must be unique"). Repositories talk to the database. Each layer only knows the one below it.
flowchart TD
    A["HTTP request"] --> B["Handler<br/>(Gin: parse, respond)"]
    B --> C["Service<br/>(business rules)"]
    C --> D["Repository<br/>(SQL / GORM)"]
    D --> E[("Database")]

Dependencies point downward. Nothing below a handler imports Gin.

For a small project, start flatter: a main.go, a handlers.go and a store.go in one package is fine. Split when a file becomes hard to scan, not before.

Handlers as methods on a struct

The key technique is a struct that holds dependencies, with handlers as methods:

Go
type UserHandler struct {
	users user.Service
}

func NewUserHandler(s user.Service) *UserHandler {
	return &UserHandler{users: s}
}

func (h *UserHandler) Get(c *gin.Context) {
	u, err := h.users.Find(c.Request.Context(), c.Param("id"))
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
		return
	}
	c.JSON(http.StatusOK, u)
}

h.Get is a method value with the type func(*gin.Context), so it can be passed straight to r.GET("/users/:id", h.Get). Compare this with a global var db *gorm.DB used inside a plain function: the struct version has no hidden inputs, so you can pass a fake service in a test.

Notice that the handler uses c.Request.Context() rather than the *gin.Context itself when calling the service. The standard context.Context carries cancellation and deadlines; keeping the service free of Gin types means it can be reused from a CLI or a background job.

Interfaces at the boundary

Define small interfaces where you consume a dependency. The handler needs "something that can find a user", not "the real database":

Go Stand-in: a handler with an injected store

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

In production UserStore is implemented by a type that queries MySQL or PostgreSQL; in tests it is the in-memory map above. The handler cannot tell the difference, and that is the point.

A router function you can reuse

Create the engine in one function that takes the handlers. main calls it to serve, and tests call it to exercise routes without a network:

Go
func NewRouter(users *UserHandler) *gin.Engine {
	r := gin.New()
	r.Use(gin.Recovery())

	api := r.Group("/api/v1")
	{
		api.GET("/users/:id", users.Get)
		api.POST("/users", users.Create)
	}
	r.GET("/healthz", func(c *gin.Context) { c.Status(http.StatusNoContent) })
	return r
}

And main.go becomes pure wiring:

Go
func main() {
	cfg := config.Load()

	db, err := gorm.Open(mysql.Open(cfg.DatabaseURL), &gorm.Config{})
	if err != nil {
		log.Fatal(err)
	}

	repo := user.NewRepository(db)
	svc := user.NewService(repo)
	router := NewRouter(NewUserHandler(svc))

	log.Fatal(router.Run(cfg.Addr))
}

Everything flows in one direction, and main is the only place that knows which concrete types are used. This style is called dependency injection; in Go you do it by hand with constructors, no framework needed.

Registering routes by feature

As the API grows, one giant router function becomes unreadable. Let each feature register its own routes onto a group:

Go Stand-in: features register their own routes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

In Gin the same pattern uses *gin.RouterGroup: func (h *UserHandler) Register(rg *gin.RouterGroup). Route groups explains groups in detail.

Where to put what

  • Request and response shapes. Keep the structs you bind from JSON (and their validation tags) next to the handler. Keep the domain model (User) separate if it carries database tags. Returning your database model straight from a handler leaks columns such as password_hash. See binding JSON and forms.
  • Errors. Define sentinel errors in the service (ErrNotFound, ErrEmailTaken) and map them to HTTP statuses in the handler, so the service stays HTTP-agnostic.
  • Config. One struct, loaded once in main, passed down. Avoid reading environment variables deep inside handlers.
  • Global state. Avoid it. A package-level var db makes tests order-dependent and hides what a function needs.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a package under internal/ guarantee?

    The Go toolchain forbids importing internal packages from outside the parent module, which keeps application code private.
  2. 2. Why make handlers methods on a struct that holds dependencies?

    A struct carries a service or store, so tests can build the handler with a fake. Method values like h.Get still match func(*gin.Context).
  3. 3. Where should the interface for a dependency be defined?

    Go interfaces are satisfied implicitly, so the consumer can declare exactly the methods it needs.
  4. 4. Which layer should know about *gin.Context?

    Handlers translate HTTP to function calls. Keeping Gin out of services and repositories makes them reusable and easy to test.

Summary

  • Start simple; split into cmd/, internal/, handler, service and repository layers as the project grows.
  • main only wires dependencies; it contains no business logic.
  • Make handlers methods on a struct and inject interfaces so tests can supply fakes.
  • Build the engine in a NewRouter function and let features register their own route groups.
  • Keep HTTP types out of services, map domain errors to status codes in handlers, and avoid package-level globals.

Next: Routes and HTTP Methods starts the routing chapter.