由于 encoding/json 需要一個非 nil 接口來解組:我如何可靠地制作用戶提供的指針類型的(完整)副本,將其存儲在我的User接口中,然后 JSON 解碼為該臨時?注意:這里的目標是實現“無人值守”——即從 Redis/BoltDB 中提取字節,解碼為接口類型,然后檢查GetID()接口定義的方法是否返回非空字符串,以及請求中間件。游樂場:http : //play.golang.org/p/rYODiNrfWwpackage mainimport ( "bytes" "encoding/json" "fmt" "log" "net/http" "os" "time")type session struct { ID string User User Expires int64}type User interface { GetID() string}type LocalUser struct { ID string Name string Created time.Time}func (u *LocalUser) GetID() string { return u.ID}type Auth struct { key []byte // We store an instance of userType here so we can unmarshal into it when // deserializing from JSON (or other non-gob decoders) into *session.User. // Attempting to unmarshal into a nil session.User would otherwise fail. // We do this so we can unmarshal from our data-store per-request *without // the package user having to do so manually* in the HTTP middleware. We can't // rely on the user passing in an fresh instance of their User satisfying type. userType User}func main() { // auth is a pointer to avoid copying the struct per-request: although small // here, it contains a 32-byte key, options fields, etc. outside of this example. var auth = &Auth{key: []byte("abc")} local := &LocalUser{"19313", "Matt", time.Now()} b, _, _, err := auth.SetUser(local) if err != nil { log.Fatalf("SetUser: %v", err) } user, err := auth.GetUser(b) if err != nil { log.Fatalf("GetUser: %#v", err) } fmt.Fprintf(os.Stdout, "%v\n", user)}
2 回答
開心每一天1111
TA貢獻1836條經驗 獲得超13個贊
如果您需要深度復制接口,請將該方法添加到您的接口中。
type User interface {
GetID() string
Copy() User
}
type LocalUser struct {
ID string
Name string
Created time.Time
}
// Copy receives a copy of LocalUser and returns a pointer to it.
func (u LocalUser) Copy() User {
return &u
}
眼眸繁星
TA貢獻1873條經驗 獲得超9個贊
因為應用程序將解碼為 aUser并且 JSON 解碼器的參數必須是指針值,所以我們可以假設User值是指針值。鑒于此假設,以下代碼可用于為解碼創建新的零值:
uzero := reflect.New(reflect.TypeOf(u).Elem()).Interface().(User)
- 2 回答
- 0 關注
- 164 瀏覽
添加回答
舉報
0/150
提交
取消
