Base64 encode and decode with whitespace checks

Go
package b64

import (
    "encoding/base64"
    "fmt"
    "strings"
)

// Encode returns the unpadded standard base64 encoding of s.
func Encode(s string) string {
    return base64.RawStdEncoding.EncodeToString([]byte(s))
}

// Decode accepts padded or unpadded standard base64 and rejects whitespace.
func Decode(s string) (string, error) {
    s = strings.TrimSpace(s)
    if len(strings.Fields(s)) > 1 {
        return "", fmt.Errorf("base64 input %q contains whitespace", s)
    }
    enc := base64.StdEncoding
    if len(s)%4 != 0 {
        enc = base64.RawStdEncoding
    }
    raw, err := enc.DecodeString(s)
    if err != nil {
        return "", fmt.Errorf("decode base64: %w", err)
    }
    return string(raw), nil
}