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)}// decoding 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)}// encoded func gzdeflate (data string,level int) []byte { if data == "" { return []byte{} } var bufs bytes. Buffer w,_ :=flate. Newwriter (&bufs,level) w.write ([]byte (data)) w.flush () defer w.close () return bufs. Bytes ()}// code func gzdeflateforstring (data string,level int) string { if data == "" { return "" } var bufs bytes. buffer w,_ :=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.
This article is from the "dream to think XI" blog, please be sure to keep this source http://qiangmzsx.blog.51cto.com/2052549/1955868
PHP encoded gzdeflate and Golang decoding deflate