Go | 套件實現 RESTful API
💬 簡介
在現代開發中,呼叫第三方 API 是常見需求。
若將 API 呼叫邏輯零散寫在主程式中,不僅難以維護,也不利於測試與重用。
本篇將實作一個簡單的 RESTful API 客戶端套件,示範如何模組化整合 HTTP 操作,建立清晰、可擴充的應用結構。

圖片來源:Gophers
📦 專案與套件結構
我們將設計一個套件 apiclient
,統一封裝 API 呼叫邏輯:
目錄架構如下:
1 2 3 4 5
| /myapp/ |- main.go |- apiclient/ |- apiclient.go |- types.go
|
apiclient.go
:負責發送 GET 請求並解析結果
types.go
:定義 API 回傳資料的資料結構(struct)
範例將使用 JSONPlaceholder 公開 API 作為模擬資料來源。
📄 apiclient/types.go
1 2 3 4 5 6 7 8
| package apiclient
type Post struct { UserID int `json:"userId"` ID int `json:"id"` Title string `json:"title"` Body string `json:"body"` }
|
- 使用
json
標籤對應 API 回傳欄位。
- 後續將以此型別接收與解析 JSON 資料。
🔧 apiclient/apiclient.go
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| package apiclient
import ( "encoding/json" "fmt" "net/http" "time" )
const baseURL = "https://jsonplaceholder.typicode.com"
var client = &http.Client{ Timeout: 5 * time.Second, }
func GetPostByID(id int) (*Post, error) { url := fmt.Sprintf("%s/posts/%d", baseURL, id)
req, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { return nil, err }
resp, err := client.Do(req) if err != nil { return nil, err } defer resp.Body.Close()
if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("API 回傳錯誤狀態碼:%d", resp.StatusCode) }
var post Post if err := json.NewDecoder(resp.Body).Decode(&post); err != nil { return nil, err }
return &post, nil }
|
- 封裝
http.Client
,集中管理逾時與錯誤處理。
- 提供
GetPostByID
封裝 API 呼叫邏輯,讓主程式只需關心業務資料。
🚀 main.go:實際使用套件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| package main
import ( "fmt" "myapp/apiclient" )
func main() { post, err := apiclient.GetPostByID(1) if err != nil { fmt.Println("API 呼叫失敗:", err) return }
fmt.Println("標題:", post.Title) fmt.Println("內容:", post.Body) }
|
只要一行 apiclient.GetPostByID
,即可取出資料並印出標題與內容。
🧪 模組化優勢與可擴充性
技術優點 |
說明 |
責任清晰 |
API 呼叫邏輯與主程式分離 |
易於測試 |
可對 apiclient 套件撰寫獨立單元測試 |
支援擴充 |
未來可加上 POST/PUT/Delete 等功能 |
改善維護性 |
API 變更僅需修改一處邏輯 |
可重用性 |
套件可跨專案使用 |
📝套件化的好處在於「高內聚、低耦合」,後續若改連接其他 API,只需修改 apiclient
而不影響主程式邏輯。
🎯 總結
藉由封裝 HTTP 操作邏輯為獨立套件,我們實現了一個簡潔、可讀的 API 客戶端範例:
- ✅ 使用清晰目錄與模組化設計
- ✅ 將資料結構與邏輯分離管理
- ✅ 提供乾淨明確的公開函式介面
未來你可以將此技術延伸應用於 GitHub API、Line Notify、Slack Webhook 等實際開發場景。
最後建議回顧一下 Go | 菜鳥教學 目錄,了解其章節內容。
註:以上參考了
Go