Open9
Go Code Snippet
Base64 エンコード・デコード
package main
import (
"encoding/base64"
"fmt"
)
func main() {
src := []byte("Hello World")
enc := base64.StdEncoding.EncodeToString(src)
fmt.Println(enc)
// => SGVsbG8gV29ybGQ=
}
package main
import (
"encoding/base64"
"fmt"
"log"
)
func main() {
src := "SGVsbG8gV29ybGQ="
dec, err := base64.StdEncoding.DecodeString(src)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(dec))
// => Hello World
}
Slice 重複排除
package main
import (
"fmt"
"slices"
)
func main() {
strs := []string{"A", "B", "C", "A", "A", "D", "B", "E", "F"}
slices.Sort(strs)
unique := slices.Compact(strs)
fmt.Printf("%+v\n", unique)
// => [A B C D E F]
}
暗号化・復号化
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"io"
)
func main() {
plainText := []byte("Bob loves Alice. But Alice hate Bob...")
key := []byte("passw0rdpassw0rdpassw0rdpassw0rd")
// Create new AES cipher block
block, err := aes.NewCipher(key)
if err != nil {
fmt.Printf("err: %s\n", err)
}
// Create IV
cipherText := make([]byte, aes.BlockSize+len(plainText))
iv := cipherText[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
fmt.Printf("err: %s\n", err)
}
// Encrypt
encryptStream := cipher.NewCTR(block, iv)
encryptStream.XORKeyStream(cipherText[aes.BlockSize:], plainText)
fmt.Printf("Cipher text: %x \n", cipherText)
// Decrpt
decryptedText := make([]byte, len(cipherText[aes.BlockSize:]))
decryptStream := cipher.NewCTR(block, cipherText[:aes.BlockSize])
decryptStream.XORKeyStream(decryptedText, cipherText[aes.BlockSize:])
fmt.Printf("Decrypted text: %s\n", string(decryptedText))
}
byte slice <-> io.Reader
package main
import (
"bytes"
"io"
)
func main() {
bt := []byte("hello")
reader := bytes.NewReader(bt)
bts, err := io.ReadAll(reader)
if err != nil {
panic(err)
}
println(string(bts))
}
JSON エンコード・デコード
package main
import (
"bytes"
"encoding/json"
"fmt"
"os"
)
type JSON struct {
Field string `json:"field"`
}
func main() {
f, err := os.Open("input.json")
if err != nil {
panic(err)
}
defer func() {
if err := f.Close(); err != nil {
panic(err)
}
}()
var j JSON
if err := json.NewDecoder(f).Decode(&j); err != nil {
panic(err)
}
fmt.Printf("%+v\n", j)
var b bytes.Buffer
if err := json.NewEncoder(&b).Encode(j); err != nil {
panic(err)
}
fmt.Println(b.String())
}
JSON マーシャル・アンマーシャル
package main
import (
"encoding/json"
"fmt"
)
type JSON struct {
Field string `json:"field"`
}
func main() {
s := `{"field": "field"}`
var j JSON
if err := json.Unmarshal([]byte(s), &j); err != nil {
panic(err)
}
fmt.Printf("%+v\n", j)
b, err := json.Marshal(j)
if err != nil {
panic(err)
}
fmt.Println(string(b))
}
おまじない
構造体がインターフェイスを満たしているかをチェックするおまじない
package main
import "context"
type Interface interface {
Do(ctx context.Context) error
}
var _ Interface = (*Struct)(nil)
type Struct struct{}
// Do implements Interface.
func (str *Struct) Do(ctx context.Context) error {
panic("unimplemented")
}
ジェネリクスを使いたい場合
package main
import "context"
type Interface[T any] interface {
Do(ctx context.Context) (*T, error)
}
var _ Interface[any] = (*Struct[any])(nil)
type Struct[T any] struct{}
// Do implements Interface.
func (s *Struct[T]) Do(ctx context.Context) (*T, error) {
panic("unimplemented")
}