本项目是一个基于 Go 和 Gin 的本地 Mock API 服务。通过配置 api.json
文件,可以快速生成模拟的后端接口,返回自定义的 mock 数据,适用于前端开发和接口联调。
- 通过配置
api.json
文件灵活定义路由、请求方法和 mock 数据文件 - 支持 GET、POST、PUT、DELETE 等常用 HTTP 方法
- mock 数据支持多种占位符,自动生成随机数据
- 支持跨域请求(CORS)
go_api/
├── api.json # 路由与mock数据配置
├── main.go # 服务主程序
├── mock/ # mock数据目录
│ └── user/
│ ├── addUser.txt
│ ├── getUser.txt
│ └── list.txt
├── go.mod
└── go.sum
- Go 1.24 及以上
- Gin
- mockJson(本地依赖,需在
go.mod
中通过replace
指向本地包)
安装依赖:
go mod tidy
api.json
示例:
[
{
"route": "/user",
"method": "get",
"path": "./mock/user/list.txt"
},
{
"route": "/user/:id",
"method": "get",
"path": "./mock/user/getUser.txt"
},
{
"route": "/user",
"method": "post",
"path": "./mock/user/addUser.txt"
}
]
route
:接口路由,支持 RESTful 风格method
:HTTP 方法(get、post、put、delete)path
:mock 数据文件路径
mock/user/list.txt
示例:
{
"code": 0,
"msg": "success",
"rows": [
{
"id": "@Id|8",
"name": "@Name",
"age": "@Number|18~35",
"avatar": "@Image|80X80",
"address": "@Address"
},
4,
15
]
}
常用 mock 语法:
@Id|8
:生成 8 位 ID@Name
:随机姓名@Number|18~35
:18~35 之间的随机数@Image|80X80
:生成 80x80 图片链接@Address
:随机地址
go run main.go
默认监听端口:9527
如:
GET http://localhost:9527/user
GET http://localhost:9527/user/123
POST http://localhost:9527/user
This project is a local mock API server based on Go and Gin. By configuring the api.json
file, you can quickly generate simulated backend APIs and return custom mock data, which is ideal for frontend development and API integration testing.
- Flexible route, method, and mock data configuration via
api.json
- Supports GET, POST, PUT, DELETE HTTP methods
- Mock data supports various placeholders for random data generation
- CORS enabled by default
go_api/
├── api.json # Route and mock data configuration
├── main.go # Main server program
├── mock/ # Mock data directory
│ └── user/
│ ├── addUser.txt
│ ├── getUser.txt
│ └── list.txt
├── go.mod
└── go.sum
- Go 1.24 or above
- Gin
- mockJson (local dependency, referenced via
replace
ingo.mod
)
Install dependencies:
go mod tidy
Example:
[
{
"route": "/user",
"method": "get",
"path": "./mock/user/list.txt"
},
{
"route": "/user/:id",
"method": "get",
"path": "./mock/user/getUser.txt"
},
{
"route": "/user",
"method": "post",
"path": "./mock/user/addUser.txt"
}
]
route
: API route, supports RESTful stylemethod
: HTTP method (get, post, put, delete)path
: Path to mock data file
mock/user/list.txt
example:
{
"code": 0,
"msg": "success",
"rows": [
{
"id": "@Id|8",
"name": "@Name",
"age": "@Number|18~35",
"avatar": "@Image|80X80",
"address": "@Address"
},
4,
15
]
}
Common mock syntax:
@Id|8
: Generate 8-digit ID@Name
: Random name@Number|18~35
: Random number between 18 and 35@Image|80X80
: Generate 80x80 image URL@Address
: Random address
go run main.go
Default port: 9527
For example:
GET http://localhost:9527/user
GET http://localhost:9527/user/123
POST http://localhost:9527/user