你好!以下是你要翻译的内容: 如何使用Go语言从数据URI中删除base64头部?

huangapple go评论82阅读模式
英文:

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, &quot;data:&quot;) {
	return nil, errors.New(&quot;not a data uri&quot;)
  }
  _, data, ok := strings.Cut(uri, &quot;,&quot;)
  if !ok {
	return nil, errors.New(&quot;not a data uri&quot;)
  }
  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, &quot;data:&quot;) {
		return nil, errors.New(&quot;not a data uri&quot;)
	}
	i := strings.Index(uri, &quot;,&quot;)
	if i &lt; 0 {
		return nil, errors.New(&quot;not a data uri&quot;)
	}
	return base64.URLEncoding.DecodeString(uri[i+1:])
}

huangapple
  • 本文由 发表于 2022年4月3日 03:34:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/71720659.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定