gitee.com/go-spring2/spring-base@v1.1.3/cache/result.go (about) 1 /* 2 * Copyright 2012-2019 the original author or authors. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * https://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package cache 18 19 import ( 20 "errors" 21 "fmt" 22 "reflect" 23 24 "gitee.com/go-spring2/spring-base/json" 25 ) 26 27 // Result stores a value. 28 type Result interface { 29 JSON() (string, error) 30 Load(v interface{}) error 31 } 32 33 // ValueResult stores a `reflect.Value`. 34 type ValueResult struct { 35 v reflect.Value 36 t reflect.Type 37 } 38 39 // NewValueResult returns a Result which stores a `reflect.Value`. 40 func NewValueResult(v interface{}) Result { 41 return &ValueResult{ 42 v: reflect.ValueOf(v), 43 t: reflect.TypeOf(v), 44 } 45 } 46 47 // JSON returns the JSON encoding of the stored value. 48 func (r *ValueResult) JSON() (string, error) { 49 b, err := json.Marshal(r.v.Interface()) 50 if err != nil { 51 return "", err 52 } 53 return string(b), nil 54 } 55 56 // Load injects the saved value to v. 57 func (r *ValueResult) Load(v interface{}) error { 58 outVal := reflect.ValueOf(v) 59 if outVal.Kind() != reflect.Ptr || outVal.IsNil() { 60 return errors.New("value should be ptr and not nil") 61 } 62 if outVal.Type().Elem() != r.t { 63 return fmt.Errorf("load type (%s) but expect type (%s)", outVal.Elem().Type(), r.t.String()) 64 } 65 outVal.Elem().Set(r.v) 66 return nil 67 } 68 69 // JSONResult stores a JSON string. 70 type JSONResult struct { 71 v string 72 } 73 74 // NewJSONResult returns a Result which stores a JSON string. 75 func NewJSONResult(v string) Result { 76 return &JSONResult{ 77 v: v, 78 } 79 } 80 81 // JSON returns the JSON encoding of the stored value. 82 func (r *JSONResult) JSON() (string, error) { 83 return r.v, nil 84 } 85 86 // Load injects the saved value to v. 87 func (r *JSONResult) Load(v interface{}) error { 88 return json.Unmarshal([]byte(r.v), v) 89 }