【发布时间】:2018-05-02 10:51:50
【问题描述】:
在我当前的 Golang 项目中,我在将日志发送到我的日志库中的 Elasticsearch 之前使用日志缓冲。我想引入类似 C atexit() 的函数来刷新所有挂起的日志,以防意外退出。
我找到了atexit 库,但在我的情况下它是不够的,因为它不允许将参数传递给处理函数。我决定编写我的版本并最终得到大致相似的结构。我有模块 atexit:
package atexit
import (
"fmt"
"os"
"reflect"
)
var handlers []interface{}
var params []interface{}
func runHandler(handler interface{}, p interface{}) {
defer func() {
if err := recover(); err != nil {
fmt.Fprintln(os.Stderr, "error: atexit handler error:", err)
}
}()
f := reflect.ValueOf(handler)
s := reflectSlice(p)
fmt.Printf("%#v", s)
f.Call(s)
}
func reflectSlice(slice interface{}) []reflect.Value {
s := reflect.ValueOf(slice)
if s.Kind() != reflect.Slice {
panic("InterfaceSlice() given a non-slice type")
}
ret := make([]reflect.Value, s.Len())
for i:=0; i<s.Len(); i++ {
ret[i] = reflect.ValueOf(s.Index(i))
}
return ret
}
func runHandlers() {
for i, handler := range handlers {
runHandler(handler, params[i])
}
}
func Exit(code int) {
runHandlers()
os.Exit(code)
}
func Register(handler interface{}, p interface{}) {
f := reflect.TypeOf(handler)
if f.Kind() != reflect.Func {
panic("Register() given a non-function type")
}
handlers = append(handlers, handler)
params = append(params, p)
}
我从主程序调用它:
package main
import (
"fmt"
"./atexit"
"encoding/json"
"reflect"
)
type Batch struct {
Index string `json:"index"`
Type string `json:"_Type"`
Content interface{} `json:"Content"`
}
func flush(b ...interface{}) {
for _, entry := range(b) {
fmt.Printf("%#v\n", entry)
fmt.Println(reflect.TypeOf(reflect.ValueOf(entry)))
fmt.Println(reflect.TypeOf(entry))
a, err := json.Marshal(entry)
if err != nil {
fmt.Println("error!")
}
fmt.Println(string(a))
}
}
func handler(v ...interface{}) {
fmt.Println("Exiting")
for _, batch := range(v) {
fmt.Printf("%#v\n", batch)
}
}
func main() {
type ColorGroup struct {
ID int
Name string
Colors []string
}
group := ColorGroup{
ID: 1,
Name: "Reds",
Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
}
fmt.Printf("%#v\n", group)
r, err := json.Marshal(group)
if err != nil {
fmt.Println("error:", err)
}
fmt.Println(string(r))
b := []Batch{Batch{"index", "type", "content1"},Batch{"index", "type", "content2"}}
atexit.Register(handler, b)
atexit.Register(flush, []ColorGroup{group})
atexit.Exit(0)
}
如您所见,通过调用reflect.ValueOf(),我得到了结构reflect.Value,然后将其传递给回调函数。问题似乎是这个结构不包含关于 json 导出的元数据,或者没有使用json.Marshal() 正确处理,然后输出空 json。有什么方法可以将正确的[]interface{} 结构传递给回调函数或一些类似的机制来大致完成我想要完成的工作吗?请注意,我想要一个通用的回调机制,它应该独立于传递给它的类型。到目前为止,这似乎是不可能的,或者至少受到f.Call(s) 的限制,它在runHandler() 中调用并以reflect.Value 作为其参数。
【问题讨论】:
标签: go reflection callback