base64编解码和URL编解码

package main

import (
   "encoding/base64"
   "fmt"
   "net/url"
)

// Base64Encode Base64编码
// @param str string 要进行Base64编码的字符串
// @return string 字符串的Base64编码
func Base64Encode(str string) string {
   return base64.StdEncoding.EncodeToString([]byte(str))
}

// Base64Decode Base64解码
// @param str string 要进行Base64解码的字符串
// @return string Base64解码后的字符串
func Base64Decode(str string) string {
   decode, _ := base64.StdEncoding.DecodeString(str)
   return string(decode)
}

// UrlEncode URL编码
// @param urlStr string URL
// @return string URL编码字符串
func UrlEncode(urlStr string) string {
   return url.QueryEscape(urlStr)
}

// UrlDecode URL解码
// @param str string URL编码字符串
// @return string URL
func UrlDecode(str string) string {
   unescape, _ := url.QueryUnescape(str)
   return unescape
}

func main() {
   strDemo := "PHP是世界上最好の语言"
   urlDemo := "https://www.domain.com/demo.html?name=张三"

   encode := Base64Encode(strDemo)
   fmt.Printf("%v <===> %v \n", strDemo, encode)
   // PHP是世界上最好の语言 <===> UEhQ5piv5LiW55WM5LiK5pyA5aW944Gu6K+t6KiA

   decode := Base64Decode(encode)
   fmt.Printf("%v <===> %v \n", encode, decode)
   // UEhQ5piv5LiW55WM5LiK5pyA5aW944Gu6K+t6KiA <===> PHP是世界上最好の语言

   urlEncode := UrlEncode(urlDemo)
   fmt.Printf("%v <===> %v \n", urlDemo, urlEncode)
   // https://www.domain.com/demo.html?name=张三 <===> https%3A%2F%2Fwww.domain.com%2Fdemo.html%3Fname%3D%E5%BC%A0%E4%B8%89

   urlDecode := UrlDecode(urlEncode)
   fmt.Printf("%v <===> %v \n", urlEncode, urlDecode)
   // https%3A%2F%2Fwww.domain.com%2Fdemo.html%3Fname%3D%E5%BC%A0%E4%B8%89 <===> https://www.domain.com/demo.html?name=张三
}

Copyright © 2024 码农人生. All Rights Reserved