PHP encoded gzdeflate and Golang decoding deflate

Source: Internet
Author: User

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.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.