常见项目目录结构

Go 没有强制规定项目必须怎么分目录。

但后端项目通常会按职责拆分。

一、简单项目结构

小项目可以很简单:

hello/
├── go.mod
└── main.go

如果只是学习语法、写小工具,这样就够了。

二、后端服务常见结构

shop/
├── go.mod
├── go.sum
├── cmd/
│   └── api/
│       └── main.go
├── internal/
│   ├── config/
│   │   └── config.go
│   ├── user/
│   │   ├── handler.go
│   │   ├── service.go
│   │   └── repository.go
│   └── order/
│       ├── handler.go
│       ├── service.go
│       └── repository.go
└── README.md

说明:

目录作用
cmd/api程序入口
internal项目内部代码,外部模块不能导入
internal/config配置读取
internal/user用户业务
internal/order订单业务

三、为什么用 internal

internal 是 Go 工具链支持的特殊目录。

放在 internal 里的包,只能被父目录及其子目录导入,外部项目不能导入。

这适合放项目内部实现,避免被其他项目误用。

四、按业务分层

例如用户模块:

internal/user/
├── handler.go      # HTTP 入参和响应
├── service.go      # 业务逻辑
├── repository.go   # 数据访问
└── model.go        # 业务模型

一次请求大概这样流动:

HTTP 请求

handler

service

repository

database

初学阶段可以先用内存数据或 map 模拟数据库。

五、入口 main.go

cmd/api/main.go

package main

import (
	"fmt"
	"net/http"
)

func main() {
	mux := http.NewServeMux()

	mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "ok")
	})

	http.ListenAndServe(":8080", mux)
}

运行:

go run ./cmd/api

六、目录不要过度设计

初学项目不要一上来拆很多层。

可以按项目规模演进:

项目规模建议
练习代码main.go
小工具main.go + 少量包
后端服务cmd/ + internal/
多服务仓库多个 cmd/xxx + shared internal 包

目录结构是为代码服务的,不是越复杂越专业。