golang base64 转回 list
时间: 2024-01-04 07:19:50 浏览: 133
在Golang中,可以使用`encoding/base64`包来进行Base64编码和解码操作。要将Base64编码的字符串转回原始数据,可以使用`DecodeString`函数。
下面是一个示例代码:
```go
package main
import (
"encoding/base64"
"fmt"
)
func main() {
base64Str := "SGVsbG8gd29ybGQh"
decodedBytes, err := base64.StdEncoding.DecodeString(base64Str)
if err != nil {
fmt.Println("Base64 decoding error:", err)
return
}
decodedStr := string(decodedBytes)
fmt.Println("Decoded string:", decodedStr)
}
```
运行以上代码,将会输出解码后的字符串:
```
Decoded string: Hello world!
```
相关问题
golang词法BNF
golang词法BNF如下:
```
SourceFile = PackageClause ";" { ImportDecl ";" } { TopLevelDecl ";" } .
PackageClause = "package" PackageName .
PackageName = identifier .
ImportDecl = "import" ( ImportSpec | "(" { ImportSpec ";" } ")" ) .
ImportSpec = [ "." | PackageName ] ImportPath .
ImportPath = string_lit .
TopLevelDecl = Declaration | FunctionDecl | MethodDecl .
Declaration = ConstDecl | TypeDecl | VarDecl .
ConstDecl = "const" ( ConstSpec | "(" { ConstSpec ";" } ")" ) .
ConstSpec = IdentifierList [ [ Type ] "=" ExpressionList ] .
IdentifierList = identifier { "," identifier } .
ExpressionList = Expression { "," Expression } .
TypeDecl = "type" ( TypeSpec | "(" { TypeSpec ";" } ")" ) .
TypeSpec = identifier Type .
Type = TypeName | TypeLit | "(" Type ")" | "*" Type | ArrayType | StructType | PointerType | FunctionType | InterfaceType | SliceType | MapType | ChannelType .
TypeName = identifier .
TypeLit = ArrayType | StructType | PointerType | FunctionType | InterfaceType | SliceType | MapType | ChannelType .
ArrayType = "[" ArrayLength "]" ElementType .
ArrayLength = Expression .
ElementType = Type .
StructType = "struct" "{" { FieldDecl ";" } "}" .
FieldDecl = ( IdentifierList Type | EmbeddedField ) [ Tag ] .
EmbeddedField = [ "*" ] TypeName .
Tag = string_lit .
PointerType = "*" BaseType .
BaseType = Type .
FunctionType = "func" Signature .
Signature = Parameters [ Result ] .
Result = Parameters | Type .
Parameters = "(" [ ParameterList [ "," ] ] ")" .
ParameterList = ParameterDecl { "," ParameterDecl } .
ParameterDecl = [ IdentifierList ] [ "..." ] Type .
InterfaceType = "interface" "{" { MethodSpec ";" } "}" .
MethodSpec = MethodName Signature | InterfaceTypeName .
MethodName = identifier .
InterfaceTypeName = TypeName .
SliceType = "[" "]" ElementType .
MapType = "map" "[" KeyType "]" ElementType .
KeyType = Type .
ChannelType = ( "chan" [ "<-" ] | "<-" "chan" ) ElementType .
VarDecl = "var" ( VarSpec | "(" { VarSpec ";" } ")" ) .
VarSpec = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) .
Expression = UnaryExpr | Expression binary_op Expression .
UnaryExpr = PrimaryExpr | unary_op UnaryExpr .
PrimaryExpr = Operand | Conversion | "(" Expression ")" | PrimaryExpr Selector | PrimaryExpr Index | PrimaryExpr Slice | PrimaryExpr TypeAssertion | PrimaryExpr Arguments .
Operand = Literal | OperandName | MethodExpr | "(" Expression ")" .
Literal = BasicLit | CompositeLit | FunctionLit .
BasicLit = int_lit | float_lit | imaginary_lit | rune_lit | string_lit .
OperandName = identifier | QualifiedIdent.
QualifiedIdent = PackageName "." identifier .
MethodExpr = ReceiverType "." MethodName .
ReceiverType = Type .
Index = "[" Expression "]" .
Slice = "[" [ Expression ] ":" [ Expression ] "]" | "[" [ Expression ] ":" Expression ":" Expression "]" .
Arguments = "(" [ ( ExpressionList | Type [ "," ExpressionList ] ) [ "..." ] ] ")" .
CompositeLit = LiteralType LiteralValue .
LiteralType = StructType | ArrayType | "[" "..." "]" ElementType | SliceType | TypeName .
LiteralValue = "{" [ ElementList [ "," ] ] "}" .
ElementList = KeyedElement { "," KeyedElement } .
KeyedElement = [ Key ":" ] Element .
Key = FieldName | Expression | LiteralValue .
FieldName = identifier .
Conversion = Type "(" Expression [ "," ] ")" .
```
golang 下载gmail 邮件附件
以下是使用golang下载gmail邮件附件的示例代码:
```go
package main
import (
"encoding/base64"
"fmt"
"io"
"log"
"net/mail"
"net/smtp"
"os"
"path/filepath"
"strings"
"github.com/joho/godotenv"
"golang.org/x/net/context"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/gmail/v1"
)
func main() {
// 加载.env环境变量文件
err := godotenv.Load()
if err != nil {
log.Fatalf("Error loading .env file: %v", err)
}
// 获取OAuth2访问令牌
ctx := context.Background()
config, err := google.ConfigFromJSON([]byte(os.Getenv("GOOGLE_CLIENT_SECRET")), gmail.GmailReadonlyScope)
if err != nil {
log.Fatalf("Unable to parse client secret file to config: %v", err)
}
token := &oauth2.Token{
AccessToken: os.Getenv("GOOGLE_ACCESS_TOKEN"),
RefreshToken: os.Getenv("GOOGLE_REFRESH_TOKEN"),
TokenType: "Bearer",
Expiry: oauth2.Now(),
}
client := config.Client(ctx, token)
// 创建Gmail服务
srv, err := gmail.New(client)
if err != nil {
log.Fatalf("Unable to retrieve Gmail client: %v", err)
}
// 获取最新的10封邮件
user := "me"
r, err := srv.Users.Messages.List(user).MaxResults(10).Q("is:unread").Do()
if err != nil {
log.Fatalf("Unable to retrieve messages: %v", err)
}
// 下载每个邮件的附件
for _, m := range r.Messages {
msg, err := srv.Users.Messages.Get(user, m.Id).Do()
if err != nil {
log.Fatalf("Unable to retrieve message %v: %v", m.Id, err)
}
// 解析邮件头部
h := msg.Payload.Headers
var subject, from, date string
for _, v := range h {
switch v.Name {
case "Subject":
subject = v.Value
case "From":
from = v.Value
case "Date":
date = v.Value
}
}
// 下载附件
for _, p := range msg.Payload.Parts {
if p.Filename != "" {
part := p.Body
data, err := base64.URLEncoding.DecodeString(part.Data)
if err != nil {
log.Fatalf("Unable to decode attachment %v: %v", p.Filename, err)
}
// 将附件保存到本地
ext := filepath.Ext(p.Filename)
filename := fmt.Sprintf("%s_%s%s", strings.ReplaceAll(from, "@", "_"), subject, ext)
f, err := os.Create(filename)
if err != nil {
log.Fatalf("Unable to create file %v: %v", filename, err)
}
defer f.Close()
_, err = io.Copy(f, strings.NewReader(string(data)))
if err != nil {
log.Fatalf("Unable to save file %v: %v", filename, err)
}
log.Printf("Attachment saved: %v", filename)
}
}
}
}
```
在上面的代码中,首先加载.env文件,该文件包含Google应用程序凭据和OAuth2访问令牌。
然后使用OAuth2访问令牌创建Gmail客户端,并使用该客户端获取最新的10封未读邮件。
对于每个邮件,我们获取其详细信息,包括邮件头部和附件。然后,我们使用base64解码附件数据,并将其保存到本地文件中。文件名采用发送方的电子邮件地址、主题和附件扩展名的组合。
最后,我们在控制台输出“Attachment saved: filename”以指示附件已成功保存。
阅读全文