File: context.go

package info (click to toggle)
golang-ariga-sqlcomment 0.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 320 kB
  • sloc: makefile: 2
file content (57 lines) | stat: -rw-r--r-- 1,440 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package sqlcomment

import (
	"context"
)

type (
	// ctxOptions allows injecting runtime options.
	ctxOptions struct {
		skip bool // i.e. skip entry.
		tags Tags
	}
	ctxKeyType struct{}
)

var ctxOptionsKey ctxKeyType

// Skip returns a new Context that tells the Driver
// to skip the commenting on Query.
//
//	client.T.Query().All(sqlcomment.Skip(ctx))
//
func Skip(ctx context.Context) context.Context {
	c, ok := ctx.Value(ctxOptionsKey).(*ctxOptions)
	if !ok {
		return context.WithValue(ctx, ctxOptionsKey, &ctxOptions{skip: true})
	}
	c.skip = true
	return ctx
}

// WithTag stores the key and val pair on the context.
// for example, if you want to add `route` tag to your SQL comment, put the url path on request context:
//	middleware := func(next http.Handler) http.Handler {
//		fn := func(w http.ResponseWriter, r *http.Request) {
//			ctx := sqlcomment.WithTag(r.Context(), "route", r.URL.Path)
//			next.ServeHTTP(w, r.WithContext(ctx))
//		}
//		return http.HandlerFunc(fn)
//	}
func WithTag(ctx context.Context, key, val string) context.Context {
	t, ok := ctx.Value(ctxOptionsKey).(*ctxOptions)
	if !ok {
		return context.WithValue(ctx, ctxOptionsKey, &ctxOptions{tags: Tags{key: val}})
	}
	t.tags[key] = val
	return ctx
}

// FromContext returns the tags stored in ctx, if any.
func FromContext(ctx context.Context) Tags {
	t, ok := ctx.Value(ctxOptionsKey).(*ctxOptions)
	if !ok {
		return Tags{}
	}
	return t.tags
}