本文整理匯總了Golang中encoding/json.Unmarshaler類的典型用法代碼示例。如果您正苦於以下問題:Golang Unmarshaler類的具體用法?Golang Unmarshaler怎麽用?Golang Unmarshaler使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了Unmarshaler類的3個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: unmarshalRequest
func unmarshalRequest(r *http.Request, req json.Unmarshaler, w http.ResponseWriter) bool {
ctype := r.Header.Get("Content-Type")
if ctype != "application/json" {
writeError(w, r, httptypes.NewHTTPError(http.StatusUnsupportedMediaType, fmt.Sprintf("Bad Content-Type %s, accept application/json", ctype)))
return false
}
b, err := ioutil.ReadAll(r.Body)
if err != nil {
writeError(w, r, httptypes.NewHTTPError(http.StatusBadRequest, err.Error()))
return false
}
if err := req.UnmarshalJSON(b); err != nil {
writeError(w, r, httptypes.NewHTTPError(http.StatusBadRequest, err.Error()))
return false
}
return true
}
示例2: unmarshalRequest
func unmarshalRequest(r *http.Request, req json.Unmarshaler, w http.ResponseWriter) bool {
ctype := r.Header.Get("Content-Type")
semicolonPosition := strings.Index(ctype, ";")
if semicolonPosition != -1 {
ctype = strings.TrimSpace(strings.ToLower(ctype[0:semicolonPosition]))
}
if ctype != "application/json" {
writeError(w, r, httptypes.NewHTTPError(http.StatusUnsupportedMediaType, fmt.Sprintf("Bad Content-Type %s, accept application/json", ctype)))
return false
}
b, err := ioutil.ReadAll(r.Body)
if err != nil {
writeError(w, r, httptypes.NewHTTPError(http.StatusBadRequest, err.Error()))
return false
}
if err := req.UnmarshalJSON(b); err != nil {
writeError(w, r, httptypes.NewHTTPError(http.StatusBadRequest, err.Error()))
return false
}
return true
}
示例3: testExpectedError
func testExpectedError(t *testing.T, expected error, xval string, ff json.Unmarshaler) {
buf := []byte(`{"X":` + xval + `}`)
err := ff.UnmarshalJSON(buf)
require.Error(t, err, "ff[%T] failed to Unmarshal", ff)
require.IsType(t, expected, err)
}