LoginSignup
2
2

More than 5 years have passed since last update.

golang context 簡単な使い方

Last updated at Posted at 2018-09-28

メモです

type tokenKey int

const (
    ctxTest tokenKey = 0
)


type App struct {
   Cache *cache.Cache
}

// uuidでtoken作成
func makeCsrfToken() string {
    h := md5.New()
    io.WriteString(h, uuid.New().String())
    token := fmt.Sprintf("%x", h.Sum(nil))
    return token
}

func (a *App) csrf(r *http.Request) {
    token := makeCsrfToken()
    ctx := context.WithValue(r.Context(), ctxTest, token)
    r.WithContext(ctx)
    a.Cache.Set(token, struct{}{}, cache.DefaultExpiration)
}
func (a *App) Authorize(w http.ResponseWriter, r *http.Request) {
    ...
    ...
    a.csrf(r)
    // 取り出す
    csrfToken := r.Context().Value(ctxTest).(string)
}
2
2
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
2
2