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
+20.7k Android Studio : AlertDialog and EditText to get user string input example
+5.6k PHP : Convert CSV to JSON with YQL example
+12.7k Golang : Sort and reverse sort a slice of bytes
+15.6k Golang : rune literal not terminated error
+21.1k Golang : For loop continue,break and range
+15.9k Golang : Get current time from the Internet time server(ntp) example
+20k Golang : Convert(cast) bytes.Buffer or bytes.NewBuffer type to io.Reader
+6.9k Mac OSX : Find large files by size
+19.7k Golang : Archive directory with tar and gzip
+9.1k Golang : io.Reader causing panic: runtime error: invalid memory address or nil pointer dereference
+21.8k SSL : How to check if current certificate is sha1 or sha2
+12.1k Golang : Decompress zlib file example