美文网首页
golang base64编码

golang base64编码

作者: 第八共同体 | 来源:发表于2018-02-06 19:15 被阅读0次

    1.stdEncoding:标准的base64编码

    type Encoding struct {
        encode    [64]byte
        decodeMap [256]byte
        padChar   rune
        strict    bool
    }
    
    const (
        StdPadding rune = '=' // Standard padding character
        NoPadding  rune = -1  // No padding
    )
    
    const encodeStd = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
    const encodeURL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
    // NewEncoding returns a new padded Encoding defined by the given alphabet,
    // which must be a 64-byte string that does not contain the padding character
    // or CR / LF ('\r', '\n').
    // The resulting Encoding uses the default padding character ('='),
    // which may be changed or disabled via WithPadding.
    func NewEncoding(encoder string) *Encoding {
        if len(encoder) != 64 {
            panic("encoding alphabet is not 64-bytes long")
        }
        for i := 0; i < len(encoder); i++ {
            if encoder[i] == '\n' || encoder[i] == '\r' {
                panic("encoding alphabet contains newline character")
            }
        }
    
        e := new(Encoding)
        e.padChar = StdPadding
        copy(e.encode[:], encoder)
    
        for i := 0; i < len(e.decodeMap); i++ {
            e.decodeMap[i] = 0xFF
        }
        for i := 0; i < len(encoder); i++ {
            e.decodeMap[encoder[i]] = byte(i)
        }
        return e
    }
    
    // StdEncoding is the standard base64 encoding, as defined in
    // RFC 4648.
    var StdEncoding = NewEncoding(encodeStd)
    
    // URLEncoding is the alternate base64 encoding defined in RFC 4648.
    // It is typically used in URLs and file names.
    var URLEncoding = NewEncoding(encodeURL)
    
    
    // EncodeToString returns the base64 encoding of src.
    func (enc *Encoding) EncodeToString(src []byte) string {
        buf := make([]byte, enc.EncodedLen(len(src)))
        enc.Encode(buf, src)
        return string(buf)
    }
    

    示例

        d := "This is a golang test."
        encodedContent := base64.StdEncoding.EncodeToString([]byte(d))
        fmt.Println(encodedContent)
        sourceContent,_ := base64.StdEncoding.DecodeString(encodedContent)
        fmt.Println(string(sourceContent))
    

    Output:

    VGhpcyBpcyBhIGdvbGFuZyB0ZXN0Lg==
    This is a golang test.
    

    相关文章

      网友评论

          本文标题:golang base64编码

          本文链接:https://www.haomeiwen.com/subject/ikqnzxtx.html