构建简易博客 / API 服务

1. 路由设计

使用 net/http 或第三方路由框架设计 RESTful 路由,如:

  • GET /posts 获取文章列表
  • GET /posts/{id} 获取单篇文章
  • POST /posts 创建文章

2. 数据模型定义

定义文章结构体:

type Post struct {
    ID      int    `json:"id"`
    Title   string `json:"title"`
    Content string `json:"content"`
}

`

3. 简单处理函数示例

func getPosts(w http.ResponseWriter, r *http.Request) {
    posts := []Post{
        {ID: 1, Title: "Hello Go", Content: "Welcome to Go programming"},
    }
    json.NewEncoder(w).Encode(posts)
}

4. 启动服务器

http.HandleFunc("/posts", getPosts)
http.ListenAndServe(":8080", nil)

5. 扩展功能

  • 路由分组
  • 请求验证
  • 日志记录
  • 热加载工具(如 air)

通过以上步骤可快速搭建基础博客或 API 服务。