Last active
May 3, 2019 23:44
-
-
Save doron2402/3588fe0f6cf1b872b9d50c57a06e45a7 to your computer and use it in GitHub Desktop.
communicating between golang and python via http binary data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"crypto/rand" | |
"encoding/binary" | |
"log" | |
"net/http" | |
) | |
// GenerateUint64 - generate a random uint64 | |
func GenerateUint64() uint64 { | |
buf := make([]byte, 8) | |
rand.Read(buf) // Always succeeds, no need to check error | |
return binary.LittleEndian.Uint64(buf) | |
} | |
func handler(w http.ResponseWriter, r *http.Request) { | |
numberOfValues := 100 | |
uint64BytesSize := 8 | |
bufferSize := numberOfValues * uint64BytesSize | |
buf := make([]byte, bufferSize) | |
tmp := GenerateUint64() | |
for index := 0; index < numberOfValues; index++ { | |
binary.LittleEndian.PutUint64(buf, tmp) | |
tmp = GenerateUint64() | |
} | |
w.Header().Set("Content-Type", "application/octet-stream") | |
w.Write(buf) | |
} | |
func main() { | |
http.HandleFunc("/", handler) | |
log.Fatal(http.ListenAndServe(":8080", nil)) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# reader.py | |
# Read uint64 from http | |
import urllib.request, urllib.parse, urllib.error | |
from struct import unpack_from | |
# Read from the web server aka api | |
data = urllib.request.urlopen('http://localhost:8080').read() | |
offset = 0 | |
for i in range(0,100): | |
parsed_data = unpack_from('Q', data, offset=offset) | |
print(parsed_data) | |
# increase offset by byte size | |
# in this case 8bytes uint64 | |
offset += 8 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment