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
+11.3k Golang : Fix fmt.Scanf() on Windows will scan input twice problem
+7.2k Golang : Null and nil value
+7.5k Golang : Rename part of filename
+6.1k Java : Human readable password generator
+13.5k Golang : Read XML elements data with xml.CharData example
+15.8k Golang : How to login and logout with JWT example
+13.1k Golang : How to get a user home directory path?
+12.7k Golang : Pass database connection to function called from another package and HTTP Handler
+5.4k Golang : What is StructTag and how to get StructTag's value?
+10.8k Golang : Natural string sorting example
+13.6k Golang : Qt progress dialog example
+11.3k Golang : Post data with url.Values{}