英文:
How can I remove the base64 header from a data URI with Go?
问题
我想从一个base64数据URI中移除base64头部,例如给定的:
data:video/mp4;base64,TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz
我想要移除前缀:
data:video/mp4;base64,
问题是我接收到不同类型的视频,所以我不知道如何可靠地移除这个头部,无论它以任何形式出现。有人可以帮忙吗?
英文:
I want to remove a base64 header from a base64 data URI, for example given:
data:video/mp4;base64,TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz
I want to remove the prefix:
data:video/mp4;base64,
The problem is that I receive different types of video, so I don't know how to reliably remove this header in any form it may present itself. Can someone help?
答案1
得分: 4
将字符串在逗号处切割以获取base64数据:
func decode(uri string) ([]byte, error) {
if !strings.HasPrefix(uri, "data:") {
return nil, errors.New("不是data uri")
}
_, data, ok := strings.Cut(uri, ",")
if !ok {
return nil, errors.New("不是data uri")
}
return base64.URLEncoding.DecodeString(data)
}
在Go 1.18中添加了strings.Cut函数。在早期的Go版本中,可以使用strings.Index在逗号处进行切割:
func decode(uri string) ([]byte, error) {
if !strings.HasPrefix(uri, "data:") {
return nil, errors.New("不是data uri")
}
i := strings.Index(uri, ",")
if i < 0 {
return nil, errors.New("不是data uri")
}
return base64.URLEncoding.DecodeString(uri[i+1:])
}
英文:
Cut the string at the comma to get the base64 data:
func decode(uri string) ([]byte, error) {
if !strings.HasPrefix(uri, "data:") {
return nil, errors.New("not a data uri")
}
_, data, ok := strings.Cut(uri, ",")
if !ok {
return nil, errors.New("not a data uri")
}
return base64.URLEncoding.DecodeString(data)
}
The strings.Cut function was added in Go 1.18. Use strings.Index to cut on comma in earlier versions of Go:
func decode(uri string) ([]byte, error) {
if !strings.HasPrefix(uri, "data:") {
return nil, errors.New("not a data uri")
}
i := strings.Index(uri, ",")
if i < 0 {
return nil, errors.New("not a data uri")
}
return base64.URLEncoding.DecodeString(uri[i+1:])
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论