August 7 @ Yellow 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 is using the pure deflate format . This is consistent with Golang's compress/flate package. With an understanding you can look at the Golang document implementation code. Then and @ Huang classmate wrote a few functions to verify, finalized as follows:
package mainimport ("Strings" "FMT" "compress/flate" "bytes" "Io/ioutil") Func main () {str:= " Huangyupeng123 "B:=gzdeflate (str,-1) Ss:=gzencode (string (b)) fmt. PRINTLN (ss)/*str:= "huangyupeng123" Ss:=gzdeflate (str,0) fmt. PRINTLN (ss) S=gzencode (ss) fmt. Println (s) */}// decoding Func gzencode (data string) string {r :=flate. Newreader (Strings. Newreader (data) defer r.close () Out, err := ioutil. ReadAll (R) if err !=nil {fmt. Errorf ("%s\n", Err)}return string (out)}// encoding func gzdeflate (data string,level int) []byte {var bufs bytes. Bufferw,_ :=flate. Newwriter (&bufs,level) W.write ([]byte (data)) W.flush () W.close () Return bufs. Bytes ()}// encoded func gzdeflateforstring (data string,level int) string {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.