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
+7.2k CloudFlare : Another way to get visitor's real IP address
+5.2k Golang : PGX CopyFrom to insert rows into Postgres database
+24.5k Golang : GORM read from database example
+6k Fontello : How to load and use fonts?
+7.8k Golang : Load DSA public key from file example
+12.7k Golang : Remove or trim extra comma from CSV
+16.4k Golang : Test floating point numbers not-a-number and infinite example
+16.5k Golang : Check if a string contains multiple sub-strings in []string?
+7.4k Golang : Check to see if *File is a file or directory
+5.8k Golang : Fix opencv.LoadHaarClassifierCascade The node does not represent a user object error
+15.2k Golang : How to add color to string?