Last active
December 3, 2021 00:45
-
-
Save Mo3g4u/0d1ea3dbd15dbe6ec3f7245dbc2ca955 to your computer and use it in GitHub Desktop.
go decode sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"encoding/base64" | |
"io" | |
"os" | |
"strings" | |
"golang.org/x/sync/errgroup" | |
) | |
const Message = "44GC44GE44GG44GI44GK" | |
// ただのデコード | |
/* | |
func main() { | |
data, err := base64.StdEncoding.DecodeString(Message) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println(string(data)) | |
} | |
*/ | |
// デコードのpipe版 | |
/* | |
func main() { | |
source := strings.NewReader(Message) | |
decoder := base64.NewDecoder(base64.StdEncoding, source) | |
pr, pw := io.Pipe() | |
go func() { | |
_, err := io.Copy(pw, decoder) | |
if err != nil { | |
pw.CloseWithError(err) | |
} else { | |
pw.Close() | |
} | |
}() | |
io.Copy(os.Stdout, pr) | |
} | |
*/ | |
// デコードのpipe版 error group 利用 | |
func main() { | |
source := strings.NewReader(Message) | |
decoder := base64.NewDecoder(base64.StdEncoding, source) | |
eg, _ := errgroup.WithContext(context.Background()) | |
pr, pw := io.Pipe() | |
eg.Go(func() error { | |
defer func() { | |
if err := pw.Close(); err != nil { | |
panic("PipeWriterを閉じれません") | |
} | |
}() | |
_, err := io.Copy(pw, decoder) | |
if err != nil { | |
return err | |
} | |
return nil | |
}) | |
io.Copy(os.Stdout, pr) | |
if err := eg.Wait(); err != nil { | |
panic(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment