前言
要使用Go建立一個RESTful的Web Server非常地簡單, 只要使用內建的模組net/http就能輕易達成首先, 匯入相關套件
package main
import (
"encoding/json"
"net/http"
)
添加兩個路由"/", "/users", 以及實作兩個handler來處理對應的請求
func handler(w http.ResponseWriter, request *http.Request) {
w.Write([]byte("Hello world."))
}
func usersHandler(w http.ResponseWriter, request *http.Request) {
data := make(map[string]interface{})
data["users"] = []interface{}{
map[string]interface{}{
"name": "andy",
"pwd": "123456",
},
}
jsonByte, _ := json.Marshal(data)
w.Header().Set("Content-Type", "application/json")
w.Write(jsonByte)
}
func main() {
http.HandleFunc("/", handler)
http.HandleFunc("/users", usersHandler)
...
給定要聽的port
http.ListenAndServe(":3000", nil)
測試 localhost:3000
測試localhost:3000/users
完整程式碼
package main
import (
"encoding/json"
"net/http"
)
func handler(w http.ResponseWriter, request *http.Request) {
w.Write([]byte("Hello world."))
}
func usersHandler(w http.ResponseWriter, request *http.Request) {
data := make(map[string]interface{})
data["users"] = []interface{}{
map[string]interface{}{
"name": "andy",
"pwd": "123456",
},
}
jsonByte, _ := json.Marshal(data)
w.Header().Set("Content-Type", "application/json")
w.Write(jsonByte)
}
func main() {
http.HandleFunc("/", handler)
http.HandleFunc("/users", usersHandler)
http.ListenAndServe(":3000", nil)
}
留言
張貼留言