|
| 1 | +package proto |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/base64" |
| 5 | + "fmt" |
| 6 | + "sort" |
| 7 | + "strings" |
| 8 | + "unicode" |
| 9 | + |
| 10 | + "golang.org/x/text/encoding/charmap" |
| 11 | +) |
| 12 | + |
| 13 | +// EncodeParams converts params map into a sorted base64-encoded string using Windows-1251 encoding. |
| 14 | +func EncodeParams(params map[string]string) (string, error) { |
| 15 | + keys := make([]string, 0, len(params)) |
| 16 | + for k := range params { |
| 17 | + keys = append(keys, k) |
| 18 | + } |
| 19 | + sort.Strings(keys) |
| 20 | + |
| 21 | + var sb strings.Builder |
| 22 | + for i, k := range keys { |
| 23 | + if i > 0 { |
| 24 | + sb.WriteByte('|') |
| 25 | + } |
| 26 | + sb.WriteString(k) |
| 27 | + sb.WriteByte('=') |
| 28 | + sb.WriteString(params[k]) |
| 29 | + } |
| 30 | + sb.WriteByte('|') |
| 31 | + |
| 32 | + enc := charmap.Windows1251.NewEncoder() |
| 33 | + encoded, err := enc.String(sb.String()) |
| 34 | + if err != nil { |
| 35 | + return "", fmt.Errorf("encode params: %w", err) |
| 36 | + } |
| 37 | + return base64.StdEncoding.EncodeToString([]byte(encoded)), nil |
| 38 | +} |
| 39 | + |
| 40 | +// DecodeResponse decodes base64-encoded Windows-1251 text to UTF-8 and removes control characters. |
| 41 | +func DecodeResponse(data string) (string, error) { |
| 42 | + raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(data)) |
| 43 | + if err != nil { |
| 44 | + return "", fmt.Errorf("base64 decode: %w", err) |
| 45 | + } |
| 46 | + decoded, err := charmap.Windows1251.NewDecoder().Bytes(raw) |
| 47 | + if err != nil { |
| 48 | + return "", fmt.Errorf("decode charset: %w", err) |
| 49 | + } |
| 50 | + cleaned := strings.Map(func(r rune) rune { |
| 51 | + if unicode.IsPrint(r) || r == '\n' || r == '\r' || r == '\t' { |
| 52 | + return r |
| 53 | + } |
| 54 | + return -1 |
| 55 | + }, string(decoded)) |
| 56 | + return cleaned, nil |
| 57 | +} |
| 58 | + |
| 59 | +// BuildRequest returns byte slice representing the command and parameters. |
| 60 | +func BuildRequest(command, encodedParams string, quit bool) []byte { |
| 61 | + if quit { |
| 62 | + return []byte(fmt.Sprintf("%s %s\nQUIT\n", command, encodedParams)) |
| 63 | + } |
| 64 | + return []byte(fmt.Sprintf("%s %s\n", command, encodedParams)) |
| 65 | +} |
0 commit comments