编辑代码

package main

import (
    "compress/gzip"
	// "archive/zip"
	"bytes"
	"encoding/base64"
	"fmt"
	"log"
)

func main() {
	// Example string to encode
	input := "abc123"

	// Compress and encode to Base64
	result := zipEncode(input, true)

	fmt.Println("Compressed and Base64 Encoded String:", result)
}

// zipEncode compresses and encodes the input string to Base64.
func zipEncode(str string, isZip bool) string {
	var encodedStr string

	if isZip {
		compressed, err := compress(str)
		if err != nil {
			log.Fatalf("Compression failed: %v", err)
		}
		encodedStr = base64.StdEncoding.EncodeToString(compressed)
	} else {
		encodedStr = base64.StdEncoding.EncodeToString([]byte(str))
	}

	// Remove newlines from the encoded string (if any)
	encodedStr = removeNewlines(encodedStr)

	return encodedStr
}

// compress compresses the input string using GZIP format.
func compress(str string) ([]byte, error) {
	var buf bytes.Buffer
	gzipWriter := gzip.NewWriter(&buf)

	_, err := gzipWriter.Write([]byte(str))
	if err != nil {
		return nil, err
	}

	err = gzipWriter.Close()
	if err != nil {
		return nil, err
	}

	return buf.Bytes(), nil
}

// compress compresses the input string using ZIP format.
// func compress(str string) ([]byte, error) {
// 	var buf bytes.Buffer
// 	zipWriter := zip.NewWriter(&buf)

// 	// Create a new entry with a dummy name "0"
// 	entry, err := zipWriter.Create("0")
// 	if err != nil {
// 		return nil, err
// 	}

// 	_, err = entry.Write([]byte(str))
// 	if err != nil {
// 		return nil, err
// 	}

// 	err = zipWriter.Close()
// 	if err != nil {
// 		return nil, err
// 	}

// 	return buf.Bytes(), nil
// }

// removeNewlines removes all newline characters from the input string.
func removeNewlines(str string) string {
	return string(bytes.ReplaceAll([]byte(str), []byte("\n"), []byte("")))
}