Skip to content

Instantly share code, notes, and snippets.

@PumpkinSeed
Created May 2, 2018 19:56
Show Gist options
  • Save PumpkinSeed/26a93d474532527e7a01ecae852f7c2a to your computer and use it in GitHub Desktop.
Save PumpkinSeed/26a93d474532527e7a01ecae852f7c2a to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"fmt"
"reflect"
)
var test = `{
"title":"%s",
"content":"%s article's content"
}`
type Article struct {
Title string `json:"title"`
Content string `json:"content"`
}
type Result struct {
Hits [][]byte
}
func main() {
var result = Result{
Hits: [][]byte{
[]byte(fmt.Sprintf(test, "First", "First")),
[]byte(fmt.Sprintf(test, "Second", "Second")),
[]byte(fmt.Sprintf(test, "Third", "Third")),
},
}
articlesContainer := result.Each(reflect.TypeOf(Article{}))
for _, article := range articlesContainer {
fmt.Printf("Title: %s, Content: %s\n", article.(Article).Title, article.(Article).Content)
}
}
func (r *Result) Each(typ reflect.Type) []interface{} {
if len(r.Hits) == 0 {
return nil
}
var slice []interface{}
for _, hit := range r.Hits {
v := reflect.New(typ).Elem()
if err := json.Unmarshal(hit, v.Addr().Interface()); err == nil {
slice = append(slice, v.Interface())
}
}
return slice
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment