惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
Visual Studio Blog
罗磊的独立博客
宝玉的分享
宝玉的分享
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
V
V2EX
酷 壳 – CoolShell
酷 壳 – CoolShell
T
Tailwind CSS Blog
博客园_首页
量子位
月光博客
月光博客
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 司徒正美
人人都是产品经理
人人都是产品经理
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
爱范儿
爱范儿
S
SegmentFault 最新的问题
雷峰网
雷峰网
小众软件
小众软件
博客园 - 聂微东
美团技术团队
Apple Machine Learning Research
Apple Machine Learning Research
WordPress大学
WordPress大学
Jina AI
Jina AI
Hugging Face - Blog
Hugging Face - Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Structuring a Go API Like Laravel (Controller, Service, R...
Ahmed Raza I · 2026-05-01 · via DEV Community
Cover image for Structuring a Go API Like Laravel (Controller, Service, Repository)

Ahmed Raza Idrisi

If you're coming from Laravel, one thing feels missing in Go:

👉 Structure

By default, Go gives you freedom—but no clear architecture.

So in this post, we’ll structure a Go API like Laravel:

  • Controller → Handle request
  • Service → Business logic
  • Repository → Database

🧠 Why Structure Matters

Without structure:

  • Code becomes messy quickly
  • Hard to scale
  • Difficult to debug

With structure:

  • Clean separation of concerns
  • Easier testing
  • Production-ready codebase

📁 Folder Structure

project/
 ├── main.go
 ├── controller/
 ├── service/
 ├── repository/
 ├── model/

Enter fullscreen mode Exit fullscreen mode


🧱 Model (model/user.go)

```go id="6pn1u5"
package model

type User struct {
ID int json:"id"
Name string json:"name"
}




---

## 🗄️ Repository Layer

Handles database queries



```go id="aq1u8u"
package repository

import (
    "database/sql"
    "yourapp/model"
)

type UserRepository struct {
    DB *sql.DB
}

func (r *UserRepository) GetAll() ([]model.User, error) {
    rows, err := r.DB.Query("SELECT id, name FROM users")
    if err != nil {
        return nil, err
    }
    defer rows.Close()

    var users []model.User

    for rows.Next() {
        var user model.User
        rows.Scan(&user.ID, &user.Name)
        users = append(users, user)
    }

    return users, nil
}

Enter fullscreen mode Exit fullscreen mode


⚙️ Service Layer

Handles business logic

```go id="qf1kmz"
package service

import (
"yourapp/model"
"yourapp/repository"
)

type UserService struct {
Repo *repository.UserRepository
}

func (s *UserService) GetUsers() ([]model.User, error) {
return s.Repo.GetAll()
}




---

## 🌐 Controller Layer

Handles HTTP requests



```go id="n8t1rn"
package controller

import (
    "encoding/json"
    "net/http"
    "yourapp/service"
)

type UserController struct {
    Service *service.UserService
}

func (c *UserController) GetUsers(w http.ResponseWriter, r *http.Request) {
    users, err := c.Service.GetUsers()
    if err != nil {
        http.Error(w, err.Error(), 500)
        return
    }

    json.NewEncoder(w).Encode(users)
}

Enter fullscreen mode Exit fullscreen mode


🚀 main.go (Wire Everything)

```go id="b4r8f2"
package main

import (
"database/sql"
"log"
"net/http"

_ "github.com/lib/pq"

"yourapp/controller"
"yourapp/repository"
"yourapp/service"

Enter fullscreen mode Exit fullscreen mode

)

func main() {
db, _ := sql.Open("postgres", "your_connection_string")

repo := &repository.UserRepository{DB: db}
service := &service.UserService{Repo: repo}
controller := &controller.UserController{Service: service}

http.HandleFunc("/users", controller.GetUsers)

log.Println("Server running on :8080")
http.ListenAndServe(":8080", nil)

Enter fullscreen mode Exit fullscreen mode

}




---

## 🔥 What You Achieved

* Clean architecture like Laravel
* Separation of concerns
* Scalable Go backend structure

---

## 🧭 When to Use This

Use this structure when:

* Building real APIs
* Working in teams
* Scaling projects

---

## 💬 Final Thought

Go doesn’t force structure…

👉 But professionals create one.

If you combine Go performance with Laravel-style architecture, you get the best of both worlds.

---

## 🚀 Coming Next

👉 Add middleware (logging, auth)
👉 Add validation layer
👉 Dockerize Go + PostgreSQL

---

#golang #backend #architecture #programming #webdev

Enter fullscreen mode Exit fullscreen mode