0
0

More than 3 years have passed since last update.

go修行19日目 HMAC

Last updated at Posted at 2020-07-11

HAMC

package main

import (
    "crypto/hmac"
    "crypto/sha256"
    "encoding/hex"
    "fmt"
)

// サーバサイドで正しいクライアントのものかを判定する
var DB = map[string]string{
    "User1Key": "User1Secret",
    "User2Key": "User2Secret",
}

func Server(apiKey, sign string, data []byte) {
    apiSecret := DB[apiKey]
    // sha256の同じアルゴリズムを使う
    h := hmac.New(sha256.New, []byte(apiSecret))
    h.Write(data)
    expectedHMAC := hex.EncodeToString(h.Sum(nil))
    // 同じアルゴリズムでエンコードしたhmacが一致するかを確認
    fmt.Println(sign == expectedHMAC)
}

func main() {
    const apiKey = "User1Key"
    const apiSecret = "User1Secret"

    data := []byte("data")
    h := hmac.New(sha256.New, []byte(apiSecret))
    h.Write(data)
    sign := hex.EncodeToString(h.Sum(nil))

    // ハッシュ値
    fmt.Println(sign)

    // サーバに投げる
    Server(apiKey, sign, data)
}

出力

076b55e7f7e12624b4569f162302f1e36c11fb3a9134889267748de14a84b996
true

Semaphore

  • goroutineが走る数を限定することができる
go get golang.org/x/sync/semaphore
package main

import (
    "context"
    "fmt"
    "time"

    "golang.org/x/sync/semaphore"
)

// 並行実行できるプロセス数を制限
var s *semaphore.Weighted = semaphore.NewWeighted(1)


func longProcess(ctx context.Context){
    // 処理が並行している場合ロックをかけることができる
    isAcquire := s.TryAcquire(1)
    if !isAcquire{
        fmt.Println("Could not get lock")
        return
    }

    defer s.Release(1)
    fmt.Println("Wait...")
    time.Sleep(1 * time.Second)
    fmt.Println("Done")
}

func main() {
    ctx := context.TODO()
    go longProcess(ctx)
    go longProcess(ctx)
    go longProcess(ctx)
    time.Sleep(5 * time.Second)
}
Could not get lock
Could not get lock
Wait...
Done

ini

  • configファイルを読み込む
  • サーバの設定値など

package main

import (
    "fmt"

    "github.com/go-ini/ini"
)

type ConfigList struct{
    Port int
    DbName string
    SQLDriver string
}

var Config ConfigList

// main関数が呼ばれる前に設定を呼び込む
func init(){
    cfg, _ := ini.Load("config.ini")
    Config = ConfigList{
        Port: cfg.Section("web").Key("port").MustInt(),
        DbName: cfg.Section("db").Key("name").MustString("example.sql"),
        SQLDriver: cfg.Section("db").Key("driver").String(),
    }
}

func main(){
    fmt.Printf("%T %v\n", Config.Port, Config.Port)
    fmt.Printf("%T %v\n", Config.DbName, Config.DbName)
    fmt.Printf("%T %v\n", Config.SQLDriver, Config.SQLDriver)

}
config.ini
[web]
port = 8080

[db]
name = stockdata.sql
driver = sqlite3

出力

int 8080
string stockdata.sql
string sqlite3

教材

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0