Why can't decompress gzip data by Go in my PHP demo, but PHP gzip data to Go is successful? I need post gzip JSON data from Go to PHP API service.
Test result
-> | php | go
---------------------
php | ok | ok
go | fail | ok
PHP code
class GzipDemo
{
public function gzen($data, $file){
$json_data = json_encode($data);
$gz_data = gzencode($json_data,9);
file_put_contents($file,$gz_data);
}
public function gzdn($file){
$data = file_get_contents($file);
$unpacked = gzdecode($data);
if ($unpacked === FALSE)
{
print("failed:".$file."
");
}else{
print($file. " result Data :".$unpacked ."
");
}
}
}
$demo = new GzipDemo();
$file="phpgzip.txt";
$demo->gzen("data",$file);
$demo->gzdn($file);
$demo->gzdn("gogzip.txt");
This result: PHP to PHP okay. Go to PHP fail.
Go code
package main
import (
"bytes"
"compress/gzip"
"encoding/json"
"fmt"
"io/ioutil"
"os"
)
func main() {
gzen("data", "gogzip.txt")
gden("gogzip.txt")
gden("phpgzip.txt")
}
func gzen(data string, file string) {
b, _ := json.Marshal(data)
buffer := new(bytes.Buffer)
w, _ := gzip.NewWriterLevel(buffer, gzip.BestCompression)
defer w.Close()
w.Write(b)
w.Flush()
ioutil.WriteFile(file, buffer.Bytes(), os.ModePerm)
}
func gden(file string) {
b, _ := ioutil.ReadFile(file)
buffer := new(bytes.Buffer)
buffer.Write(b)
r, _ := gzip.NewReader(buffer)
defer r.close()
data, _ := ioutil.ReadAll(r)
fmt.Println(file, " result Data:", string(data))
}
This result: Go to Go okay. PHP to Go okay.