golang struct to buf
struct to buf
package main import ( "bytes" "encoding/binary" "reflect" "io" "errors" "fmt" ) func writeBuf(w io.Writer,v reflect.Value) (n int, err error){ newBuf := bytes.NewBuffer(nil) for i := 0; i < v.NumField(); i++ { switch v.Field(i).Type().Kind() { case reflect.Struct: n,err := writeBuf(newBuf,v.Field(i)) if err != nil { return n,err } case reflect.Bool: boolByte := []byte{0} if v.Field(i).Bool() { boolByte = []byte{1} } newBuf.Write(boolByte) case reflect.String: newBuf.WriteString(v.Field(i).String()) case reflect.Slice: newBuf.Write(v.Field(i).Bytes()) case reflect.Int: binary.Write(newBuf, binary.LittleEndian,int32(v.Field(i).Int())) case reflect.Uint: binary.Write(newBuf, binary.LittleEndian, uint32(v.Field(i).Uint())) case reflect.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, binary.LittleEndian, v.Field(i).Interface()) } } return w.Write(newBuf.Bytes()) } func WriteStructToBuffer(w io.Writer ,data interface{}) ( error ) { v := reflect.Indirect(reflect.ValueOf(data)) if v.Kind() == reflect.Struct { fmt.Println("test") _,err := writeBuf(w,v) return err } return errors.New("invalid type Not a struct") } func StringFixedLength(s string, length int) []byte { sLength := len(s) if sLength >= length { return []byte(s[:length]) } else { b := make([]byte, length-sLength) return append([]byte(s), b...) } return nil }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。