Search code examples
gobase64data-uri

How can I remove the base64 header from a data URI with Go?


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?


Solution

  • 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:])
    }