Golang初學者,我試圖編寫一個通用函數來服務ReST請求。我傳遞一個函數來創建一個新的資源(結構),其上實現了一個接口,因爲我也會調用結構體上的方法。在解碼JSON時,記錄類型顯示正確的(結構)類型,但JSON解碼器似乎只識別它無法解碼的接口。Golang JSON解碼器無法識別類型
package main
import (
"encoding/json"
"github.com/julienschmidt/httprouter"
"log"
"net/http"
"strings"
)
// general resource interface
type resource interface {
// check semantics and return an array of errors or nil if no error found
check() []string
// update the resource in backend
update() error
}
// specific resource named "anchor"
type anchor struct {
ID string `json:"id"`
Name string `json:"name"`
}
func newAnchor() resource {
return anchor{}
}
func (a anchor) check() []string {
return nil
}
func (a anchor) update() error {
return nil
}
// generic function to create (POST) a new resource
func restCreate(newResource func() resource) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
const F = "restCreate"
var checkErrs []string
res := newResource()
log.Printf("%s res type %T\n", F, res)
dcdr := json.NewDecoder(r.Body)
err := dcdr.Decode(&res)
log.Printf("%s Unmarshalled into %T: %+v\n", F, res, res)
if err == nil {
checkErrs = res.check()
}
switch {
case err != nil:
w.WriteHeader(http.StatusInternalServerError)
log.Printf("[ERR] %s: %v\n", F, err)
case checkErrs != nil:
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(strings.Join(checkErrs, "\n")))
log.Printf("%s: %v\n", F, err)
default:
res.update()
bs, _ := json.Marshal(res)
w.Write(bs)
}
}
}
func main() {
r := httprouter.New()
r.POST("/anchors", restCreate(newAnchor))
http.ListenAndServe(":8080", r)
}
執行日誌顯示:
restCreate RES 類型main.anchor
restCreate解組成main.anchor:{ID:名稱:}
[ERR] restCreate:JSON:不能解組object into Go值main.resource
爲什麼printf顯示結構體類型和json.Decoder的接口?
我會很感激在什麼地方出了錯,以及如何在一個通用的方法來解決這個任何指標...
這工作 - 謝謝帕夫洛。只是有點困惑,爲什麼你可以返回合成文字和它的地址,將進一步探索。 – mhcbinder