golangstruct to buf自留笔记
/** * Created with IntelliJ IDEA. * User: liaojie * Date: 13-7-4 * Time: 下午1:42 * To change this template use File | Settings | File Templates. */ 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,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,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 }原文链接:https://www.f2er.com/go/191280.html