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
+17.9k Golang : Qt image viewer example
+8.2k How to show different content from website server when AdBlock is detected?
+11k Golang : Create Temporary File
+14k Golang : convert rune to unicode hexadecimal value and back to rune character
+18.6k Golang : Generate thumbnails from images
+8.6k Python : Fix SyntaxError: Non-ASCII character in file, but no encoding declared
+4.3k Golang : Converting individual Jawi alphabet to Rumi(Romanized) alphabet example
+8.6k Golang : Add text to image and get OpenCV's X, Y co-ordinates example
+34k Golang : Proper way to set function argument default value
+6.9k How to let Facebook Login button redirect to a particular URL ?
+13.1k Golang : Handle or parse date string with Z suffix(RFC3339) example
+35.1k Golang : Upload and download file to/from AWS S3