Golang encoding/binary.Write() function examples
package encoding/binary
Write writes the binary representation of data into w (1st parameter). Data (3rd parameter) must be a fixed-size value or a slice of fixed-size values, or a pointer to such data. Bytes written to w are encoded using the specified byte order (2nd parameter) and read from successive fields of the data. When writing structs, zero values are written for fields with blank (_) field names.
Golang encoding/binary.Write() function usage examples
Example 1 :
package main
import (
"bytes"
"encoding/binary"
"fmt"
"math"
)
func main() {
buf := new(bytes.Buffer)
var pi float64 = math.Pi
err := binary.Write(buf, binary.LittleEndian, pi)
if err != nil {
fmt.Println("binary.Write failed:", err)
}
fmt.Println(buf.Bytes())
}
Output :
[24 45 68 84 251 33 9 64]
Example 2 :
func (self *MockRequestHandler) HandleRequest(request *protocol.Request, conn net.Conn) error {
response := &protocol.Response{RequestId: request.Id, Type: &writeOk}
data, _ := response.Encode()
binary.Write(conn, binary.LittleEndian, uint32(len(data)))
conn.Write(data)
return nil
}
References :
http://golang.org/pkg/encoding/binary/#Write
https://github.com/influxdb/influxdb/blob/master/coordinator/clientservertest.go
Advertisement
Something interesting
Tutorials
+8.3k Golang: Prevent over writing file with md5 hash
+6.3k WARNING: UNPROTECTED PRIVATE KEY FILE! error message
+6.5k Golang : Combine slices of complex numbers and operation example
+16.5k Golang : Check if a string contains multiple sub-strings in []string?
+12.9k Python : Convert IPv6 address to decimal and back to IPv6
+16.3k Golang :Trim white spaces from a string
+16.5k Golang : Execute terminal command to remote machine example
+8.3k Golang : Implementing class(object-oriented programming style)
+17.7k Golang : [json: cannot unmarshal object into Go value of type]
+7.1k Golang : Get Alexa ranking data example
+9.3k Golang : Generate random Chinese, Japanese, Korean and other runes
+25.3k Golang : Get current file path of a file or executable