Go Restful JSON 是一種提供 RESTful Web 服務的框架,目標是將 JSON 直接映射到 Go 結構體上,使得 Go 程序可以更加方便地調用 RESTful Web 服務,同時提供了強大的路由和中間件功能。
package main import ( "log" "net/http" "github.com/gorilla/mux" ) type Person struct { ID string `json:"id,omitempty"` Name string `json:"name,omitempty"` } var people []Person func GetPersonEndpoint(w http.ResponseWriter, req *http.Request) { params := mux.Vars(req) for _, item := range people { if item.ID == params["id"] { json.NewEncoder(w).Encode(item) return } } json.NewEncoder(w).Encode(&Person{}) } func GetPeopleEndpoint(w http.ResponseWriter, req *http.Request) { json.NewEncoder(w).Encode(people) } func CreatePersonEndpoint(w http.ResponseWriter, req *http.Request) { params := mux.Vars(req) var person Person _ = json.NewDecoder(req.Body).Decode(&person) person.ID = params["id"] people = append(people, person) json.NewEncoder(w).Encode(people) } func DeletePersonEndpoint(w http.ResponseWriter, req *http.Request) { params := mux.Vars(req) for index, item := range people { if item.ID == params["id"] { people = append(people[:index], people[index+1:]...) break } } json.NewEncoder(w).Encode(people) } func main() { router := mux.NewRouter() people = append(people, Person{ID: "1", Name: "Alice"}) people = append(people, Person{ID: "2", Name: "Bob"}) router.HandleFunc("/people", GetPeopleEndpoint).Methods("GET") router.HandleFunc("/people/{id}", GetPersonEndpoint).Methods("GET") router.HandleFunc("/people/{id}", CreatePersonEndpoint).Methods("POST") router.HandleFunc("/people/{id}", DeletePersonEndpoint).Methods("DELETE") log.Fatal(http.ListenAndServe(":8080", router)) }
我們可以看到,使用 Go Restful JSON 編寫 RESTful Web 服務非常方便,只需要定義好路由和處理函數(shù),處理函數(shù)中直接調用 Go 結構體即可將 JSON 數(shù)據(jù)轉換為 Go 結構體。此外,Go Restful JSON 還提供了強大的路由和中間件功能,可以讓我們更加方便地實現(xiàn)各種需求。