File: context.go

package info (click to toggle)
golang-github-manyminds-api2go 1.0-RC2%2Bgit20161229.31.dc368bb-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 484 kB
  • ctags: 488
  • sloc: sh: 23; makefile: 3
file content (80 lines) | stat: -rw-r--r-- 1,793 bytes parent folder | download | duplicates (3)
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package api2go

import (
	"context"
	"time"
)

// APIContextAllocatorFunc to allow custom context implementations
type APIContextAllocatorFunc func(*API) APIContexter

// APIContexter embedding context.Context and requesting two helper functions
type APIContexter interface {
	context.Context
	Set(key string, value interface{})
	Get(key string) (interface{}, bool)
	Reset()
}

// APIContext api2go context for handlers, nil implementations related to Deadline and Done.
type APIContext struct {
	keys map[string]interface{}
}

// Set a string key value in the context
func (c *APIContext) Set(key string, value interface{}) {
	if c.keys == nil {
		c.keys = make(map[string]interface{})
	}
	c.keys[key] = value
}

// Get a key value from the context
func (c *APIContext) Get(key string) (value interface{}, exists bool) {
	if c.keys != nil {
		value, exists = c.keys[key]
	}
	return
}

// Reset resets all values on Context, making it safe to reuse
func (c *APIContext) Reset() {
	c.keys = nil
}

// Deadline implements net/context
func (c *APIContext) Deadline() (deadline time.Time, ok bool) {
	return
}

// Done implements net/context
func (c *APIContext) Done() <-chan struct{} {
	return nil
}

// Err implements net/context
func (c *APIContext) Err() error {
	return nil
}

// Value implements net/context
func (c *APIContext) Value(key interface{}) interface{} {
	if keyAsString, ok := key.(string); ok {
		val, _ := c.Get(keyAsString)
		return val
	}
	return nil
}

// Compile time check
var _ APIContexter = &APIContext{}

// ContextQueryParams fetches the QueryParams if Set
func ContextQueryParams(c *APIContext) map[string][]string {
	qp, ok := c.Get("QueryParams")
	if ok == false {
		qp = make(map[string][]string)
		c.Set("QueryParams", qp)
	}
	return qp.(map[string][]string)
}