哈囉!今天我們要來練習建立 Go 的 API,昨天我們已經有先介紹了 Web API 的使用方式,如果在操作上忘記了,都可以再回去看看~
那我們就開始吧!
在 Go 裡面如果要建立 API 可以有兩種方式:
net/http
記得要新增以下的套件,才能順利跑喔!
import (
"encoding/json"
"net/http"
)
而我們今天先選最簡單的方式來建立,這樣在實作過程中,也能比較清楚的知道流程和 API 的呼叫方式。
首先,我們需要先定義 API endpoint(URL):
GET /hello
:回傳 “Hello World !“GET /users
:回傳使用者列表POST /users
:建立新使用者我們可以先建立 user struct 和一個預設的 user 列表:
// user struct
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
// user 列表
var users = []User{
{ID: 1, Name: "Alice"},
{ID: 2, Name: "Bob"},
}
然後根據上面的定義,需要寫 3 個 function 來處理「 請求 」、「 回傳 」、「寫入 」。
在那之前,我們先介紹一些常用的用法解釋:
http.ResponseWriter
:設定 header、狀態碼、回應內容,並把資料回傳回去。http.HandleFunc
:綁定 URL 和對應的處理 function。http.MethodGet
:內建的 HTTP Method 常數,判斷 request 的種類。
http.MethodGet
。http.MethodPost
。http.MethodPut
。http.MethodDelete
。以上都是 Go 的標準格式,可以記一下!
再來新增這 3 個 function:
/hello
: // GET /hello
func getHello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello, World !")
}
/users
:// GET /users
func getUsers(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json") // 跟瀏覽器說 這是 JSON
json.NewEncoder(w).Encode(users) // 轉成 JSON 輸出
}
/users
:// POST /users
func addUser(w http.ResponseWriter, r *http.Request) {
var newUser User // 宣告一變數 newUser,型態是 User(指的是前面 user struct)
err := json.NewDecoder(r.Body).Decode(&newUser) // 把客戶端送來的 JSON 轉換成 Go 的 struct(這段我們之前有學過,還記得嗎?)
if err != nil { // 檢查 JSON 格式是否正確
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
newUser.ID = len(users) + 1 // 新增使用者 ID
users = append(users, newUser) // 新增使用者到列表
w.Header().Set("Content-Type", "application/json") // 設定回應的格式是 JSON 資料
json.NewEncoder(w).Encode(newUser) // 把新增的 newUser 轉成 JSON,然後回傳
}
最後,把所有的路由設定寫在主程式 main
:
// 主要設定路由的地方
func main() {
http.HandleFunc("/hello", getHello)
http.HandleFunc("/users", func(w http.ResponseWriter, r *http.Request) {
qq
if r.Method == http.MethodGet { // 判斷 HTTP Mothods 是哪一種,而帶入不同 fuction
getUsers(w, r)
} else if r.Method == http.MethodPost {
addUser(w, r)
} else {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
})
fmt.Println("Server running at http://localhost:8080")
http.ListenAndServe(":8080", nil) // 啟動伺服器
}
完整程式 main.go
檔案就是:
package main
import (
"encoding/json"
"fmt"
"net/http"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
var users = []User{
{ID: 1, Name: "Alice"},
{ID: 2, Name: "Bob"},
}
// GET /hello
func getHello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello, World !")
}
// GET /users
func getUsers(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(users)
}
// POST /users
func addUser(w http.ResponseWriter, r *http.Request) {
var newUser User
err := json.NewDecoder(r.Body).Decode(&newUser)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
newUser.ID = len(users) + 1
users = append(users, newUser)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(newUser)
}
func main() {
http.HandleFunc("/hello", getHello)
http.HandleFunc("/users", func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
getUsers(w, r)
} else if r.Method == http.MethodPost {
addUser(w, r)
} else {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
})
fmt.Println("Server running at http://localhost:8080")
http.ListenAndServe(":8080", nil)
}
那我們就來啟動伺服器,然後測試剛剛寫的 API 有沒有成功。
在 main.go
路徑下輸入指令:
// 啟動伺服器
go run main.go
啟動之後,會看到:
Server running at http://localhost:8080
接著,我們來測試看看 API ,可以使用終端機 或 Postman 測試~
這邊使用 終端機 來示範。
GET /hello
輸入:
curl http://localhost:8080/hello
回傳:
GET /users
輸入:
curl http://localhost:8080/users
回傳:
POST /users
輸入:
curl -X POST http://localhost:8080/users -d '{"name":"Charlie"}' -H "Content-Type: application/json"
回傳:
以上就是 Go API 的簡單實作~
明天會介紹 Go 的框架 Gin,Gin 框架會讓建立 API 變得更容易!那我們就明天見啦!