本文整理汇总了Golang中encoding/base64.NewDecoder函数的典型用法代码示例。如果您正苦于以下问题:Golang NewDecoder函数的具体用法?Golang NewDecoder怎么用?Golang NewDecoder使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewDecoder函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestDelete
// Test the delete function.
func TestDelete(t *testing.T) {
store := New()
// Add some images.
addA, _ := jpeg.Decode(base64.NewDecoder(base64.StdEncoding, strings.NewReader(imgA)))
addB, _ := jpeg.Decode(base64.NewDecoder(base64.StdEncoding, strings.NewReader(imgB)))
hashA, _ := CreateHash(addA)
hashB, _ := CreateHash(addB)
store.Add("imgA", hashA)
store.Add("imgB", hashB)
// Delete one.
store.Delete("imgA")
// Query should only return imgB.
query, _ := jpeg.Decode(base64.NewDecoder(base64.StdEncoding, strings.NewReader(imgC)))
queryHash, _ := CreateHash(query)
matches := store.Query(queryHash)
if len(matches) != 1 {
t.Errorf("Invalid query result set size, expected 1, is %d", len(matches))
return
}
if matches[0].ID != "imgB" {
t.Errorf("Query found %s but should have found imgB", matches[0].ID)
}
}
示例2: postBuild
func postBuild(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if version.LessThan("1.3") {
return fmt.Errorf("Multipart upload for build is no longer supported. Please upgrade your docker client.")
}
var (
authEncoded = r.Header.Get("X-Registry-Auth")
authConfig = &auth.AuthConfig{}
configFileEncoded = r.Header.Get("X-Registry-Config")
configFile = &auth.ConfigFile{}
job = eng.Job("build")
)
// This block can be removed when API versions prior to 1.9 are deprecated.
// Both headers will be parsed and sent along to the daemon, but if a non-empty
// ConfigFile is present, any value provided as an AuthConfig directly will
// be overridden. See BuildFile::CmdFrom for details.
if version.LessThan("1.9") && authEncoded != "" {
authJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded))
if err := json.NewDecoder(authJson).Decode(authConfig); err != nil {
// for a pull it is not an error if no auth was given
// to increase compatibility with the existing api it is defaulting to be empty
authConfig = &auth.AuthConfig{}
}
}
if configFileEncoded != "" {
configFileJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(configFileEncoded))
if err := json.NewDecoder(configFileJson).Decode(configFile); err != nil {
// for a pull it is not an error if no auth was given
// to increase compatibility with the existing api it is defaulting to be empty
configFile = &auth.ConfigFile{}
}
}
if version.GreaterThanOrEqualTo("1.8") {
job.SetenvBool("json", true)
streamJSON(job, w, true)
} else {
job.Stdout.Add(utils.NewWriteFlusher(w))
}
job.Stdin.Add(r.Body)
job.Setenv("remote", r.FormValue("remote"))
job.Setenv("t", r.FormValue("t"))
job.Setenv("q", r.FormValue("q"))
job.Setenv("nocache", r.FormValue("nocache"))
job.Setenv("rm", r.FormValue("rm"))
job.SetenvJson("authConfig", authConfig)
job.SetenvJson("configFile", configFile)
if err := job.Run(); err != nil {
if !job.Stdout.Used() {
return err
}
sf := utils.NewStreamFormatter(version.GreaterThanOrEqualTo("1.8"))
w.Write(sf.FormatError(err))
}
return nil
}
示例3: DecodeRFC2047Word
func DecodeRFC2047Word(s string) (string, error) {
fields := strings.Split(s, "?")
if len(fields) != 5 || fields[0] != "=" || fields[4] != "=" {
return "", errors.New("mail: address not RFC 2047 encoded")
}
charset, encMark := strings.ToLower(fields[1]), strings.ToLower(fields[2])
enc := text.GetEncoding(charset)
if enc == nil {
return "", fmt.Errorf("mail: charset not supported: %q", charset)
}
in := bytes.NewBufferString(fields[3])
var r io.Reader
switch encMark {
case "b":
r = base64.NewDecoder(base64.StdEncoding, in)
case "q":
r = qDecoder{r: in}
default:
return "", fmt.Errorf("mail: RFC 2047 encoding not supported: %q", encMark)
}
dec, err := ioutil.ReadAll(text.NewReader(r, enc))
if err != nil {
return "", err
}
return string(dec), err
}
示例4: decodeSecureCookie
func decodeSecureCookie(value string) (user string, session string, err os.Error) {
parts := strings.Split(value, "|", 3)
if len(parts) != 3 {
err = os.NewError("Malformed cookie value")
return
}
val := parts[0]
timestamp := parts[1]
sig := parts[2]
// Check signature
if getCookieSig([]byte(val), timestamp) != sig {
return "", "", os.NewError("Signature error, cookie is invalid")
}
// Check time stamp
ts, _ := strconv.Atoi64(timestamp)
if ts+maxAge < time.UTC().Seconds() {
return "", "", os.NewError("Cookie is outdated")
}
buf := bytes.NewBufferString(val)
encoder := base64.NewDecoder(base64.StdEncoding, buf)
res, _ := ioutil.ReadAll(encoder)
str := string(res)
lst := strings.Split(str, "!", -1)
if len(lst) != 2 {
return "", "", os.NewError("Missing !")
}
return lst[0], lst[1], nil
}
示例5: GetSecureCookie
func (ctx *Context) GetSecureCookie(name string) (string, bool) {
cookie, ok := ctx.Request.Cookies[name]
if !ok {
return "", false
}
parts := strings.Split(cookie, "|", 3)
val := parts[0]
timestamp := parts[1]
sig := parts[2]
if getCookieSig([]byte(val), timestamp) != sig {
return "", false
}
ts, _ := strconv.Atoi64(timestamp)
if time.Seconds()-31*86400 > ts {
return "", false
}
buf := bytes.NewBufferString(val)
encoder := base64.NewDecoder(base64.StdEncoding, buf)
res, _ := ioutil.ReadAll(encoder)
return string(res), true
}
示例6: getImagesSearch
func (s *Server) getImagesSearch(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
var (
config *cliconfig.AuthConfig
authEncoded = r.Header.Get("X-Registry-Auth")
headers = map[string][]string{}
)
if authEncoded != "" {
authJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded))
if err := json.NewDecoder(authJson).Decode(&config); err != nil {
// for a search it is not an error if no auth was given
// to increase compatibility with the existing api it is defaulting to be empty
config = &cliconfig.AuthConfig{}
}
}
for k, v := range r.Header {
if strings.HasPrefix(k, "X-Meta-") {
headers[k] = v
}
}
query, err := s.daemon.RegistryService.Search(r.Form.Get("term"), config, headers)
if err != nil {
return err
}
return json.NewEncoder(w).Encode(query.Results)
}
示例7: getImagesSearch
func getImagesSearch(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
var (
authEncoded = r.Header.Get("X-Registry-Auth")
authConfig = ®istry.AuthConfig{}
metaHeaders = map[string][]string{}
)
if authEncoded != "" {
authJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded))
if err := json.NewDecoder(authJson).Decode(authConfig); err != nil {
// for a search it is not an error if no auth was given
// to increase compatibility with the existing api it is defaulting to be empty
authConfig = ®istry.AuthConfig{}
}
}
for k, v := range r.Header {
if strings.HasPrefix(k, "X-Meta-") {
metaHeaders[k] = v
}
}
var job = eng.Job("search", r.Form.Get("term"))
job.SetenvJson("metaHeaders", metaHeaders)
job.SetenvJson("authConfig", authConfig)
streamJSON(job, w, false)
return job.Run()
}
示例8: postImagesCreate
// Creates an image from Pull or from Import
func postImagesCreate(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
var (
image = r.Form.Get("fromImage")
repo = r.Form.Get("repo")
tag = r.Form.Get("tag")
job *engine.Job
)
authEncoded := r.Header.Get("X-Registry-Auth")
authConfig := ®istry.AuthConfig{}
if authEncoded != "" {
authJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded))
if err := json.NewDecoder(authJson).Decode(authConfig); err != nil {
// for a pull it is not an error if no auth was given
// to increase compatibility with the existing api it is defaulting to be empty
authConfig = ®istry.AuthConfig{}
}
}
if image != "" { //pull
if tag == "" {
image, tag = parsers.ParseRepositoryTag(image)
}
metaHeaders := map[string][]string{}
for k, v := range r.Header {
if strings.HasPrefix(k, "X-Meta-") {
metaHeaders[k] = v
}
}
job = eng.Job("pull", image, tag)
job.SetenvBool("parallel", version.GreaterThan("1.3"))
job.SetenvJson("metaHeaders", metaHeaders)
job.SetenvJson("authConfig", authConfig)
} else { //import
if tag == "" {
repo, tag = parsers.ParseRepositoryTag(repo)
}
job = eng.Job("import", r.Form.Get("fromSrc"), repo, tag)
job.Stdin.Add(r.Body)
job.SetenvList("changes", r.Form["changes"])
}
if version.GreaterThan("1.0") {
job.SetenvBool("json", true)
streamJSON(job, w, true)
} else {
job.Stdout.Add(utils.NewWriteFlusher(w))
}
if err := job.Run(); err != nil {
if !job.Stdout.Used() {
return err
}
sf := utils.NewStreamFormatter(version.GreaterThan("1.0"))
w.Write(sf.FormatError(err))
}
return nil
}
示例9: TestUploadingBinary
func TestUploadingBinary(t *testing.T) {
if FB_TEST_VALID_ACCESS_TOKEN == "" {
t.Skipf("skip this case as we don't have a valid access token.")
}
buf := bytes.NewBufferString(FB_TEST_BINARY_JPG_FILE)
reader := base64.NewDecoder(base64.StdEncoding, buf)
session := &Session{}
session.SetAccessToken(FB_TEST_VALID_ACCESS_TOKEN)
result, e := session.Api("/me/photos", POST, Params{
"message": "Test photo from https://github.com/huandu/facebook",
"source": Data("my_profile.jpg", reader),
})
if e != nil {
t.Fatalf("cannot create photo on my timeline. [e:%v]", e)
}
var id string
e = result.DecodeField("id", &id)
if e != nil {
t.Fatalf("facebook should return photo id on success. [e:%v]", e)
}
t.Logf("newly created photo id is %v", id)
}
示例10: LoadSharedFilesAscii
// LoadSharedFilesAscii loads an ASCII-encoded .sia file into the renter. It
// returns the nicknames of the loaded files.
func (r *Renter) LoadSharedFilesAscii(asciiSia string) ([]string, error) {
lockID := r.mu.Lock()
defer r.mu.Unlock(lockID)
dec := base64.NewDecoder(base64.URLEncoding, bytes.NewBufferString(asciiSia))
return r.loadSharedFiles(dec)
}
示例11: main
func main() {
var r io.Reader
r = strings.NewReader(data)
r = base64.NewDecoder(base64.StdEncoding, r)
r, _ = gzip.NewReader(r)
io.Copy(os.Stdout, r)
}
示例12: GetPlayback
func GetPlayback(base64Playback string) *js.Object {
var p engine.Playback
buf := bytes.NewReader([]byte(base64Playback))
r := base64.NewDecoder(base64.StdEncoding, buf)
gob.NewDecoder(r).Decode(&p)
return js.MakeWrapper(&p)
}
示例13: statContainerPath
func (b *Builder) statContainerPath(container, path string) (*containerPathStat, error) {
query := make(url.Values, 1)
query.Set("path", filepath.ToSlash(path)) // Normalize the paths used in the API.
urlPath := fmt.Sprintf("/containers/%s/archive?%s", container, query.Encode())
req, err := http.NewRequest("HEAD", b.client.URL.String()+urlPath, nil)
if err != nil {
return nil, fmt.Errorf("unable to prepare request: %s", err)
}
resp, err := b.client.HTTPClient.Do(req)
if err != nil {
return nil, fmt.Errorf("unable to make request: %s", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("request failed with status code: %d", resp.StatusCode)
}
encodedStat := resp.Header.Get("X-Docker-Container-Path-Stat")
statDecoder := base64.NewDecoder(base64.StdEncoding, strings.NewReader(encodedStat))
var stat containerPathStat
if err = json.NewDecoder(statDecoder).Decode(&stat); err != nil {
return nil, fmt.Errorf("unable to decode container path stat header: %s", err)
}
return &stat, nil
}
示例14: DecompressOperationParam
// Decompress the parameters stored within an operation
func (op *Operation) DecompressOperationParam() (err error) {
defer func() {
if e := recover(); e != nil {
err = fmt.Errorf("DecompressOperationParam() -> %v", e)
}
}()
if !op.IsCompressed {
return nil
}
pstr, ok := op.Parameters.(string)
if !ok {
panic("Compressed parameter was not a string")
}
b := bytes.NewBuffer([]byte(pstr))
rb64 := base64.NewDecoder(base64.StdEncoding, b)
r, err := gzip.NewReader(rb64)
if err != nil {
panic(err)
}
rb, err := ioutil.ReadAll(r)
if err != nil {
panic(err)
}
err = json.Unmarshal(rb, &op.Parameters)
if err != nil {
panic(err)
}
op.IsCompressed = false
return
}
示例15: Decode
// trim(url_base64(json(token))) + "." + hex(hmac-sha256(base64_str))
func (token *Token) Decode(tokenBytes []byte) error {
const signatureLen = 64 // hmac-sha256
bytesArray := bytes.Split(tokenBytes, tokenBytesSplitSep)
if len(bytesArray) < 2 {
return errors.New("invalid token bytes")
}
// 验证签名
signatrue := make([]byte, signatureLen)
Hash := hmac.New(sha256.New, securitykey.Key)
Hash.Write(bytesArray[0])
hex.Encode(signatrue, Hash.Sum(nil))
if !bytes.Equal(signatrue, bytesArray[1]) {
return errors.New("invalid token bytes, signature mismatch")
}
// 解码
temp := signatrue[:4] // signatrue 不再使用, 利用其空间
copy(temp, tokenBytes[len(bytesArray[0]):]) // 保护 tokenBytes
defer func() {
copy(tokenBytes[len(bytesArray[0]):], temp) // 恢复 tokenBytes
token.Signatrue = string(bytesArray[1])
}()
base64Bytes := base64Pad(bytesArray[0])
base64Decoder := base64.NewDecoder(base64.URLEncoding, bytes.NewReader(base64Bytes))
return json.NewDecoder(base64Decoder).Decode(token)
}