這是一個建立於
的文章,其中的資訊可能已經有所發展或是發生改變。
前言
restful開發時,對象轉json,json轉對象是非常頻繁的操作,怎麼樣才能少些重複的代碼呢,以這個為目的開啟這篇文章
所有代碼放在github上
簡化資料結構
每次需要返回的資料有code,msg,data這些欄位,每個類型都加這些欄位太繁複了,這裡有interface的方式,去代替任意類型,然後使用的時候data欄位與其他類型任意的組合
package modeltype Resp struct { Code string `json:"code"` Msg string `json:"msg,omitempty"` Data interface{} `json:"data,omitempty"`}type User struct { Username string `json:"username"` Password string `json:"password,omitempty"`}
json和http請求結合起來
對golang內建的json處理封裝,使之可以直接從http請求中讀出對象,把對象以json格式輸出到響應中
package toolsimport ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http")// MarshalJson 把對象以json格式放到response中func MarshalJson(w http.ResponseWriter, v interface{}) error { data, err := json.Marshal(v) if err != nil { return err } fmt.Fprint(w, string(data)) return nil}// UnMarshalJson 從request中取出對象func UnMarshalJson(req *http.Request, v interface{}) error { result, err := ioutil.ReadAll(req.Body) if err != nil { return err } json.Unmarshal([]byte(bytes.NewBuffer(result).String()), v) return nil}
調用
經過以上的處理,調用變得相當容易,不需要再做更多的重複編碼,代碼可讀性上大大提高
func UserLoginndler(w http.ResponseWriter, r *http.Request) { user := &model.User{} tools.UnMarshalJson(r, user) resp := &model.Resp{Code: "1001", Msg: "帳號或者密碼錯誤"} if user.Username == "sweetop" && user.Password == "123456" { resp = &model.Resp{Code: "0", Msg: "success"} } tools.MarshalJson(w, resp)}
func UserListHandler(w http.ResponseWriter, r *http.Request) { resp := &model.Resp{Code: "0", Msg: "success"} users := make([]model.User, 0) resp.Data = append(users, model.User{Username: "sweetop"}) tools.MarshalJson(w, resp)}