This is a creation in Article, where the information may have evolved or changed.
August 7 @ Huang classmate asked me: "Data to Redis is gzdeflate compressed data, Golang out from Redis, decompression failed." Many business from PHP to Golang often encounter, so write down this blog post, hoping to help more people.
To decode PHP's encoding using Golang, then you need to know what the algorithm of the Gzdeflate function is, first go to the Gzdeflate document and look at the discovery:
gzdeflate使用的是纯粹的DEFLATE格式。 This is consistent with the Golang compress/flate package. With an understanding you can look at the Golang document implementation code. Then and @ Huang classmate wrote several functions to verify, the final finalized as follows:
package mainimport ("strings""fmt""compress/flate""bytes""io/ioutil""github.com/bitly/go-simplejson")func main() {str:="test123"str=""b:=Gzdeflate(str,-1)ss:=Gzdecode(string(b))fmt.Println(ss)}// 解码func Gzdecode(data string) string {if data == "" {return ""}r :=flate.NewReader(strings.NewReader(data))defer r.Close()out, err := ioutil.ReadAll(r)if err !=nil {fmt.Errorf("%s\n",err)return ""}return string(out)}// 编码func Gzdeflate(data string,level int) []byte {if data == "" {return []byte{}}var bufs bytes.Bufferw,_ :=flate.NewWriter(&bufs,level)w.Write([]byte(data))w.Flush()defer w.Close()return bufs.Bytes()}// 编码func GzdeflateForString(data string,level int) string {if data == "" {return ""}var bufs bytes.Bufferw,_ :=flate.NewWriter(&bufs,level)w.Write([]byte(data))w.Flush()defer w.Close()return bufs.String()}
After @ Huang classmate test can be used correctly. Leave a wiki for future classmates to see.