struct to buf
packagemain import( "bytes" "encoding/binary" "reflect" "io" "errors" "fmt" ) funcwriteBuf(wio.Writer,vreflect.Value)(nint,errerror){ newBuf:=bytes.NewBuffer(nil) fori:=0;i<v.NumField();i++{ switchv.Field(i).Type().Kind(){ casereflect.Struct: n,err:=writeBuf(newBuf,v.Field(i)) iferr!=nil{ returnn,err } casereflect.Bool: boolByte:=[]byte{0} ifv.Field(i).Bool(){ boolByte=[]byte{1} } newBuf.Write(boolByte) casereflect.String: newBuf.WriteString(v.Field(i).String()) casereflect.Slice: newBuf.Write(v.Field(i).Bytes()) casereflect.Int: binary.Write(newBuf,binary.LittleEndian,int32(v.Field(i).Int())) casereflect.Uint: binary.Write(newBuf,uint32(v.Field(i).Uint())) casereflect.Uint8,reflect.Uint16,reflect.Uint32,reflect.Uint64,reflect.Int8,reflect.Int16,reflect.Int32,reflect.Int64,reflect.Float32,reflect.Float64,reflect.Complex64,reflect.Complex128: binary.Write(newBuf,v.Field(i).Interface()) } } returnw.Write(newBuf.Bytes()) } funcWriteStructToBuffer(wio.Writer,datainterface{})(error){ v:=reflect.Indirect(reflect.ValueOf(data)) ifv.Kind()==reflect.Struct{ fmt.Println("test") _,err:=writeBuf(w,v) returnerr } returnerrors.New("invalidtypeNotastruct") } funcStringFixedLength(sstring,lengthint)[]byte{ sLength:=len(s) ifsLength>=length{ return[]byte(s[:length]) }else{ b:=make([]byte,length-sLength) returnappend([]byte(s),b...) } returnnil }原文链接:https://www.f2er.com/go/191025.html