func NewClient(network, address string) *Client {
	return NewClientWithDialer(network, address, new(net.Dialer))
}

func NewClient ( network , address string ) * Client { return NewClientWithDialer ( network , address , new ( net . Dialer ) ) }

// NewClient creates a new Livestatus client instance.

NewClient creates a new Livestatus client instance .


func NewClientWithDialer(network, address string, dialer *net.Dialer) *Client {
	return &Client{
		network: network,
		address: address,
		dialer:  dialer,
	}
}

func NewClientWithDialer ( network , address string , dialer * net . Dialer ) * Client { return & Client { network : network , address : address , dialer : dialer , } }

// NewClientWithDialer creates a new Livestatus client instance using a provided network dialer.

NewClientWithDialer creates a new Livestatus client instance using a provided network dialer .


func (c *Client) Exec(r Request) (*Response, error) {
	var err error

	// Initialize connection if none available
	if c.conn == nil {
		c.conn, err = c.dialer.Dial(c.network, c.address)
		if err != nil {
			return nil, err
		}

		if r.keepAlive() {
			switch c.network {
			case "tcp":
				c.conn.(*net.TCPConn).SetKeepAlive(true)
			}
		} else {
			defer c.Close()
		}
	}

	return r.handle(c.conn)
}

// Exec executes a given Livestatus query.

Exec executes a given Livestatus query .


func xtoi2(s string, e byte) (byte, bool) {
	if len(s) > 2 && s[2] != e {
		return 0, false
	}
	n, ei, ok := xtoi(s[:2], 0)
	return byte(n), ok && ei == 2
}

func xtoi2 ( s string , e byte ) ( byte , bool ) { if len ( s ) > 2 && s [ 2 ] != e { return 0 , false } n , ei , ok := xtoi ( s [ : 2 ] , 0 ) return byte ( n ) , ok && ei == 2 }

// xtoi2 converts the next two hex digits of s into a byte.
// If s is longer than 2 bytes then the third byte must be e.
// If the first two bytes of s are not hex digits or the third byte
// does not match e, false is returned.

xtoi2 converts the next two hex digits of s into a byte . If s is longer than 2 bytes then the third byte must be e . If the first two bytes of s are not hex digits or the third byte does not match e false is returned .


func (address HardwareAddr) Mask(mask []byte) []byte {
	n := len(address)
	if n != len(mask) {
		return nil
	}
	out := make([]byte, n)
	for i := 0; i < n; i++ {
		out[i] = address[i] & mask[i]
	}
	return out
}

func ( address HardwareAddr ) Mask ( mask [ ] byte ) [ ] byte { n := len ( address ) if n != len ( mask ) { return nil } out := make ( [ ] byte , n ) for i := 0 ; i < n ; i ++ { out [ i ] = address [ i ] & mask [ i ] } return out }

// Mask returns the result of masking the address with mask.

Mask returns the result of masking the address with mask .


func New(file string) *OuiDb {
	db := &OuiDb{}
	if err := db.Load(file); err != nil {
		return nil
	}
	return db
}

func New ( file string ) * OuiDb { db := & OuiDb { } if err := db . Load ( file ) ; err != nil { return nil } return db }

// New returns a new OUI database loaded from the specified file.

New returns a new OUI database loaded from the specified file .


func (m *OuiDb) Lookup(address HardwareAddr) *AddressBlock {
	for _, block := range m.Blocks {
		if block.Contains(address) {
			return &block
		}
	}

	return nil
}

func ( m * OuiDb ) Lookup ( address HardwareAddr ) * AddressBlock { for _ , block := range m . Blocks { if block . Contains ( address ) { return & block } } return nil }

// Lookup finds the OUI the address belongs to


func (m *OuiDb) VendorLookup(s string) (string, error) {
	addr, err := net.ParseMAC(s)
	if err != nil {
		return "", err
	}
	block := m.Lookup(HardwareAddr(addr))
	if block == nil {
		return "", ErrInvalidMACAddress
	}
	return block.Organization, nil
}

func ( m * OuiDb ) VendorLookup ( s string ) ( string , error ) { addr , err := net . ParseMAC ( s ) if err != nil { return " " , err } block := m . Lookup ( HardwareAddr ( addr ) ) if block == nil { return " " , ErrInvalidMACAddress } return block . Organization , nil }

// VendorLookup obtains the vendor organization name from the MAC address s.

VendorLookup obtains the vendor organization name from the MAC address s .


func (b *AddressBlock) Contains(address HardwareAddr) bool {
	//fmt.Println("%v %v %v %v", b.Oui, len(b.Oui), address.Mask(CIDRMask(b.Mask, len(b.Oui)*8)), CIDRMask(b.Mask, len(b.Oui)*8))

	return (bytes.Equal(address.Mask(CIDRMask(b.Mask, len(b.Oui)*8)), b.Oui))
}

// Contains reports whether the mac address belongs to the OUI


func ThrottledReader(
	ctx context.Context,
	r io.Reader,
	throttle Throttle) io.Reader {
	return &throttledReader{
		ctx:      ctx,
		wrapped:  r,
		throttle: throttle,
	}
}

func ThrottledReader ( ctx context . Context , r io . Reader , throttle Throttle ) io . Reader { return & throttledReader { ctx : ctx , wrapped : r , throttle : throttle , } }

// Create a reader that limits the bandwidth of reads made from r according to
// the supplied throttler. Reads are assumed to be made under the supplied
// context.

Create a reader that limits the bandwidth of reads made from r according to the supplied throttler . Reads are assumed to be made under the supplied context .


func NewThrottledBucket(
	opThrottle Throttle,
	egressThrottle Throttle,
	wrapped gcs.Bucket) (b gcs.Bucket) {
	b = &throttledBucket{
		opThrottle:     opThrottle,
		egressThrottle: egressThrottle,
		wrapped:        wrapped,
	}

	return
}

func NewThrottledBucket ( opThrottle Throttle , egressThrottle Throttle , wrapped gcs . Bucket ) ( b gcs . Bucket ) { b = & throttledBucket { opThrottle : opThrottle , egressThrottle : egressThrottle , wrapped : wrapped , } return }

// Create a bucket that limits the rate at which it calls the wrapped bucket
// using opThrottle, and limits the bandwidth with which it reads from the
// wrapped bucket using egressThrottle.

Create a bucket that limits the rate at which it calls the wrapped bucket using opThrottle and limits the bandwidth with which it reads from the wrapped bucket using egressThrottle .


func NewCmdWithRunner(cmdName string, runner func()) (*CmdWithRunner, error) {
	if cmdName == "" {
		return nil, errors.New("cmdName cannot be blank")
	}

	for _, r := range cmdName {
		if unicode.IsSpace(r) {
			return nil, errors.Errorf("cmdName cannot contain whitespace: %q", cmdName)
		}
	}

	return &CmdWithRunner{
		cmdName: cmdName,
		runner:  runner,
	}, nil
}

func NewCmdWithRunner ( cmdName string , runner func ( ) ) ( * CmdWithRunner , error ) { if cmdName == " " { return nil , errors . New ( " " ) } for _ , r := range cmdName { if unicode . IsSpace ( r ) { return nil , errors . Errorf ( " " , cmdName ) } } return & CmdWithRunner { cmdName : cmdName , runner : runner , } , nil }

// NewCmdWithRunner creates a new CmdWithRunner for the provided name and runner. Returns an error if the provided name
// is not a legal command name.

NewCmdWithRunner creates a new CmdWithRunner for the provided name and runner . Returns an error if the provided name is not a legal command name .


func MustNewCmdWithRunner(cmdName string, runner func()) *CmdWithRunner {
	cmdWithRunner, err := NewCmdWithRunner(cmdName, runner)
	if err != nil {
		panic(err)
	}
	return cmdWithRunner
}

func MustNewCmdWithRunner ( cmdName string , runner func ( ) ) * CmdWithRunner { cmdWithRunner , err := NewCmdWithRunner ( cmdName , runner ) if err != nil { panic ( err ) } return cmdWithRunner }

// MustNewCmdWithRunner returns the result of NewCmdWithRunner and panics in cases where the function returns an error.

MustNewCmdWithRunner returns the result of NewCmdWithRunner and panics in cases where the function returns an error .


func importBreakPaths(file *ast.File) []string {
	var output []string

	for _, decl := range file.Decls {
		if gen, ok := decl.(*ast.GenDecl); ok && gen.Tok == token.IMPORT {
			for srcIndex, currSpec := range gen.Specs {
				if srcIndex > 0 {
					// if there was a previous element, check if the group has changed
					currGroup := importGroup(importPath(currSpec))
					prevGroup := importGroup(importPath(gen.Specs[srcIndex-1]))
					if currGroup != prevGroup {
						// if group has changed, add path to the output
						output = append(output, importPath(gen.Specs[srcIndex]))
					}
				}
			}

			// assume that only one import token block exists
			break
		}
	}

	return output
}

// importBreakPaths returns a slice that contains the import paths before which a line breaks should be inserted.

importBreakPaths returns a slice that contains the import paths before which a line breaks should be inserted .


func SelfProxyCmderSupplier() CmderSupplier {
	return func(cmd Cmd) (Cmder, error) {
		selfCmder, err := selfCmder()
		if err != nil {
			return nil, err
		}
		return CmderWithPrependedArgs(selfCmder, proxyCmd(cmd).Name()), nil
	}
}

func SelfProxyCmderSupplier ( ) CmderSupplier { return func ( cmd Cmd ) ( Cmder , error ) { selfCmder , err := selfCmder ( ) if err != nil { return nil , err } return CmderWithPrependedArgs ( selfCmder , proxyCmd ( cmd ) . Name ( ) ) , nil } }

// SelfProxyCmderSupplier returns a supplier that, given a command, re-invokes the current executable with a proxy
// version of the provided command.

SelfProxyCmderSupplier returns a supplier that given a command re - invokes the current executable with a proxy version of the provided command .


func SupplierWithPrependedArgs(s CmderSupplier, argsFunc func(cmd Cmd) []string) CmderSupplier {
	return func(cmd Cmd) (Cmder, error) {
		r, err := s(cmd)
		if err != nil {
			return nil, err
		}
		return CmderWithPrependedArgs(r, argsFunc(cmd)...), nil
	}
}

func SupplierWithPrependedArgs ( s CmderSupplier , argsFunc func ( cmd Cmd ) [ ] string ) CmderSupplier { return func ( cmd Cmd ) ( Cmder , error ) { r , err := s ( cmd ) if err != nil { return nil , err } return CmderWithPrependedArgs ( r , argsFunc ( cmd ) ... ) , nil } }

// SupplierWithPrependedArgs returns a new Supplier that invokes the provided supplier and returns the result of calling
// RunnerWithPrependedArgs on the returned runner with the result of applying the provided "argsFunc" function to the
// provided command.

SupplierWithPrependedArgs returns a new Supplier that invokes the provided supplier and returns the result of calling RunnerWithPrependedArgs on the returned runner with the result of applying the provided argsFunc function to the provided command .


func selfCmder() (Cmder, error) {
	pathToSelf, err := osext.Executable()
	if err != nil {
		return nil, errors.Wrapf(err, "failed to determine path for current executable")
	}
	return PathCmder(pathToSelf), nil
}

func selfCmder ( ) ( Cmder , error ) { pathToSelf , err := osext . Executable ( ) if err != nil { return nil , errors . Wrapf ( err , " " ) } return PathCmder ( pathToSelf ) , nil }

// selfCmder returns a Cmder that creates a command that re-invokes the currently running executable.

selfCmder returns a Cmder that creates a command that re - invokes the currently running executable .


func CmderWithPrependedArgs(r Cmder, prependedArgs ...string) Cmder {
	return &wrappedCmder{
		inner:         r,
		prependedArgs: prependedArgs,
	}
}

func CmderWithPrependedArgs ( r Cmder , prependedArgs ... string ) Cmder { return & wrappedCmder { inner : r , prependedArgs : prependedArgs , } }

// CmderWithPrependedArgs returns a new Cmder that invokes the provided Cmder, but always adds the provided
// "prependedArgs" before any user-supplied arguments. Note that if the runner being wrapped has a notion of
// "prependedArgs" itself, those arguments will precede the "prependedArgs" provided in this method.

CmderWithPrependedArgs returns a new Cmder that invokes the provided Cmder but always adds the provided prependedArgs before any user - supplied arguments . Note that if the runner being wrapped has a notion of prependedArgs itself those arguments will precede the prependedArgs provided in this method .


func NewSeeforRouter() *Seefor {
	c4 := &Seefor{}
	c4.afters = make([]After, 0)
	c4.befores = make([]Before, 0)
	c4.roots = make(map[string]*rootNode)
	c4.HandleMethodNotAllowed = true
	return c4
}

func NewSeeforRouter ( ) * Seefor { c4 := & Seefor { } c4 . afters = make ( [ ] After , 0 ) c4 . befores = make ( [ ] Before , 0 ) c4 . roots = make ( map [ string ] * rootNode ) c4 . HandleMethodNotAllowed = true return c4 }

// NewSeeforRouter for creating a new instance of Seefor router


func (c4 *Seefor) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	started := time.Now()
	c4.handleBeforeMiddlewares(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		beforeEnd := time.Now()
		if root, exist := c4.roots[req.Method]; exist {
			handler, params, route := root.match(req.URL.Path)
			if handler != nil {
				if c4.timer != nil {
					after := time.Now()
					c4.handleAfterMiddlewares(handler, w, req, params)
					c4.timer.Get(route).Accumulate(started, beforeEnd, after, time.Now())
				} else {
					c4.handleAfterMiddlewares(handler, w, req, params)
				}
				return
			}
		}
		c4.Router.handleMissing(w, req)
	}), w, req)
}

func ( c4 * Seefor ) ServeHTTP ( w http . ResponseWriter , req * http . Request ) { started := time . Now ( ) c4 . handleBeforeMiddlewares ( http . HandlerFunc ( func ( w http . ResponseWriter , req * http . Request ) { beforeEnd := time . Now ( ) if root , exist := c4 . roots [ req . Method ] ; exist { handler , params , route := root . match ( req . URL . Path ) if handler != nil { if c4 . timer != nil { after := time . Now ( ) c4 . handleAfterMiddlewares ( handler , w , req , params ) c4 . timer . Get ( route ) . Accumulate ( started , beforeEnd , after , time . Now ( ) ) } else { c4 . handleAfterMiddlewares ( handler , w , req , params ) } return } } c4 . Router . handleMissing ( w , req ) } ) , w , req ) }

// Implementing http handler interface.
// This is a override of Router.ServeHTTP for handling middlewares

Implementing http handler interface . This is a override of Router . ServeHTTP for handling middlewares


func (c4 *Seefor) Before(middleware ...Before) {
	c4.befores = append(c4.befores, middleware...)
}

func ( c4 * Seefor ) Before ( middleware ... Before ) { c4 . befores = append ( c4 . befores , middleware ... ) }

// Before is for adding middleware for running before routing


func (c4 *Seefor) After(middleware ...After) {
	c4.afters = append(c4.afters, middleware...)
}

func ( c4 * Seefor ) After ( middleware ... After ) { c4 . afters = append ( c4 . afters , middleware ... ) }

// After is for adding middleware for running after routing


func (c4 *Seefor) UseTimer(timer *Timer) *Timer {
	if timer == nil {
		if c4.timer != nil {
			return c4.timer
		}
		timer = NewTimer()
	}
	c4.timer = timer

	return c4.timer
}

func ( c4 * Seefor ) UseTimer ( timer * Timer ) * Timer { if timer == nil { if c4 . timer != nil { return c4 . timer } timer = NewTimer ( ) } c4 . timer = timer return c4 . timer }

// UseTimer set timer for meaturing endpoint performance.
// If timer is nil and no timer exists
// then a new timer will be created
// else existing timer will be returned.
// You can serve statistics internal using Timer as handler

UseTimer set timer for meaturing endpoint performance . If timer is nil and no timer exists then a new timer will be created else existing timer will be returned . You can serve statistics internal using Timer as handler


func NewRouter() *Router {
	r := &Router{}
	r.roots = make(map[string]*rootNode)
	r.HandleMethodNotAllowed = true
	return r
}

func NewRouter ( ) * Router { r := & Router { } r . roots = make ( map [ string ] * rootNode ) r . HandleMethodNotAllowed = true return r }


func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	//now := time.Now()
	if root, exist := r.roots[req.Method]; exist {
		handler, params, _ := root.match(req.URL.Path)
		if handler != nil {
			handler.ServeHTTP(w, req, params)
			//log.Println(time.Now().Sub(now))
			return
		}
	}
	r.handleMissing(w, req)
}

func
(
r
*
Router
)
ServeHTTP
(
w
http
.
ResponseWriter
,
req
*
http
.
Request
)
{
//now := time.Now()
if
root
,
exist
:=
r
.
roots
[
req
.
Method
]
;
exist
{
handler
,
params
,
_
:=
root
.
match
(
req
.
URL
.
Path
)
if
handler
!=
{
handler
.
ServeHTTP
(
w
,
req
,
params
)
//log.Println(time.Now().Sub(now))
return
}
}
r
.
handleMissing
(
w
,
req
)
}


func (r *Router) Group(path string, fn func(r *GroupRouter)) {
	gr := NewGroupRouter(r, path)
	fn(gr)
}

func ( r * Router ) Group ( path string , fn func ( r * GroupRouter ) ) { gr := NewGroupRouter ( r , path ) fn ( gr ) }

// Group takes a path which typically a prefix for an endpoint
// It will call callback function with a group router which
// you can add handler for different request methods

Group takes a path which typically a prefix for an endpoint It will call callback function with a group router which you can add handler for different request methods


func (n *routeNode) findChild(nn *routeNode) *routeNode {
	for _, c := range n.children {
		if c.path == nn.path {
			// same node
			return c
		}
	}
	return nil
}

func
(
n
*
routeNode
)
findChild
(
nn
*
routeNode
)
*
routeNode
{
for
_
,
c
:=
range
n
.
children
{
if
c
.
path
==
nn
.
path
{
// same node
return
c
}
}
return
}

// findChild finds a child node that matches the given node
// It returns nil if no node found. This is to see if
// we already have a similar node registered

findChild finds a child node that matches the given node It returns nil if no node found . This is to see if we already have a similar node registered


func (n *routeNode) insertChild(nn *routeNode) *routeNode {
	if child := n.findChild(nn); child != nil {
		return child
	}

	if n.paramChild != nil && nn.paramNode {
		// only allow one param child, unique param name
		if n.paramChild.paramName != nn.paramName {
			panic("Param name must be same for")
		}
		return n.paramChild
	}
	if nn.paramNode {
		n.paramChild = nn
	} else {
		n.children = append(n.children, nn)
	}
	return nn
}

// insertChild registers given node in the route node tree
// If there is already a similar node it will not insert new node
// The returned node is always the registered one ie either
// newly registered or the old one

insertChild registers given node in the route node tree If there is already a similar node it will not insert new node The returned node is always the registered one ie either newly registered or the old one


func (t *Timer) Get(name string) *Counter {
	if c, exist := t.routes[name]; exist {
		return c
	}
	t.mux.Lock()
	defer t.mux.Unlock()
	// could be a race so check again
	// could loose som small data but good not to
	if c, exist := t.routes[name]; exist {
		return c
	}
	t.routes[name] = &Counter{}
	t.routes[name].Min = 1<<63 - 1
	return t.routes[name]
}

// Get returns a Counter for a route.
// If there is no entry it will create a new one.
// It will lock during creation

Get returns a Counter for a route . If there is no entry it will create a new one . It will lock during creation


func (t *Timer) ServeHTTP(w http.ResponseWriter, req *http.Request) {

	req.ParseForm()
	sortBy := req.Form.Get("sort")

	stats := &Stats{}
	stats.SortBy = strings.ToLower(sortBy)
	stats.Generated = time.Now()
	stats.UpTime = fmt.Sprintf("%s", stats.Generated.Sub(t.Since))
	// Read access OK for map?
	stats.Result = make([]*Stat, 0, len(t.routes))
	for k, v := range t.routes {
		stat := &Stat{}
		stat.Route = k
		stat.Count = v.Count
		stat.Tot = v.Tot
		stat.Avg = time.Duration(int64(v.Tot) / v.Count)
		stat.AvgAfter = time.Duration(int64(v.AfterTot) / v.Count)
		stat.AvgBefore = time.Duration(int64(v.BeforeTot) / v.Count)
		stat.Max = v.Max
		stat.Min = v.Min
		stats.Result = append(stats.Result, stat)
	}
	sort.Sort(sort.Reverse(stats))
	jsonData, _ := json.Marshal(stats)
	w.Write(jsonData)
}

func
(
t
*
Timer
)
ServeHTTP
(
w
http
.
ResponseWriter
,
req
*
http
.
Request
)
{
req
.
ParseForm
(
)
sortBy
:=
req
.
Form
.
Get
(
"
"
)
stats
:=
&
Stats
{
}
stats
.
SortBy
=
strings
.
ToLower
(
sortBy
)
stats
.
Generated
=
time
.
Now
(
)
stats
.
UpTime
=
fmt
.
Sprintf
(
"
"
,
stats
.
Generated
.
Sub
(
t
.
Since
)
)
// Read access OK for map?
stats
.
Result
=
make
(
[
]
*
Stat
,
0
,
len
(
t
.
routes
)
)
for
k
,
v
:=
range
t
.
routes
{
stat
:=
&
Stat
{
}
stat
.
Route
=
k
stat
.
Count
=
v
.
Count
stat
.
Tot
=
v
.
Tot
stat
.
Avg
=
time
.
Duration
(
int64
(
v
.
Tot
)
/
v
.
Count
)
stat
.
AvgAfter
=
time
.
Duration
(
int64
(
v
.
AfterTot
)
/
v
.
Count
)
stat
.
AvgBefore
=
time
.
Duration
(
int64
(
v
.
BeforeTot
)
/
v
.
Count
)
stat
.
Max
=
v
.
Max
stat
.
Min
=
v
.
Min
stats
.
Result
=
append
(
stats
.
Result
,
stat
)
}
sort
.
Sort
(
sort
.
Reverse
(
stats
)
)
jsonData
,
_
:=
json
.
Marshal
(
stats
)
w
.
Write
(
jsonData
)
}


func main() {
	router := r2router.NewSeeforRouter()

	// basic auth for entire router
	router.Before(httpauth.SimpleBasicAuth("testuser", "testpw"))

	router.Get("/hello/:name", func(w http.ResponseWriter, r *http.Request, p r2router.Params) {
		w.Write([]byte( p.Get("name")))
	})

	http.ListenAndServe("127.0.0.1:8080", router)
}

func
main
(
)
{
router
:=
r2router
.
NewSeeforRouter
(
)
// basic auth for entire router
router
.
Before
(
httpauth
.
SimpleBasicAuth
(
"
"
,
"
"
)
)
router
.
Get
(
"
"
,
func
(
w
http
.
ResponseWriter
,
r
*
http
.
Request
,
p
r2router
.
Params
)
{
w
.
Write
(
[
]
byte
(
p
.
Get
(
"
"
)
)
)
}
)
http
.
ListenAndServe
(
"
"
,
router
)
}

// Example how to use basic auth together with r2router


func NewGroupRouter(r *Router, path string) *GroupRouter {
	gr := &GroupRouter{}
	gr.router = r
	gr.path = strings.TrimRight(path, "/")
	return gr
}

func NewGroupRouter ( r * Router , path string ) * GroupRouter { gr := & GroupRouter { } gr . router = r gr . path = strings . TrimRight ( path , " " ) return gr }

// NewGroupRouter return GroupRouter which is a helper
// to construct a group of endpoints, such example could
// be API-version or different methods for an endpoint
// You should always use router.Group instead of using this directly

NewGroupRouter return GroupRouter which is a helper to construct a group of endpoints such example could be API - version or different methods for an endpoint You should always use router . Group instead of using this directly


func RouteMiddleware(next r2router.HandlerFunc) r2router.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request, p r2router.Params) {
		p.AppSet("say", "Hello")
		next(w, r, p)
	}
}

func RouteMiddleware ( next r2router . HandlerFunc ) r2router . HandlerFunc { return func ( w http . ResponseWriter , r * http . Request , p r2router . Params ) { p . AppSet ( " " , " " ) next ( w , r , p ) } }


func RouteHandlerFunc(next http.HandlerFunc) r2router.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request, _ r2router.Params) {
		next(w, r)
	}
}

func RouteHandlerFunc ( next http . HandlerFunc ) r2router . HandlerFunc { return func ( w http . ResponseWriter , r * http . Request , _ r2router . Params ) { next ( w , r ) } }


func RectFromSphere(c Vec3, r float32) Rectangle {
	return RectWHD(c[0]-r, c[1]-r, c[2]-r, 2*r, 2*r, 2*r)
}

func RectFromSphere ( c Vec3 , r float32 ) Rectangle { return RectWHD ( c [ 0 ] - r , c [ 1 ] - r , c [ 2 ] - r , 2 * r , 2 * r , 2 * r ) }

// RectFromSphere returns the minimum rectangle that contains the circle of
// center c and radius r.

RectFromSphere returns the minimum rectangle that contains the circle of center c and radius r .


func CopyRect(r Rectangle) Rectangle {
	r1 := NewRect()
	r1.Min.Assign(r.Min)
	r1.Max.Assign(r.Max)
	return r1
}

func CopyRect ( r Rectangle ) Rectangle { r1 := NewRect ( ) r1 . Min . Assign ( r . Min ) r1 . Max . Assign ( r . Max ) return r1 }

// CopyRect allocates and returns a new Rectangle that is the copy of r.

CopyRect allocates and returns a new Rectangle that is the copy of r .


func (r Rectangle) Size() Vec3 {
	return Vec3{
		r.Max[0] - r.Min[0],
		r.Max[1] - r.Min[1],
		r.Max[2] - r.Min[2],
	}
}

func ( r Rectangle ) Size ( ) Vec3 { return Vec3 { r . Max [ 0 ] - r . Min [ 0 ] , r . Max [ 1 ] - r . Min [ 1 ] , r . Max [ 2 ] - r . Min [ 2 ] , } }

// Size returns r's width, height and depth.

Size returns r s width height and depth .


func (r Rectangle) Overlaps(s Rectangle) bool {
	return !r.Empty() && !s.Empty() &&
		r.Min[0] < s.Max[0] && s.Min[0] < r.Max[0] &&
		r.Min[1] < s.Max[1] && s.Min[1] < r.Max[1] &&
		r.Min[2] < s.Max[2] && s.Min[2] < r.Max[2]
}

func ( r Rectangle ) Overlaps ( s Rectangle ) bool { return ! r . Empty ( ) && ! s . Empty ( ) && r . Min [ 0 ] < s . Max [ 0 ] && s . Min [ 0 ] < r . Max [ 0 ] && r . Min [ 1 ] < s . Max [ 1 ] && s . Min [ 1 ] < r . Max [ 1 ] && r . Min [ 2 ] < s . Max [ 2 ] && s . Min [ 2 ] < r . Max [ 2 ] }

// Overlaps reports whether r and s have a non-empty intersection.

Overlaps reports whether r and s have a non - empty intersection .


func (r Rectangle) String() string {
	return fmt.Sprintf("(Min:%v,Max:%v)", r.Min, r.Max)
}

func ( r Rectangle ) String ( ) string { return fmt . Sprintf ( " " , r . Min , r . Max ) }

// String returns a string representation of r.

String returns a string representation of r .


func (r Rectangle) Dx() float64 {
	return r.Max.X - r.Min.X
}

func ( r Rectangle ) Dx ( ) float64 { return r . Max . X - r . Min . X }


func (r Rectangle) Dy() float64 {
	return r.Max.Y - r.Min.Y
}

func ( r Rectangle ) Dy ( ) float64 { return r . Max . Y - r . Min . Y }


func (r Rectangle) In(s Rectangle) bool {
	if r.Empty() {
		return true
	}
	// Note that r.Max is an exclusive bound for r, so that r.In(s)
	// does not require that r.Max.In(s).
	return s.Min[0] <= r.Min[0] && r.Max[0] <= s.Max[0] &&
		s.Min[1] <= r.Min[1] && r.Max[1] <= s.Max[1]
}

// In reports whether Rectangle r is contained in s.

In reports whether Rectangle r is contained in s .


func Approx(x, y float64) bool {
	eps := epsilon64 * 100
	return math.Abs(x-y) < eps*(1.0+math.Max(math.Abs(x), math.Abs(y)))
}

func Approx ( x , y float64 ) bool { eps := epsilon64 * 100 return math . Abs ( x - y ) < eps * ( 1.0 + math . Max ( math . Abs ( x ) , math . Abs ( y ) ) ) }


func ApproxEpsilon(x, y float64, eps float64) bool {
	return math.Abs(x-y) < eps*(1.0+math.Max(math.Abs(x), math.Abs(y)))
}

func ApproxEpsilon ( x , y float64 , eps float64 ) bool { return math . Abs ( x - y ) < eps * ( 1.0 + math . Max ( math . Abs ( x ) , math . Abs ( y ) ) ) }

// ApproxEpsilon returns true if x ~= y, using provided epsilon value.

ApproxEpsilon returns true if x ~ = y using provided epsilon value .


func (v Vec3) SetXYZ(x, y, z float32) {
	v[0] = x
	v[1] = y
	v[2] = z
}

func ( v Vec3 ) SetXYZ ( x , y , z float32 ) { v [ 0 ] = x v [ 1 ] = y v [ 2 ] = z }

// SetXYZ sets the 3 components at once.


func Vec3Dist2DSqr(v1, v2 Vec3) float32 {
	dx := v1[0] - v2[0]
	dz := v1[2] - v2[2]
	return dx*dx + dz*dz
}

func Vec3Dist2DSqr ( v1 , v2 Vec3 ) float32 { dx := v1 [ 0 ] - v2 [ 0 ] dz := v1 [ 2 ] - v2 [ 2 ] return dx * dx + dz * dz }

// Vec3Dist2DSqr derives the square of the distance between v1 and v2 on the
// xz-plane.
//
// The vectors are projected onto the xz-plane, so the y-values are ignored.

Vec3Dist2DSqr derives the square of the distance between v1 and v2 on the xz - plane . The vectors are projected onto the xz - plane so the y - values are ignored .


func (v Vec3) Copy(dst Vec3) {
	dst[0] = v[0]
	dst[1] = v[1]
	dst[2] = v[2]
}

func ( v Vec3 ) Copy ( dst Vec3 ) { dst [ 0 ] = v [ 0 ] dst [ 1 ] = v [ 1 ] dst [ 2 ] = v [ 2 ] }

// Vec3 methods
// Copy copies the 3 vector components into dst.

Vec3 methods Copy copies the 3 vector components into dst .


// Assign assign the component of v1 to v. v = v1

Assign assign the component of v1 to v . v = v1


func (v Vec3) Dist2D(v1 Vec3) float32 {
	dx := v1[0] - v[0]
	dz := v1[2] - v[2]
	return math32.Sqrt(dx*dx + dz*dz)
}

func ( v Vec3 ) Dist2D ( v1 Vec3 ) float32 { dx := v1 [ 0 ] - v [ 0 ] dz := v1 [ 2 ] - v [ 2 ] return math32 . Sqrt ( dx * dx + dz * dz ) }

// Dist2D derives the distance between v and v2 on the xz-plane.
//
// The vectors are projected onto the xz-plane, so the y-values are ignored.

Dist2D derives the distance between v and v2 on the xz - plane . The vectors are projected onto the xz - plane so the y - values are ignored .


func (v Vec3) Dist2DSqr(v1 Vec3) float32 {
	dx := v1[0] - v[0]
	dz := v1[2] - v[2]
	return dx*dx + dz*dz
}

func ( v Vec3 ) Dist2DSqr ( v1 Vec3 ) float32 { dx := v1 [ 0 ] - v [ 0 ] dz := v1 [ 2 ] - v [ 2 ] return dx * dx + dz * dz }

// Dist2DSqr derives the square of the distance between v and v2 on the
// xz-plane.
//
// The vectors are projected onto the xz-plane, so the y-values are ignored.

Dist2DSqr derives the square of the distance between v and v2 on the xz - plane . The vectors are projected onto the xz - plane so the y - values are ignored .


// Cross returns the cross product of two vectors. v x v1

Cross returns the cross product of two vectors . v x v1


func (v Vec3) Dot2D(u Vec3) float32 {
	return v[0]*u[0] + v[2]*u[2]
}

func ( v Vec3 ) Dot2D ( u Vec3 ) float32 { return v [ 0 ] * u [ 0 ] + v [ 2 ] * u [ 2 ] }

// Dot2D derives the dot product of two vectors on the xz-plane. u . v
//
// The vectors are projected onto the xz-plane, so the y-values are ignored.

Dot2D derives the dot product of two vectors on the xz - plane . u . v The vectors are projected onto the xz - plane so the y - values are ignored .


func NewRay(o, v Vec) Ray {
	//v = v.Normalize()
	return Ray{
		o:    o,
		v:    v,
		invv: Vec{1.0 / v.X, 1.0 / v.Y},
	}
}

func
NewRay
(
o
,
v
Vec
)
Ray
{
//v = v.Normalize()
return
Ray
{
o
:
o
,
v
:
v
,
invv
:
Vec
{
1.0
/
v
.
X
,
1.0
/
v
.
Y
}
,
}
}

// NewRay creates a new Ray having the o as origin and v as direction of the
// line.

NewRay creates a new Ray having the o as origin and v as direction of the line .


func (r Ray) IntersectRect(b Rectangle) bool {
	t1 := (b.Min.X - r.o.X) * r.invv.X
	t2 := (b.Max.X - r.o.X) * r.invv.X

	tmin := math.Min(t1, t2)
	tmax := math.Max(t1, t2)

	// x
	t1 = (b.Min.X - r.o.X) * r.invv.X
	t2 = (b.Max.X - r.o.X) * r.invv.X
	tmin = math.Max(tmin, math.Min(t1, t2))
	tmax = math.Min(tmax, math.Max(t1, t2))

	// y
	t1 = (b.Min.Y - r.o.Y) * r.invv.Y
	t2 = (b.Max.Y - r.o.Y) * r.invv.Y
	tmin = math.Max(tmin, math.Min(t1, t2))
	tmax = math.Min(tmax, math.Max(t1, t2))

	return tmax >= math.Max(tmin, 0.0)
}

func
(
r
Ray
)
IntersectRect
(
b
Rectangle
)
bool
{
t1
:=
(
b
.
Min
.
X
r
.
o
.
X
)
*
r
.
invv
.
X
t2
:=
(
b
.
Max
.
X
r
.
o
.
X
)
*
r
.
invv
.
X
tmin
:=
math
.
Min
(
t1
,
t2
)
tmax
:=
math
.
Max
(
t1
,
t2
)
// x
t1
=
(
b
.
Min
.
X
r
.
o
.
X
)
*
r
.
invv
.
X
t2
=
(
b
.
Max
.
X
r
.
o
.
X
)
*
r
.
invv
.
X
tmin
=
math
.
Max
(
tmin
,
math
.
Min
(
t1
,
t2
)
)
tmax
=
math
.
Min
(
tmax
,
math
.
Max
(
t1
,
t2
)
)
// y
t1
=
(
b
.
Min
.
Y
r
.
o
.
Y
)
*
r
.
invv
.
Y
t2
=
(
b
.
Max
.
Y
r
.
o
.
Y
)
*
r
.
invv
.
Y
tmin
=
math
.
Max
(
tmin
,
math
.
Min
(
t1
,
t2
)
)
tmax
=
math
.
Min
(
tmax
,
math
.
Max
(
t1
,
t2
)
)
return
tmax
>=
math
.
Max
(
tmin
,
0.0
)
}

// IntersectRect indicates wether the ray intersects with the rectangle b.

IntersectRect indicates wether the ray intersects with the rectangle b .


func SupportedFunc(opts *ServerOptions) func(*Request) error {
	subjectMap := map[SubjectType]bool{}
	for _, subjectType := range opts.SubjectTypes {
		subjectMap[subjectType] = true
	}
	identityMap := map[string]bool{}
	for _, identity := range opts.Identities {
		identityMap[string(identity.Type)+string(identity.Format)] = true
	}
	return func(req *Request) error {
		if _, ok := subjectMap[req.SubjectRequestType]; !ok {
			return ErrUnsupportedRequestType(req.SubjectRequestType)
		}
		for _, identity := range req.SubjectIdentities {
			if _, ok := identityMap[string(identity.Type)+string(identity.Format)]; !ok {
				return ErrUnsupportedIdentity(identity)
			}
		}
		return nil
	}
}

func SupportedFunc ( opts * ServerOptions ) func ( * Request ) error { subjectMap := map [ SubjectType ] bool { } for _ , subjectType := range opts . SubjectTypes { subjectMap [ subjectType ] = true } identityMap := map [ string ] bool { } for _ , identity := range opts . Identities { identityMap [ string ( identity . Type ) + string ( identity . Format ) ] = true } return func ( req * Request ) error { if _ , ok := subjectMap [ req . SubjectRequestType ] ; ! ok { return ErrUnsupportedRequestType ( req . SubjectRequestType ) } for _ , identity := range req . SubjectIdentities { if _ , ok := identityMap [ string ( identity . Type ) + string ( identity . Format ) ] ; ! ok { return ErrUnsupportedIdentity ( identity ) } } return nil } }

// SupportedFunc returns a function that checks if the server can
// support a specific request.

SupportedFunc returns a function that checks if the server can support a specific request .


func NewSigner(opts *KeyOptions) (Signer, error) {
	privateKey := opts.KeyBytes
	if opts.KeyPath != "" {
		raw, err := ioutil.ReadFile(opts.KeyPath)
		if err != nil {
			return nil, err
		}
		privateKey = raw
	}
	block, _ := pem.Decode(privateKey)
	blockBytes := block.Bytes
	// Decode the PEM key if a password is set
	if x509.IsEncryptedPEMBlock(block) {
		b, err := x509.DecryptPEMBlock(block, opts.Password)
		if err != nil {
			return nil, err
		}
		blockBytes = b
	}
	parsed, err := x509.ParsePKCS8PrivateKey(blockBytes)
	if err != nil {
		return nil, err
	}
	privKey, ok := parsed.(*rsa.PrivateKey)
	if !ok {
		return nil, fmt.Errorf("unsupported private key")
	}
	return &rsaSigner{privKey: privKey}, nil
}

// NewSigner creates a new RSA backed Signer


func NewVerifier(opts *KeyOptions) (Verifier, error) {
	publicKey := opts.KeyBytes
	if opts.KeyPath != "" {
		raw, err := ioutil.ReadFile(opts.KeyPath)
		if err != nil {
			return nil, err
		}
		publicKey = raw
	}
	block, _ := pem.Decode(publicKey)
	cert, err := x509.ParseCertificate(block.Bytes)
	if err != nil {
		return nil, err
	}
	// TODO
	// Currently only support RSA keys
	// Need to consider DSA/ECDSA
	if cert.PublicKeyAlgorithm != x509.RSA {
		return nil, fmt.Errorf("unsupported public key type")
	}
	return &rsaVerifier{publicKey: cert.PublicKey.(*rsa.PublicKey), cert: cert}, nil
}

func
NewVerifier
(
opts
*
KeyOptions
)
(
Verifier
,
error
)
{
publicKey
:=
opts
.
KeyBytes
if
opts
.
KeyPath
!=
"
"
{
raw
,
err
:=
ioutil
.
ReadFile
(
opts
.
KeyPath
)
if
err
!=
{
return
,
err
}
publicKey
=
raw
}
block
,
_
:=
pem
.
Decode
(
publicKey
)
cert
,
err
:=
x509
.
ParseCertificate
(
block
.
Bytes
)
if
err
!=
{
return
,
err
}
// TODO
// Currently only support RSA keys
// Need to consider DSA/ECDSA
if
cert
.
PublicKeyAlgorithm
!=
x509
.
RSA
{
return
,
fmt
.
Errorf
(
"
"
)
}
return
&
rsaVerifier
{
publicKey
:
cert
.
PublicKey
.
(
*
rsa
.
PublicKey
)
,
cert
:
cert
}
,
}

// NewVerifier creates a new RSA backed Verifier


func (c *Client) Request(req *Request) (*Response, error) {
	buf := bytes.NewBuffer(nil)
	err := json.NewEncoder(buf).Encode(req)
	if err != nil {
		return nil, err
	}
	reqResp := &Response{}
	resp, err := c.caller.Call("POST", c.endpoint+"/opengdpr_requests", buf)
	return reqResp, c.json(resp, err, true, reqResp)
}

func ( c * Client ) Request ( req * Request ) ( * Response , error ) { buf := bytes . NewBuffer ( nil ) err := json . NewEncoder ( buf ) . Encode ( req ) if err != nil { return nil , err } reqResp := & Response { } resp , err := c . caller . Call ( " " , c . endpoint + " " , buf ) return reqResp , c . json ( resp , err , true , reqResp ) }

// Request makes a performs a new GDPR request.

Request makes a performs a new GDPR request .


func (c *Client) Status(id string) (*StatusResponse, error) {
	statResp := &StatusResponse{}
	resp, err := c.caller.Call("GET", c.endpoint+"/opengdpr_requests/"+id, nil)
	return statResp, c.json(resp, err, true, statResp)
}

func ( c * Client ) Status ( id string ) ( * StatusResponse , error ) { statResp := & StatusResponse { } resp , err := c . caller . Call ( " " , c . endpoint + " " + id , nil ) return statResp , c . json ( resp , err , true , statResp ) }

// Status checks the status of an existing GDPR request.

Status checks the status of an existing GDPR request .


func (c *Client) Cancel(id string) (*CancellationResponse, error) {
	cancelResp := &CancellationResponse{}
	resp, err := c.caller.Call("DELETE", c.endpoint+"/opengdpr_requests/"+id, nil)
	return cancelResp, c.json(resp, err, true, cancelResp)
}

func ( c * Client ) Cancel ( id string ) ( * CancellationResponse , error ) { cancelResp := & CancellationResponse { } resp , err := c . caller . Call ( " " , c . endpoint + " " + id , nil ) return cancelResp , c . json ( resp , err , true , cancelResp ) }

// Cancel cancels an existing GDPR request.

Cancel cancels an existing GDPR request .


func (c *Client) Discovery() (*DiscoveryResponse, error) {
	discResp := &DiscoveryResponse{}
	resp, err := c.caller.Call("GET", c.endpoint+"/discovery", nil)
	return discResp, c.json(resp, err, false, discResp)
}

func ( c * Client ) Discovery ( ) ( * DiscoveryResponse , error ) { discResp := & DiscoveryResponse { } resp , err := c . caller . Call ( " " , c . endpoint + " " , nil ) return discResp , c . json ( resp , err , false , discResp ) }

// Discovery describes the remote OpenGDPR speciication.

Discovery describes the remote OpenGDPR speciication .


func NewClient(opts *ClientOptions) *Client {
	cli := opts.Client
	if cli == nil {
		cli = http.DefaultClient
	}
	client := &Client{
		caller: &defaultCaller{
			client: cli,
			headers: map[string]string{
				"GDPR-Version": ApiVersion,
				"Content-Type": "Application/JSON",
			},
		},
		endpoint: opts.Endpoint,
		verifier: opts.Verifier,
	}
	return client
}

func NewClient ( opts * ClientOptions ) * Client { cli := opts . Client if cli == nil { cli = http . DefaultClient } client := & Client { caller : & defaultCaller { client : cli , headers : map [ string ] string { " " : ApiVersion , " " : " " , } , } , endpoint : opts . Endpoint , verifier : opts . Verifier , } return client }

// NewClient returns a new OpenGDPR client.

NewClient returns a new OpenGDPR client .


func (s *VecStack) Push(value *Vec) {
	s.top = &item{value, s.top}
	s.size++
}

func ( s * VecStack ) Push ( value * Vec ) { s . top = & item { value , s . top } s . size ++ }

// Push pushes a new item on top of the stack.

Push pushes a new item on top of the stack .


func (s *VecStack) Pop() (value *Vec) {
	if s.size > 0 {
		value, s.top = s.top.value, s.top.next
		s.size--
		return
	}
	return nil
}

func ( s * VecStack ) Pop ( ) ( value * Vec ) { if s . size > 0 { value , s . top = s . top . value , s . top . next s . size -- return } return nil }

// Pop removes the topmost item from the stack and return its value.
//
// If the stack is empty, Pop returns nil.

Pop removes the topmost item from the stack and return its value . If the stack is empty Pop returns nil .


func (s *VecStack) PopLast() (value *Vec) {
	if lastElem := s.popLast(s.top); s.size >= 2 && lastElem != nil {
		return lastElem.value
	}
	return nil
}

func ( s * VecStack ) PopLast ( ) ( value * Vec ) { if lastElem := s . popLast ( s . top ) ; s . size >= 2 && lastElem != nil { return lastElem . value } return nil }

// PopLast removes the bottommost item.
//
// PopLast does nothing if the stack does not contain at least 2 items.

PopLast removes the bottommost item . PopLast does nothing if the stack does not contain at least 2 items .


func (s *VecStack) Peek() (value *Vec, exists bool) {
	exists = false
	if s.size > 0 {
		value = s.top.value
		exists = true
	}
	return
}

func ( s * VecStack ) Peek ( ) ( value * Vec , exists bool ) { exists = false if s . size > 0 { value = s . top . value exists = true } return }

// Peek returns the topmost item without removing it from the stack.

Peek returns the topmost item without removing it from the stack .


func (s *VecStack) PeekN(n int) []*Vec {
	var (
		N   []*Vec
		cur *item
	)
	N = make([]*Vec, 0, n)
	cur = s.top
	for len(N) < n {
		if cur == nil {
			break
		}
		N = append(N, cur.value)
		cur = cur.next
	}
	return N
}

func ( s * VecStack ) PeekN ( n int ) [ ] * Vec { var ( N [ ] * Vec cur * item ) N = make ( [ ] * Vec , 0 , n ) cur = s . top for len ( N ) < n { if cur == nil { break } N = append ( N , cur . value ) cur = cur . next } return N }

// PeekN returns at max the N topmost item without removing them from the stack.

PeekN returns at max the N topmost item without removing them from the stack .


func Vecf32(x, y float32) Vec {
	return Vec{float64(x), float64(y)}
}

func Vecf32 ( x , y float32 ) Vec { return Vec { float64 ( x ) , float64 ( y ) } }

// Vecf32 creates a Vec from float32 values.

Vecf32 creates a Vec from float32 values .


func Veci(x, y int) Vec {
	return Vec{float64(x), float64(y)}
}

func Veci ( x , y int ) Vec { return Vec { float64 ( x ) , float64 ( y ) } }


func (v Vec) Add(v2 Vec) Vec {
	return Vec{v.X + v2.X, v.Y + v2.Y}
}

func ( v Vec ) Add ( v2 Vec ) Vec { return Vec { v . X + v2 . X , v . Y + v2 . Y } }


func (v Vec) Sub(v2 Vec) Vec {
	return Vec{v.X - v2.X, v.Y - v2.Y}
}

func ( v Vec ) Sub ( v2 Vec ) Vec { return Vec { v . X - v2 . X , v . Y - v2 . Y } }


func (v Vec) In(r Rectangle) bool {
	return r.Min.X <= v.X && v.X < r.Max.X &&
		r.Min.Y <= v.Y && v.Y < r.Max.Y
}

func ( v Vec ) In ( r Rectangle ) bool { return r . Min . X <= v . X && v . X < r . Max . X && r . Min . Y <= v . Y && v . Y < r . Max . Y }


func (v Vec) Len() float64 {
	return float64(math.Hypot(float64(v.X), float64(v.Y)))
}

func ( v Vec ) Len ( ) float64 { return float64 ( math . Hypot ( float64 ( v . X ) , float64 ( v . Y ) ) ) }


func (v Vec) ApproxFuncEqual(v2 Vec, eq func(float64, float64) bool) bool {
	if !eq(v.X, v2.X) {
		return false
	}
	if !eq(v.Y, v2.Y) {
		return false
	}
	return true
}

func ( v Vec ) ApproxFuncEqual ( v2 Vec , eq func ( float64 , float64 ) bool ) bool { if ! eq ( v . X , v2 . X ) { return false } if ! eq ( v . Y , v2 . Y ) { return false } return true }

// ApproxFuncEqual takes in a func that compares two floats, and uses it to do
// an element-wise comparison of the vector to another.
//
// This is intended to be used with FloatEqualFunc

ApproxFuncEqual takes in a func that compares two floats and uses it to do an element - wise comparison of the vector to another . This is intended to be used with FloatEqualFunc


func (hm HandlerMap) Merge(other HandlerMap) {
	for key, methods := range other {
		if _, ok := hm[key]; !ok {
			hm[key] = map[string]Builder{}
		}
		for method, builder := range methods {
			hm[key][method] = builder
		}
	}
}

func ( hm HandlerMap ) Merge ( other HandlerMap ) { for key , methods := range other { if _ , ok := hm [ key ] ; ! ok { hm [ key ] = map [ string ] Builder { } } for method , builder := range methods { hm [ key ] [ method ] = builder } } }

// Merge merges another HandlerMap into itself.

Merge merges another HandlerMap into itself .


func (s *Server) respCode(r *http.Request) int {
	if r.URL.Path == "/opengdpr_requests" && r.Method == "POST" {
		return http.StatusCreated
	}
	return http.StatusOK
}

func ( s * Server ) respCode ( r * http . Request ) int { if r . URL . Path == " " && r . Method == " " { return http . StatusCreated } return http . StatusOK }

// respCode maps any successful request with a
// specific status code or returns 200.

respCode maps any successful request with a specific status code or returns 200 .


func NewServer(opts *ServerOptions) *Server {
	server := &Server{
		signer:          opts.Signer,
		verifier:        opts.Verifier,
		isProcessor:     hasProcessor(opts),
		isController:    hasController(opts),
		headers:         http.Header{},
		processorDomain: opts.ProcessorDomain,
	}
	server.headers.Set("Accept", "application/json")
	server.headers.Set("Content-Type", "application/json")
	if hasProcessor(opts) {
		server.headers.Set("X-OpenGDPR-ProcessorDomain", opts.ProcessorDomain)
	}
	router := httprouter.New()
	hm := buildHandlerMap(opts)
	for path, methods := range hm {
		for method, builder := range methods {
			router.Handle(method, path, server.handle(builder(opts)))
		}
	}
	server.handlerFn = router.ServeHTTP
	return server
}

func NewServer ( opts * ServerOptions ) * Server { server := & Server { signer : opts . Signer , verifier : opts . Verifier , isProcessor : hasProcessor ( opts ) , isController : hasController ( opts ) , headers : http . Header { } , processorDomain : opts . ProcessorDomain , } server . headers . Set ( " " , " " ) server . headers . Set ( " " , " " ) if hasProcessor ( opts ) { server . headers . Set ( " " , opts . ProcessorDomain ) } router := httprouter . New ( ) hm := buildHandlerMap ( opts ) for path , methods := range hm { for method , builder := range methods { router . Handle ( method , path , server . handle ( builder ( opts ) ) ) } } server . handlerFn = router . ServeHTTP return server }

// NewServer returns a server type that statisfies the
// http.Handler interface.

NewServer returns a server type that statisfies the http . Handler interface .


func Callback(cbReq *CallbackRequest, opts *CallbackOptions) error {
	client := opts.Client
	if client == nil {
		client = http.DefaultClient
	}
	buf := bytes.NewBuffer(nil)
	err := json.NewEncoder(buf).Encode(cbReq)
	if err != nil {
		return err
	}
	signature, err := opts.Signer.Sign(buf.Bytes())
	if err != nil {
		return err
	}
	req, err := http.NewRequest("POST", cbReq.StatusCallbackUrl, buf)
	if err != nil {
		return err
	}
	req.Header.Set("X-OpenGDPR-Processor-Domain", opts.ProcessorDomain)
	req.Header.Set("X-OpenGDPR-Signature", signature)
	// Attempt to make callback
	for i := 0; i < opts.MaxAttempts; i++ {
		resp, err := client.Do(req)
		if err != nil || resp.StatusCode != 200 {
			time.Sleep(opts.Backoff)
			continue
		}
		// Success
		return nil
	}
	return fmt.Errorf("callback timed out for %s", cbReq.StatusCallbackUrl)
}

func
Callback
(
cbReq
*
CallbackRequest
,
opts
*
CallbackOptions
)
error
{
client
:=
opts
.
Client
if
client
==
{
client
=
http
.
DefaultClient
}
buf
:=
bytes
.
NewBuffer
(
)
err
:=
json
.
NewEncoder
(
buf
)
.
Encode
(
cbReq
)
if
err
!=
{
return
err
}
signature
,
err
:=
opts
.
Signer
.
Sign
(
buf
.
Bytes
(
)
)
if
err
!=
{
return
err
}
req
,
err
:=
http
.
NewRequest
(
"
"
,
cbReq
.
StatusCallbackUrl
,
buf
)
if
err
!=
{
return
err
}
req
.
Header
.
Set
(
"
"
,
opts
.
ProcessorDomain
)
req
.
Header
.
Set
(
"
"
,
signature
)
// Attempt to make callback
for
i
:=
0
;
i
<
opts
.
MaxAttempts
;
i
++
{
resp
,
err
:=
client
.
Do
(
req
)
if
err
!=
||
resp
.
StatusCode
!=
200
{
time
.
Sleep
(
opts
.
Backoff
)
continue
}
// Success
return
}
return
fmt
.
Errorf
(
"
"
,
cbReq
.
StatusCallbackUrl
)
}

// Callback sends the CallbackRequest type to the configured
// StatusCallbackUrl. If it fails to deliver in n attempts or
// the request is invalid it will return an error.

Callback sends the CallbackRequest type to the configured StatusCallbackUrl . If it fails to deliver in n attempts or the request is invalid it will return an error .


func ErrNotFound(id string) error {
	return ErrorResponse{
		Code:    http.StatusNotFound,
		Message: fmt.Sprintf("request %s not found", id),
	}
}

func ErrNotFound ( id string ) error { return ErrorResponse { Code : http . StatusNotFound , Message : fmt . Sprintf ( " " , id ) , } }

// ErrNotFound indicates a request could
// not be found by the processor.

ErrNotFound indicates a request could not be found by the processor .


func ErrUnsupportedRequestType(st SubjectType) error {
	return ErrorResponse{
		Code:    http.StatusNotImplemented,
		Message: fmt.Sprintf("unsupported request type: %s", st),
	}
}

func ErrUnsupportedRequestType ( st SubjectType ) error { return ErrorResponse { Code : http . StatusNotImplemented , Message : fmt . Sprintf ( " " , st ) , } }

// ErrUnsupportedRequestType indicates the processor
// cannot fullfil a request for the given RequestType.

ErrUnsupportedRequestType indicates the processor cannot fullfil a request for the given RequestType .


func ErrUnsupportedIdentity(id Identity) error {
	return ErrorResponse{
		Code:    http.StatusNotImplemented,
		Message: fmt.Sprintf("unsupported identity: %s/%s", id.Type, id.Format),
	}
}

func ErrUnsupportedIdentity ( id Identity ) error { return ErrorResponse { Code : http . StatusNotImplemented , Message : fmt . Sprintf ( " " , id . Type , id . Format ) , } }

// ErrUnsupportedIdentity indicates the processor
// does not support the given identity type.

ErrUnsupportedIdentity indicates the processor does not support the given identity type .


func ErrMissingRequiredField(field string) error {
	return ErrorResponse{
		Code:    http.StatusBadRequest,
		Message: fmt.Sprintf("missing required field: %s", field),
	}
}

func ErrMissingRequiredField ( field string ) error { return ErrorResponse { Code : http . StatusBadRequest , Message : fmt . Sprintf ( " " , field ) , } }

// ErrMissingRequiredField indicates the request
// is missing a required field.

ErrMissingRequiredField indicates the request is missing a required field .


func ErrInvalidRequestSignature(signature string, err error) error {
	return ErrorResponse{
		Code:    http.StatusForbidden,
		Message: fmt.Sprintf("could not validate request signature: %s", signature),
		Errors:  []Error{Error{Message: err.Error()}},
	}
}

func ErrInvalidRequestSignature ( signature string , err error ) error { return ErrorResponse { Code : http . StatusForbidden , Message : fmt . Sprintf ( " " , signature ) , Errors : [ ] Error { Error { Message : err . Error ( ) } } , } }

// ErrInvalidRequestSignature indicates the payload could not
// be verified with the given signature.

ErrInvalidRequestSignature indicates the payload could not be verified with the given signature .


func (c *Client) DatabaseServers() ([]DatabaseServer, error) {
	var dbs []DatabaseServer
	_, err := c.MakeApiRequest("GET", "/1.0/database_servers", nil, &dbs)
	if err != nil {
		return nil, err
	}
	return dbs, err
}

func ( c * Client ) DatabaseServers ( ) ( [ ] DatabaseServer , error ) { var dbs [ ] DatabaseServer _ , err := c . MakeApiRequest ( " " , " " , nil , & dbs ) if err != nil { return nil , err } return dbs , err }

// DatabaseServers retrieves a list of all database servers


func (c *Client) SnapshotDatabaseServer(identifier string) (*DatabaseSnapshot, error) {
	dbs := new(DatabaseServer)
	res, err := c.MakeApiRequest("POST", "/1.0/database_servers/"+identifier+"/snapshot", nil, &dbs)
	if err != nil {
		return nil, err
	}
	snapID := getLinkRel(res.Header.Get("Link"), "dbi", "snapshot")
	if snapID != nil {
		snap := new(DatabaseSnapshot)
		snap.Id = *snapID
		return snap, nil
	}
	return nil, nil
}

func ( c * Client ) SnapshotDatabaseServer ( identifier string ) ( * DatabaseSnapshot , error ) { dbs := new ( DatabaseServer ) res , err := c . MakeApiRequest ( " " , " " + identifier + " " , nil , & dbs ) if err != nil { return nil , err } snapID := getLinkRel ( res . Header . Get ( " " ) , " " , " " ) if snapID != nil { snap := new ( DatabaseSnapshot ) snap . Id = * snapID return snap , nil } return nil , nil }

// SnapshotDatabaseServer requests a snapshot of an existing database server.

SnapshotDatabaseServer requests a snapshot of an existing database server .


func (c *Client) ResetPasswordForDatabaseServer(identifier string) (*DatabaseServer, error) {
	dbs := new(DatabaseServer)
	_, err := c.MakeApiRequest("POST", "/1.0/database_servers/"+identifier+"/reset_password", nil, &dbs)
	if err != nil {
		return nil, err
	}
	return dbs, nil
}

func ( c * Client ) ResetPasswordForDatabaseServer ( identifier string ) ( * DatabaseServer , error ) { dbs := new ( DatabaseServer ) _ , err := c . MakeApiRequest ( " " , " " + identifier + " " , nil , & dbs ) if err != nil { return nil , err } return dbs , nil }

// ResetPasswordForDatabaseServer requests a snapshot of an existing database server.

ResetPasswordForDatabaseServer requests a snapshot of an existing database server .


func (c *Client) Servers() ([]Server, error) {
	var servers []Server
	_, err := c.MakeApiRequest("GET", "/1.0/servers", nil, &servers)
	if err != nil {
		return nil, err
	}
	return servers, err
}

func ( c * Client ) Servers ( ) ( [ ] Server , error ) { var servers [ ] Server _ , err := c . MakeApiRequest ( " " , " " , nil , & servers ) if err != nil { return nil , err } return servers , err }

// Servers retrieves a list of all servers


func (c *Client) Server(identifier string) (*Server, error) {
	server := new(Server)
	_, err := c.MakeApiRequest("GET", "/1.0/servers/"+identifier, nil, server)
	if err != nil {
		return nil, err
	}
	return server, err
}

func ( c * Client ) Server ( identifier string ) ( * Server , error ) { server := new ( Server ) _ , err := c . MakeApiRequest ( " " , " " + identifier , nil , server ) if err != nil { return nil , err } return server , err }

// Server retrieves a detailed view of one server


func (c *Client) DestroyServer(identifier string) error {
	_, err := c.MakeApiRequest("DELETE", "/1.0/servers/"+identifier, nil, nil)
	if err != nil {
		return err
	}
	return nil
}

func ( c * Client ) DestroyServer ( identifier string ) error { _ , err := c . MakeApiRequest ( " " , " " + identifier , nil , nil ) if err != nil { return err } return nil }

// DestroyServer issues a request to destroy the server


func (c *Client) LockServer(identifier string) error {
	return c.LockResource(Server{Id: identifier})
}

func ( c * Client ) LockServer ( identifier string ) error { return c . LockResource ( Server { Id : identifier } ) }

// LockServer locks an existing server, preventing it's destruction without
// first unlocking. Deprecated, use LockResource instead.

LockServer locks an existing server preventing it s destruction without first unlocking . Deprecated use LockResource instead .


func (c *Client) UnlockServer(identifier string) error {
	return c.UnLockResource(Server{Id: identifier})
}

func ( c * Client ) UnlockServer ( identifier string ) error { return c . UnLockResource ( Server { Id : identifier } ) }

// UnlockServer unlocks a previously locked existing server, allowing
// destruction again. Deprecated, use UnLockResource instead.

UnlockServer unlocks a previously locked existing server allowing destruction again . Deprecated use UnLockResource instead .


func (c *Client) SnapshotServer(identifier string) (*Image, error) {
	res, err := c.MakeApiRequest("POST", "/1.0/servers/"+identifier+"/snapshot", nil, nil)
	if err != nil {
		return nil, err
	}
	imageID := getLinkRel(res.Header.Get("Link"), "img", "snapshot")
	if imageID != nil {
		img := new(Image)
		img.Id = *imageID
		return img, nil
	}
	return nil, nil
}

func ( c * Client ) SnapshotServer ( identifier string ) ( * Image , error ) { res , err := c . MakeApiRequest ( " " , " " + identifier + " " , nil , nil ) if err != nil { return nil , err } imageID := getLinkRel ( res . Header . Get ( " " ) , " " , " " ) if imageID != nil { img := new ( Image ) img . Id = * imageID return img , nil } return nil , nil }

// SnapshotServer issues a request to snapshot the disk of an existing
// server. The snapshot is allocated an Image Id which is returned within an
// instance of Image.

SnapshotServer issues a request to snapshot the disk of an existing server . The snapshot is allocated an Image Id which is returned within an instance of Image .


func (s *Server) FullConsoleUrl() string {
	if s.ConsoleUrl == "" || s.ConsoleToken == "" {
		return s.ConsoleUrl
	}
	u, err := url.Parse(s.ConsoleUrl)
	if u == nil || err != nil {
		return s.ConsoleUrl
	}
	values := u.Query()
	if values.Get("password") != "" {
		return s.ConsoleUrl
	}
	values.Set("password", s.ConsoleToken)
	u.RawQuery = values.Encode()
	return u.String()
}

func ( s * Server ) FullConsoleUrl ( ) string { if s . ConsoleUrl == " " || s . ConsoleToken == " " { return s . ConsoleUrl } u , err := url . Parse ( s . ConsoleUrl ) if u == nil || err != nil { return s . ConsoleUrl } values := u . Query ( ) if values . Get ( " " ) != " " { return s . ConsoleUrl } values . Set ( " " , s . ConsoleToken ) u . RawQuery = values . Encode ( ) return u . String ( ) }

// FullConsoleUrl returns the console url for the server with the token in the
// query string.  Server needs a ConsoleUrl and ConsoleToken, retrieved using
// ActivateConsoleForServer

FullConsoleUrl returns the console url for the server with the token in the query string . Server needs a ConsoleUrl and ConsoleToken retrieved using ActivateConsoleForServer


func (c *Client) FirewallRule(identifier string) (*FirewallRule, error) {
	rule := new(FirewallRule)
	_, err := c.MakeApiRequest("GET", "/1.0/firewall_rules/"+identifier, nil, rule)
	if err != nil {
		return nil, err
	}
	return rule, err
}

func ( c * Client ) FirewallRule ( identifier string ) ( * FirewallRule , error ) { rule := new ( FirewallRule ) _ , err := c . MakeApiRequest ( " " , " " + identifier , nil , rule ) if err != nil { return nil , err } return rule , err }

// FirewallRule retrieves a detailed view of one firewall rule


func (c *Client) ServerGroups() ([]ServerGroup, error) {
	var groups []ServerGroup
	_, err := c.MakeApiRequest("GET", "/1.0/server_groups", nil, &groups)
	if err != nil {
		return nil, err
	}
	return groups, err
}

func ( c * Client ) ServerGroups ( ) ( [ ] ServerGroup , error ) { var groups [ ] ServerGroup _ , err := c . MakeApiRequest ( " " , " " , nil , & groups ) if err != nil { return nil , err } return groups , err }

// ServerGroups retrieves a list of all server groups


func (c *Client) ServerGroup(identifier string) (*ServerGroup, error) {
	group := new(ServerGroup)
	_, err := c.MakeApiRequest("GET", "/1.0/server_groups/"+identifier, nil, group)
	if err != nil {
		return nil, err
	}
	return group, err
}

func ( c * Client ) ServerGroup ( identifier string ) ( * ServerGroup , error ) { group := new ( ServerGroup ) _ , err := c . MakeApiRequest ( " " , " " + identifier , nil , group ) if err != nil { return nil , err } return group , err }

// ServerGroup retrieves a detailed view on one server group


func (c *Client) AddServersToServerGroup(identifier string, serverIds []string) (*ServerGroup, error) {
	group := new(ServerGroup)
	opts := new(serverGroupMemberOptions)
	for _, id := range serverIds {
		opts.Servers = append(opts.Servers, serverGroupMember{Server: id})
	}
	_, err := c.MakeApiRequest("POST", "/1.0/server_groups/"+identifier+"/add_servers", opts, &group)
	if err != nil {
		return nil, err
	}
	return group, nil
}

func ( c * Client ) AddServersToServerGroup ( identifier string , serverIds [ ] string ) ( * ServerGroup , error ) { group := new ( ServerGroup ) opts := new ( serverGroupMemberOptions ) for _ , id := range serverIds { opts . Servers = append ( opts . Servers , serverGroupMember { Server : id } ) } _ , err := c . MakeApiRequest ( " " , " " + identifier + " " , opts , & group ) if err != nil { return nil , err } return group , nil }

// AddServersToServerGroup adds servers to an existing server group.
//
// The identifier parameter specifies the destination group.
//
// The serverIds paramater specifies the identifiers of the servers you want to add.

AddServersToServerGroup adds servers to an existing server group . The identifier parameter specifies the destination group . The serverIds paramater specifies the identifiers of the servers you want to add .


func (c *Client) MoveServersToServerGroup(src string, dst string, serverIds []string) (*ServerGroup, error) {
	group := new(ServerGroup)
	opts := serverGroupMemberOptions{Destination: dst}
	for _, id := range serverIds {
		opts.Servers = append(opts.Servers, serverGroupMember{Server: id})
	}
	_, err := c.MakeApiRequest("POST", "/1.0/server_groups/"+src+"/move_servers", opts, &group)
	if err != nil {
		return nil, err
	}
	return group, nil
}

func ( c * Client ) MoveServersToServerGroup ( src string , dst string , serverIds [ ] string ) ( * ServerGroup , error ) { group := new ( ServerGroup ) opts := serverGroupMemberOptions { Destination : dst } for _ , id := range serverIds { opts . Servers = append ( opts . Servers , serverGroupMember { Server : id } ) } _ , err := c . MakeApiRequest ( " " , " " + src + " " , opts , & group ) if err != nil { return nil , err } return group , nil }

// MoveServersToServerGroup atomically moves servers from one group to another.
//
// The src parameter specifies the group to which the servers currently belong
//
// The dst parameter specifies the group to which you want to move the servers.
//
// The serverIds parameter specifies the identifiers of the servers you want to move.

MoveServersToServerGroup atomically moves servers from one group to another . The src parameter specifies the group to which the servers currently belong The dst parameter specifies the group to which you want to move the servers . The serverIds parameter specifies the identifiers of the servers you want to move .


func (c *Client) LoadBalancers() ([]LoadBalancer, error) {
	var lbs []LoadBalancer
	_, err := c.MakeApiRequest("GET", "/1.0/load_balancers", nil, &lbs)
	if err != nil {
		return nil, err
	}
	return lbs, err
}

func ( c * Client ) LoadBalancers ( ) ( [ ] LoadBalancer , error ) { var lbs [ ] LoadBalancer _ , err := c . MakeApiRequest ( " " , " " , nil , & lbs ) if err != nil { return nil , err } return lbs , err }

// LoadBalancers retrieves a list of all load balancers


func (c *Client) LoadBalancer(identifier string) (*LoadBalancer, error) {
	lb := new(LoadBalancer)
	_, err := c.MakeApiRequest("GET", "/1.0/load_balancers/"+identifier, nil, lb)
	if err != nil {
		return nil, err
	}
	return lb, err
}

func ( c * Client ) LoadBalancer ( identifier string ) ( * LoadBalancer , error ) { lb := new ( LoadBalancer ) _ , err := c . MakeApiRequest ( " " , " " + identifier , nil , lb ) if err != nil { return nil , err } return lb , err }

// LoadBalancer retrieves a detailed view of one load balancer


func (c *Client) AddNodesToLoadBalancer(loadBalancerID string, nodes []LoadBalancerNode) (*LoadBalancer, error) {
	lb := new(LoadBalancer)
	_, err := c.MakeApiRequest("POST", "/1.0/load_balancers/"+loadBalancerID+"/add_nodes", nodes, &lb)
	if err != nil {
		return nil, err
	}
	return lb, nil
}

func ( c * Client ) AddNodesToLoadBalancer ( loadBalancerID string , nodes [ ] LoadBalancerNode ) ( * LoadBalancer , error ) { lb := new ( LoadBalancer ) _ , err := c . MakeApiRequest ( " " , " " + loadBalancerID + " " , nodes , & lb ) if err != nil { return nil , err } return lb , nil }

// AddNodesToLoadBalancer adds nodes to an existing load balancer.

AddNodesToLoadBalancer adds nodes to an existing load balancer .


func (c *Client) RemoveListenersFromLoadBalancer(loadBalancerID string, listeners []LoadBalancerListener) (*LoadBalancer, error) {
	lb := new(LoadBalancer)
	_, err := c.MakeApiRequest("POST", "/1.0/load_balancers/"+loadBalancerID+"/remove_listeners", listeners, &lb)
	if err != nil {
		return nil, err
	}
	return lb, nil
}

func ( c * Client ) RemoveListenersFromLoadBalancer ( loadBalancerID string , listeners [ ] LoadBalancerListener ) ( * LoadBalancer , error ) { lb := new ( LoadBalancer ) _ , err := c . MakeApiRequest ( " " , " " + loadBalancerID + " " , listeners , & lb ) if err != nil { return nil , err } return lb , nil }

// RemoveListenersFromLoadBalancer removes listeners to an existing load balancer.

RemoveListenersFromLoadBalancer removes listeners to an existing load balancer .


func (c *Client) LockResource(resource interface{}) error {
	rpath, err := resourcePath(resource)
	if err != nil {
		return err
	}
	_, err = c.MakeApiRequest("PUT", fmt.Sprintf("/1.0/%s/lock_resource", rpath), nil, nil)
	if err != nil {
		return err
	}
	return nil
}

func ( c * Client ) LockResource ( resource interface { } ) error { rpath , err := resourcePath ( resource ) if err != nil { return err } _ , err = c . MakeApiRequest ( " " , fmt . Sprintf ( " " , rpath ) , nil , nil ) if err != nil { return err } return nil }

// LockResource locks a resource against destroy requests. Support brightbox.CloudIP, brightbox.Server, brightbox.Image and brightbox.LoadBalancer

LockResource locks a resource against destroy requests . Support brightbox . CloudIP brightbox . Server brightbox . Image and brightbox . LoadBalancer


func (c *Client) FirewallPolicies() ([]FirewallPolicy, error) {
	var policies []FirewallPolicy
	_, err := c.MakeApiRequest("GET", "/1.0/firewall_policies", nil, &policies)
	if err != nil {
		return nil, err
	}
	return policies, err
}

func ( c * Client ) FirewallPolicies ( ) ( [ ] FirewallPolicy , error ) { var policies [ ] FirewallPolicy _ , err := c . MakeApiRequest ( " " , " " , nil , & policies ) if err != nil { return nil , err } return policies , err }

// FirewallPolicies retrieves a list of all firewall policies


func (c *Client) FirewallPolicy(identifier string) (*FirewallPolicy, error) {
	policy := new(FirewallPolicy)
	_, err := c.MakeApiRequest("GET", "/1.0/firewall_policies/"+identifier, nil, policy)
	if err != nil {
		return nil, err
	}
	return policy, err
}

func ( c * Client ) FirewallPolicy ( identifier string ) ( * FirewallPolicy , error ) { policy := new ( FirewallPolicy ) _ , err := c . MakeApiRequest ( " " , " " + identifier , nil , policy ) if err != nil { return nil , err } return policy , err }

// FirewallPolicy retrieves a detailed view of one firewall policy


func (c *Client) ApplyFirewallPolicy(policyId string, serverGroupId string) (*FirewallPolicy, error) {
	policy := new(FirewallPolicy)
	_, err := c.MakeApiRequest("POST", "/1.0/firewall_policies/"+policyId+"/apply_to",
		map[string]string{"server_group": serverGroupId}, &policy)
	if err != nil {
		return nil, err
	}
	return policy, nil
}

func ( c * Client ) ApplyFirewallPolicy ( policyId string , serverGroupId string ) ( * FirewallPolicy , error ) { policy := new ( FirewallPolicy ) _ , err := c . MakeApiRequest ( " " , " " + policyId + " " , map [ string ] string { " " : serverGroupId } , & policy ) if err != nil { return nil , err } return policy , nil }

// ApplyFirewallPolicy issues a request to apply the given firewall policy to
// the given server group.
//

ApplyFirewallPolicy issues a request to apply the given firewall policy to the given server group .


func (r GetAuthResult) Extract() (*AuthResult, error) {
	var s *AuthResult
	err := r.ExtractInto(&s)
	return s, err
}

func ( r GetAuthResult ) Extract ( ) ( * AuthResult , error ) { var s * AuthResult err := r . ExtractInto ( & s ) return s , err }

// Extract is a method that attempts to interpret any Swauth authentication
// response as a AuthResult struct.

Extract is a method that attempts to interpret any Swauth authentication response as a AuthResult struct .


func (c *Client) ApiClients() ([]ApiClient, error) {
	var apiClients []ApiClient
	_, err := c.MakeApiRequest("GET", "/1.0/api_clients", nil, &apiClients)
	if err != nil {
		return nil, err
	}
	return apiClients, err
}

func ( c * Client ) ApiClients ( ) ( [ ] ApiClient , error ) { var apiClients [ ] ApiClient _ , err := c . MakeApiRequest ( " " , " " , nil , & apiClients ) if err != nil { return nil , err } return apiClients , err }

// ApiClients retrieves a list of all API clients


func (c *Client) ApiClient(identifier string) (*ApiClient, error) {
	apiClient := new(ApiClient)
	_, err := c.MakeApiRequest("GET", "/1.0/api_clients/"+identifier, nil, apiClient)
	if err != nil {
		return nil, err
	}
	return apiClient, err
}

func ( c * Client ) ApiClient ( identifier string ) ( * ApiClient , error ) { apiClient := new ( ApiClient ) _ , err := c . MakeApiRequest ( " " , " " + identifier , nil , apiClient ) if err != nil { return nil , err } return apiClient , err }

// ApiClient retrieves a detailed view of one API client


func (c *Client) ResetSecretForApiClient(identifier string) (*ApiClient, error) {
	ac := new(ApiClient)
	_, err := c.MakeApiRequest("POST", "/1.0/api_clients/"+identifier+"/reset_secret", nil, &ac)
	if err != nil {
		return nil, err
	}
	return ac, nil
}

func ( c * Client ) ResetSecretForApiClient ( identifier string ) ( * ApiClient , error ) { ac := new ( ApiClient ) _ , err := c . MakeApiRequest ( " " , " " + identifier + " " , nil , & ac ) if err != nil { return nil , err } return ac , nil }

// ResetSecretForApiClient requests a snapshot of an existing api client


func (c *Client) Images() ([]Image, error) {
	var images []Image
	_, err := c.MakeApiRequest("GET", "/1.0/images", nil, &images)
	if err != nil {
		return nil, err
	}
	return images, err
}

func ( c * Client ) Images ( ) ( [ ] Image , error ) { var images [ ] Image _ , err := c . MakeApiRequest ( " " , " " , nil , & images ) if err != nil { return nil , err } return images , err }

// Images retrieves a list of all images


func (c *Client) Image(identifier string) (*Image, error) {
	image := new(Image)
	_, err := c.MakeApiRequest("GET", "/1.0/images/"+identifier, nil, image)
	if err != nil {
		return nil, err
	}
	return image, err
}

func ( c * Client ) Image ( identifier string ) ( * Image , error ) { image := new ( Image ) _ , err := c . MakeApiRequest ( " " , " " + identifier , nil , image ) if err != nil { return nil , err } return image , err }

// Image retrieves a detailed view of one image


func (c *Client) Accounts() ([]Account, error) {
	var accounts []Account
	_, err := c.MakeApiRequest("GET", "/1.0/accounts?nested=false", nil, &accounts)
	if err != nil {
		return nil, err
	}
	return accounts, err
}

func ( c * Client ) Accounts ( ) ( [ ] Account , error ) { var accounts [ ] Account _ , err := c . MakeApiRequest ( " " , " " , nil , & accounts ) if err != nil { return nil , err } return accounts , err }

// Accounts retrieves a list of all accounts associated with the client.
//
// API Clients are only ever associated with one single account. User clients
// can have multiple accounts, through collaborations.

Accounts retrieves a list of all accounts associated with the client . API Clients are only ever associated with one single account . User clients can have multiple accounts through collaborations .


func (c *Client) Account(identifier string) (*Account, error) {
	account := new(Account)
	_, err := c.MakeApiRequest("GET", "/1.0/accounts/"+identifier, nil, account)
	if err != nil {
		return nil, err
	}
	return account, err
}

func ( c * Client ) Account ( identifier string ) ( * Account , error ) { account := new ( Account ) _ , err := c . MakeApiRequest ( " " , " " + identifier , nil , account ) if err != nil { return nil , err } return account , err }

// Account retrieves a detailed view of one account


func (c *Client) CloudIPs() ([]CloudIP, error) {
	var cloudips []CloudIP
	_, err := c.MakeApiRequest("GET", "/1.0/cloud_ips", nil, &cloudips)
	if err != nil {
		return nil, err
	}
	return cloudips, err
}

func ( c * Client ) CloudIPs ( ) ( [ ] CloudIP , error ) { var cloudips [ ] CloudIP _ , err := c . MakeApiRequest ( " " , " " , nil , & cloudips ) if err != nil { return nil , err } return cloudips , err }

// CloudIPs retrieves a list of all cloud ips


func (c *Client) CloudIP(identifier string) (*CloudIP, error) {
	cloudip := new(CloudIP)
	_, err := c.MakeApiRequest("GET", "/1.0/cloud_ips/"+identifier, nil, cloudip)
	if err != nil {
		return nil, err
	}
	return cloudip, err
}

func ( c * Client ) CloudIP ( identifier string ) ( * CloudIP , error ) { cloudip := new ( CloudIP ) _ , err := c . MakeApiRequest ( " " , " " + identifier , nil , cloudip ) if err != nil { return nil , err } return cloudip , err }

// CloudIP retrieves a detailed view of one cloud ip


func (c *Client) MapCloudIPtoServer(identifier string, serverid string) error {
	server, err := c.Server(serverid)
	if err != nil {
		return err
	}
	if len(server.Interfaces) == 0 {
		return fmt.Errorf("Server %s has no interfaces to map cloud ip %s to", server.Id, identifier)
	}
	destination := server.Interfaces[0].Id
	err = c.MapCloudIP(identifier, destination)
	if err != nil {
		return err
	}
	return nil
}

func ( c * Client ) MapCloudIPtoServer ( identifier string , serverid string ) error { server , err := c . Server ( serverid ) if err != nil { return err } if len ( server . Interfaces ) == 0 { return fmt . Errorf ( " " , server . Id , identifier ) } destination := server . Interfaces [ 0 ] . Id err = c . MapCloudIP ( identifier , destination ) if err != nil { return err } return nil }

// MapCloudIPtoServer is a convenience method to map a Cloud IP to a
// server. First looks up the server to get the network interface id. Uses the
// first interface found.

MapCloudIPtoServer is a convenience method to map a Cloud IP to a server . First looks up the server to get the network interface id . Uses the first interface found .


func setAuthHeader(t *oauth2.Token, r *http.Request) {
	r.Header.Set("X-Auth-Token", t.AccessToken)
}

func setAuthHeader ( t * oauth2 . Token , r * http . Request ) { r . Header . Set ( " " , t . AccessToken ) }

// setAuthHeader sets the Swift Authorization header to r using the access
// token in t.
//

setAuthHeader sets the Swift Authorization header to r using the access token in t .


func Auth(c *gophercloud.ProviderClient, opts AuthOptsBuilder) (r GetAuthResult) {
	h := make(map[string]string)

	if opts != nil {
		headers, err := opts.ToAuthOptsMap()
		if err != nil {
			r.Err = err
			return
		}

		for k, v := range headers {
			h[k] = v
		}
	}

	resp, err := c.Request("GET", getURL(c), &gophercloud.RequestOpts{
		MoreHeaders: h,
		OkCodes:     []int{200},
	})

	if resp != nil {
		r.Header = resp.Header
	}

	r.Err = err

	return r
}

func Auth ( c * gophercloud . ProviderClient , opts AuthOptsBuilder ) ( r GetAuthResult ) { h := make ( map [ string ] string ) if opts != nil { headers , err := opts . ToAuthOptsMap ( ) if err != nil { r . Err = err return } for k , v := range headers { h [ k ] = v } } resp , err := c . Request ( " " , getURL ( c ) , & gophercloud . RequestOpts { MoreHeaders : h , OkCodes : [ ] int { 200 } , } ) if resp != nil { r . Header = resp . Header } r . Err = err return r }

// Auth performs an authentication request for a Swauth-based user.

Auth performs an authentication request for a Swauth - based user .


func (c *Client) Collaborations() ([]Collaboration, error) {
	var cl []Collaboration
	_, err := c.MakeApiRequest("GET", "/1.0/user/collaborations", nil, &cl)
	if err != nil {
		return nil, err
	}
	return cl, err
}

func ( c * Client ) Collaborations ( ) ( [ ] Collaboration , error ) { var cl [ ] Collaboration _ , err := c . MakeApiRequest ( " " , " " , nil , & cl ) if err != nil { return nil , err } return cl , err }

// Collaborations retrieves a list of all the current user's collaborations

Collaborations retrieves a list of all the current user s collaborations


func (c *Client) Collaboration(identifier string) (*Collaboration, error) {
	col := new(Collaboration)
	_, err := c.MakeApiRequest("GET", "/1.0/user/collaborations/"+identifier, nil, col)
	if err != nil {
		return nil, err
	}
	return col, err
}

func ( c * Client ) Collaboration ( identifier string ) ( * Collaboration , error ) { col := new ( Collaboration ) _ , err := c . MakeApiRequest ( " " , " " + identifier , nil , col ) if err != nil { return nil , err } return col , err }

// Collaboration retrieves a detailed view of one of the current user's
// collaborations

Collaboration retrieves a detailed view of one of the current user s collaborations


func (c *Client) DatabaseSnapshots() ([]DatabaseSnapshot, error) {
	var database_snapshot []DatabaseSnapshot
	_, err := c.MakeApiRequest("GET", "/1.0/database_snapshots", nil, &database_snapshot)
	if err != nil {
		return nil, err
	}
	return database_snapshot, err
}

func ( c * Client ) DatabaseSnapshots ( ) ( [ ] DatabaseSnapshot , error ) { var database_snapshot [ ] DatabaseSnapshot _ , err := c . MakeApiRequest ( " " , " " , nil , & database_snapshot ) if err != nil { return nil , err } return database_snapshot , err }

// DatabaseSnapshots retrieves a list of all database snapshot


func (c *Client) DatabaseSnapshot(identifier string) (*DatabaseSnapshot, error) {
	database_snapshot := new(DatabaseSnapshot)
	_, err := c.MakeApiRequest("GET", "/1.0/database_snapshots/"+identifier, nil, database_snapshot)
	if err != nil {
		return nil, err
	}
	return database_snapshot, err
}

func ( c * Client ) DatabaseSnapshot ( identifier string ) ( * DatabaseSnapshot , error ) { database_snapshot := new ( DatabaseSnapshot ) _ , err := c . MakeApiRequest ( " " , " " + identifier , nil , database_snapshot ) if err != nil { return nil , err } return database_snapshot , err }

// DatabaseSnapshot retrieves a detailed view of one database snapshot


func (d PingScanner) Scan() (aliveIPs []string, err error) {
	var hostsInCidr []string
	if hostsInCidr, err = expandCidrIntoIPs(d.CIDR); err != nil {
		return nil, err
	}
	pingChan := make(chan string, d.NumOfConcurrency)
	pongChan := make(chan pong, len(hostsInCidr))
	doneChan := make(chan []pong)

	for i := 0; i < d.NumOfConcurrency; i++ {
		go ping(pingChan, pongChan, d.PingOptions...)
	}

	go receivePong(len(hostsInCidr), pongChan, doneChan)

	for _, ip := range hostsInCidr {
		pingChan <- ip
	}

	alives := <-doneChan
	for _, a := range alives {
		aliveIPs = append(aliveIPs, a.IP)
	}
	sort.Strings(aliveIPs)
	return
}

func ( d PingScanner ) Scan ( ) ( aliveIPs [ ] string , err error ) { var hostsInCidr [ ] string if hostsInCidr , err = expandCidrIntoIPs ( d . CIDR ) ; err != nil { return nil , err } pingChan := make ( chan string , d . NumOfConcurrency ) pongChan := make ( chan pong , len ( hostsInCidr ) ) doneChan := make ( chan [ ] pong ) for i := 0 ; i < d . NumOfConcurrency ; i ++ { go ping ( pingChan , pongChan , d . PingOptions ... ) } go receivePong ( len ( hostsInCidr ) , pongChan , doneChan ) for _ , ip := range hostsInCidr { pingChan <- ip } alives := <- doneChan for _ , a := range alives { aliveIPs = append ( aliveIPs , a . IP ) } sort . Strings ( aliveIPs ) return }


func ToFile(src, dest string, options FileOptions) error {
	u, err := url.Parse(src)
	if err != nil {
		return errors.Wrap(err, "invalid src URL")
	}

	targetDir := filepath.Dir(dest)
	if err = createDir(targetDir, options.Mkdirs == nil || *options.Mkdirs); err != nil {
		return err
	}

	targetName := filepath.Base(dest)
	f, err := ioutil.TempFile(targetDir, ".tmp-"+targetName)
	if err != nil {
		return errors.Wrap(err, "failed to create temp file")
	}

	err = downloadFile(u, f, options.Options)
	if err != nil {
		_ = f.Close()           // #nosec
		_ = os.Remove(f.Name()) // #nosec
		return errors.Wrap(err, "failed to download")
	}
	err = f.Close()
	if err != nil {
		_ = os.Remove(f.Name()) // #nosec
		return errors.Wrap(err, "failed to close temp file")
	}

	if err = renameFile(f.Name(), dest); err != nil {
		return err
	}

	return nil
}

func
ToFile
(
src
,
dest
string
,
options
FileOptions
)
error
{
u
,
err
:=
url
.
Parse
(
src
)
if
err
!=
{
return
errors
.
Wrap
(
err
,
"
"
)
}
targetDir
:=
filepath
.
Dir
(
dest
)
if
err
=
createDir
(
targetDir
,
options
.
Mkdirs
==
||
*
options
.
Mkdirs
)
;
err
!=
{
return
err
}
targetName
:=
filepath
.
Base
(
dest
)
f
,
err
:=
ioutil
.
TempFile
(
targetDir
,
"
"
+
targetName
)
if
err
!=
{
return
errors
.
Wrap
(
err
,
"
"
)
}
err
=
downloadFile
(
u
,
f
,
options
.
Options
)
if
err
!=
{
_
=
f
.
Close
(
)
// #nosec
_
=
os
.
Remove
(
f
.
Name
(
)
)
// #nosec
return
errors
.
Wrap
(
err
,
"
"
)
}
err
=
f
.
Close
(
)
if
err
!=
{
_
=
os
.
Remove
(
f
.
Name
(
)
)
// #nosec
return
errors
.
Wrap
(
err
,
"
"
)
}
if
err
=
renameFile
(
f
.
Name
(
)
,
dest
)
;
err
!=
{
return
err
}
return
}

// ToFile downloads the specified `src` URL to `dest` file using
// the specified `FileOptions`.

ToFile downloads the specified src URL to dest file using the specified FileOptions .


func ToWriter(src string, w io.Writer, options Options) error {
	u, err := url.Parse(src)
	if err != nil {
		return errors.Wrap(err, "invalid src URL")
	}
	return FromURL(u, w, options)
}

func ToWriter ( src string , w io . Writer , options Options ) error { u , err := url . Parse ( src ) if err != nil { return errors . Wrap ( err , " " ) } return FromURL ( u , w , options ) }

// ToWriter downloads the specified `src` URL to `w` writer using
// the specified `Options`.

ToWriter downloads the specified src URL to w writer using the specified Options .


func FromURL(src *url.URL, w io.Writer, options Options) error {
	httpClient := getHTTPClient(options)
	var (
		err  error
		resp *http.Response
	)
	downloader := func() error {
		resp, err = httpClient.Get(src.String())
		if err != nil {
			return &retriableError{errors.Wrap(err, "Temporary download error")}
		}
		if resp.StatusCode != http.StatusOK {
			defer func() { _ = resp.Body.Close() }() // #nosec
			return errors.Errorf("received invalid status code: %d (expected %d)", resp.StatusCode, http.StatusOK)
		}
		return nil
	}
	retries := options.Retries
	if retries == 0 {
		retries = 5
	}
	if err = retryAfter(retries, downloader, options.RetryInterval); err != nil {
		return errors.Wrap(err, "download failed")
	}
	defer func() { _ = resp.Body.Close() }() // #nosec

	var (
		validator checksumValidator

		reader io.Reader = resp.Body
	)

	if options.ProgressBars != nil && resp.ContentLength > 0 {
		bar := newProgressBar(resp.ContentLength, options.ProgressBars.MaxWidth, options.ProgressBars.Writer)
		bar.Start()
		reader = bar.NewProxyReader(reader)
		defer func() {
			<-time.After(bar.RefreshRate)
			fmt.Println()
		}()
	}

	validator, reader, err = createValidatorReader(reader, options.ChecksumHash, httpClient, options.Checksum, path.Base(src.Path))
	if err != nil {
		return err
	}

	if _, err = io.Copy(w, reader); err != nil {
		return errors.Wrap(err, "failed to copy contents")
	}

	if !validator.validate() {
		return errors.New("checksum validation failed")
	}

	return nil
}

func
FromURL
(
src
*
url
.
URL
,
w
io
.
Writer
,
options
Options
)
error
{
httpClient
:=
getHTTPClient
(
options
)
var
(
err
error
resp
*
http
.
Response
)
downloader
:=
func
(
)
error
{
resp
,
err
=
httpClient
.
Get
(
src
.
String
(
)
)
if
err
!=
{
return
&
retriableError
{
errors
.
Wrap
(
err
,
"
"
)
}
}
if
resp
.
StatusCode
!=
http
.
StatusOK
{
defer
func
(
)
{
_
=
resp
.
Body
.
Close
(
)
}
(
)
// #nosec
return
errors
.
Errorf
(
"
"
,
resp
.
StatusCode
,
http
.
StatusOK
)
}
return
}
retries
:=
options
.
Retries
if
retries
==
0
{
retries
=
5
}
if
err
=
retryAfter
(
retries
,
downloader
,
options
.
RetryInterval
)
;
err
!=
{
return
errors
.
Wrap
(
err
,
"
"
)
}
defer
func
(
)
{
_
=
resp
.
Body
.
Close
(
)
}
(
)
// #nosec
var
(
validator
checksumValidator
reader
io
.
Reader
=
resp
.
Body
)
if
options
.
ProgressBars
!=
&&
resp
.
ContentLength
>
0
{
bar
:=
newProgressBar
(
resp
.
ContentLength
,
options
.
ProgressBars
.
MaxWidth
,
options
.
ProgressBars
.
Writer
)
bar
.
Start
(
)
reader
=
bar
.
NewProxyReader
(
reader
)
defer
func
(
)
{
<-
time
.
After
(
bar
.
RefreshRate
)
fmt
.
Println
(
)
}
(
)
}
validator
,
reader
,
err
=
createValidatorReader
(
reader
,
options
.
ChecksumHash
,
httpClient
,
options
.
Checksum
,
path
.
Base
(
src
.
Path
)
)
if
err
!=
{
return
err
}
if
_
,
err
=
io
.
Copy
(
w
,
reader
)
;
err
!=
{
return
errors
.
Wrap
(
err
,
"
"
)
}
if
!
validator
.
validate
(
)
{
return
errors
.
New
(
"
"
)
}
return
}

// FromURL downloads the specified `src` URL to `w` writer using
// the specified `Options`.

FromURL downloads the specified src URL to w writer using the specified Options .


func (totp *TOTP) ForPeriod(period int64) int32 {
	data := int_to_bytestring(period)

	hmacHash := hmac.New(sha1.New, totp.key)
	hmacHash.Write(data)
	digest := hmacHash.Sum(nil)
	offset := int(digest[19] & 0xf)
	code := int32(digest[offset]&0x7f)<<24 |
		int32(digest[offset+1]&0xff)<<16 |
		int32(digest[offset+2]&0xff)<<8 |
		int32(digest[offset+3]&0xff)

	code = int32(int64(code) % int64(math.Pow10(totp.Digits)))
	return code
}

func ( totp * TOTP ) ForPeriod ( period int64 ) int32 { data := int_to_bytestring ( period ) hmacHash := hmac . New ( sha1 . New , totp . key ) hmacHash . Write ( data ) digest := hmacHash . Sum ( nil ) offset := int ( digest [ 19 ] & 0xf ) code := int32 ( digest [ offset ] & 0x7f ) << 24 | int32 ( digest [ offset + 1 ] & 0xff ) << 16 | int32 ( digest [ offset + 2 ] & 0xff ) << 8 | int32 ( digest [ offset + 3 ] & 0xff ) code = int32 ( int64 ( code ) % int64 ( math . Pow10 ( totp . Digits ) ) ) return code }

// Return the time-based OTP for the given period.

Return the time - based OTP for the given period .


func (totp *TOTP) QRCodeData(label string) string {
	// We need to URL Escape the label, but at the same time, spaces come through
	// as +'s, so we need to reverse that encoding...
	label = url.QueryEscape(label)
	label = strings.Replace(label, "+", " ", -1)
	return fmt.Sprintf("otpauth://totp/%v?secret=%v&Digits=%v&Period=%v", label, totp.Secret(), totp.Digits, totp.Period)
}

// Return the data to be contained in a QR Code for this TOTP with the given label.

Return the data to be contained in a QR Code for this TOTP with the given label .


func RandomSecret(length int, rnd *rand.Rand) string {
	if 0 <= length {
		length = 10
	}
	secret := make([]byte, length)
	for i, _ := range secret {
		secret[i] = byte(rnd.Int31() % 256)
	}
	return base32.StdEncoding.EncodeToString(secret)
}

func RandomSecret ( length int , rnd * rand . Rand ) string { if 0 <= length { length = 10 } secret := make ( [ ] byte , length ) for i , _ := range secret { secret [ i ] = byte ( rnd . Int31 ( ) % 256 ) } return base32 . StdEncoding . EncodeToString ( secret ) }

// Generate a Random secret encoded as a b32 string
// If the length is <= 0, a default length of 10 bytes will
// be used, which will generate a secret of length 16.

Generate a Random secret encoded as a b32 string If the length is < = 0 a default length of 10 bytes will be used which will generate a secret of length 16 .


func DefaultPeerConfig() *PeerConfig {
	return &PeerConfig{
		AuthEnc:          true,
		HandshakeTimeout: 2 * time.Second,
		DialTimeout:      3 * time.Second,
		MConfig:          DefaultMConnConfig(),
		Fuzz:             false,
		FuzzConfig:       DefaultFuzzConnConfig(),
	}
}

func DefaultPeerConfig ( ) * PeerConfig { return & PeerConfig { AuthEnc : true , HandshakeTimeout : 2 * time . Second , DialTimeout : 3 * time . Second , MConfig : DefaultMConnConfig ( ) , Fuzz : false , FuzzConfig : DefaultFuzzConnConfig ( ) , } }

// DefaultPeerConfig returns the default config.

DefaultPeerConfig returns the default config .


func (p *Peer) PubKey() crypto.PubKeyEd25519 {
	if p.config.AuthEnc {
		return p.conn.(*SecretConnection).RemotePubKey()
	}
	if p.NodeInfo == nil {
		panic("Attempt to get peer's PubKey before calling Handshake")
	}
	return p.PubKey()
}

func ( p * Peer ) PubKey ( ) crypto . PubKeyEd25519 { if p . config . AuthEnc { return p . conn . ( * SecretConnection ) . RemotePubKey ( ) } if p . NodeInfo == nil { panic ( " " ) } return p . PubKey ( ) }


func (p *Peer) OnStart() error {
	p.BaseService.OnStart()
	_, err := p.mconn.Start()
	return err
}

func ( p * Peer ) OnStart ( ) error { p . BaseService . OnStart ( ) _ , err := p . mconn . Start ( ) return err }


func (p *Peer) Send(chID byte, msg interface{}) bool {
	if !p.IsRunning() {
		// see Switch#Broadcast, where we fetch the list of peers and loop over
		// them - while we're looping, one peer may be removed and stopped.
		return false
	}
	return p.mconn.Send(chID, msg)
}

// Send msg to the channel identified by chID byte. Returns false if the send
// queue is full after timeout, specified by MConnection.

Send msg to the channel identified by chID byte . Returns false if the send queue is full after timeout specified by MConnection .


func (p *Peer) WriteTo(w io.Writer) (n int64, err error) {
	var n_ int
	wire.WriteString(p.Key, w, &n_, &err)
	n += int64(n_)
	return
}

func ( p * Peer ) WriteTo ( w io . Writer ) ( n int64 , err error ) { var n_ int wire . WriteString ( p . Key , w , & n_ , & err ) n += int64 ( n_ ) return }

// WriteTo writes the peer's public key to w.

WriteTo writes the peer s public key to w .


func (p *Peer) Equals(other *Peer) bool {
	return p.Key == other.Key
}

func ( p * Peer ) Equals ( other * Peer ) bool { return p . Key == other . Key }

// Equals reports whenever 2 peers are actually represent the same node.

Equals reports whenever 2 peers are actually represent the same node .


func FuzzConnAfter(conn net.Conn, d time.Duration) net.Conn {
	return FuzzConnAfterFromConfig(conn, d, DefaultFuzzConnConfig())
}

func FuzzConnAfter ( conn net . Conn , d time . Duration ) net . Conn { return FuzzConnAfterFromConfig ( conn , d , DefaultFuzzConnConfig ( ) ) }

// FuzzConnAfter creates a new FuzzedConnection. Fuzzing starts when the
// duration elapses.

FuzzConnAfter creates a new FuzzedConnection . Fuzzing starts when the duration elapses .


func NewMConnectionWithConfig(conn net.Conn, chDescs []*ChannelDescriptor, onReceive receiveCbFunc, onError errorCbFunc, config *MConnConfig) *MConnection {
	mconn := &MConnection{
		conn:        conn,
		bufReader:   bufio.NewReaderSize(conn, minReadBufferSize),
		bufWriter:   bufio.NewWriterSize(conn, minWriteBufferSize),
		sendMonitor: flow.New(0, 0),
		recvMonitor: flow.New(0, 0),
		send:        make(chan struct{}, 1),
		pong:        make(chan struct{}),
		onReceive:   onReceive,
		onError:     onError,
		config:      config,

		LocalAddress:  NewNetAddress(conn.LocalAddr()),
		RemoteAddress: NewNetAddress(conn.RemoteAddr()),
	}

	// Create channels
	var channelsIdx = map[byte]*Channel{}
	var channels = []*Channel{}

	for _, desc := range chDescs {
		descCopy := *desc // copy the desc else unsafe access across connections
		channel := newChannel(mconn, &descCopy)
		channelsIdx[channel.id] = channel
		channels = append(channels, channel)
	}
	mconn.channels = channels
	mconn.channelsIdx = channelsIdx

	mconn.BaseService = *cmn.NewBaseService(log, "MConnection", mconn)

	return mconn
}

// NewMConnectionWithConfig wraps net.Conn and creates multiplex connection with a config

NewMConnectionWithConfig wraps net . Conn and creates multiplex connection with a config


func (c *MConnection) _recover() {
	if r := recover(); r != nil {
		stack := debug.Stack()
		err := cmn.StackError{r, stack}
		c.stopForError(err)
	}
}

func ( c * MConnection ) _recover ( ) { if r := recover ( ) ; r != nil { stack := debug . Stack ( ) err := cmn . StackError { r , stack } c . stopForError ( err ) } }

// Catch panics, usually caused by remote disconnects.

Catch panics usually caused by remote disconnects .


func (c *MConnection) Send(chID byte, msg interface{}) bool {
	if !c.IsRunning() {
		return false
	}

	log.Debug("Send", "channel", chID, "conn", c, "msg", msg) //, "bytes", wire.BinaryBytes(msg))

	// Send message to channel.
	channel, ok := c.channelsIdx[chID]
	if !ok {
		log.Error(cmn.Fmt("Cannot send bytes, unknown channel %X", chID))
		return false
	}

	success := channel.sendBytes(wire.BinaryBytes(msg))
	if success {
		// Wake up sendRoutine if necessary
		select {
		case c.send <- struct{}{}:
		default:
		}
	} else {
		log.Warn("Send failed", "channel", chID, "conn", c, "msg", msg)
	}
	return success
}

func
(
c
*
MConnection
)
Send
(
chID
byte
,
msg
interface
{
}
)
bool
{
if
!
c
.
IsRunning
(
)
{
return
false
}
log
.
Debug
(
"
"
,
"
"
,
chID
,
"
"
,
c
,
"
"
,
msg
)
//, "bytes", wire.BinaryBytes(msg))
// Send message to channel.
channel
,
ok
:=
c
.
channelsIdx
[
chID
]
if
!
ok
{
log
.
Error
(
cmn
.
Fmt
(
"
"
,
chID
)
)
return
false
}
success
:=
channel
.
sendBytes
(
wire
.
BinaryBytes
(
msg
)
)
if
success
{
// Wake up sendRoutine if necessary
select
{
case
c
.
send
<-
struct
{
}
{
}
:
default
:
}
}
else
{
log
.
Warn
(
"
"
,
"
"
,
chID
,
"
"
,
c
,
"
"
,
msg
)
}
return
success
}

// Queues a message to be sent to channel.

Queues a message to be sent to channel .


func (c *MConnection) TrySend(chID byte, msg interface{}) bool {
	if !c.IsRunning() {
		return false
	}

	log.Debug("TrySend", "channel", chID, "conn", c, "msg", msg)

	// Send message to channel.
	channel, ok := c.channelsIdx[chID]
	if !ok {
		log.Error(cmn.Fmt("Cannot send bytes, unknown channel %X", chID))
		return false
	}

	ok = channel.trySendBytes(wire.BinaryBytes(msg))
	if ok {
		// Wake up sendRoutine if necessary
		select {
		case c.send <- struct{}{}:
		default:
		}
	}

	return ok
}

func
(
c
*
MConnection
)
TrySend
(
chID
byte
,
msg
interface
{
}
)
bool
{
if
!
c
.
IsRunning
(
)
{
return
false
}
log
.
Debug
(
"
"
,
"
"
,
chID
,
"
"
,
c
,
"
"
,
msg
)
// Send message to channel.
channel
,
ok
:=
c
.
channelsIdx
[
chID
]
if
!
ok
{
log
.
Error
(
cmn
.
Fmt
(
"
"
,
chID
)
)
return
false
}
ok
=
channel
.
trySendBytes
(
wire
.
BinaryBytes
(
msg
)
)
if
ok
{
// Wake up sendRoutine if necessary
select
{
case
c
.
send
<-
struct
{
}
{
}
:
default
:
}
}
return
ok
}

// Queues a message to be sent to channel.
// Nonblocking, returns true if successful.

Queues a message to be sent to channel . Nonblocking returns true if successful .


func (c *MConnection) CanSend(chID byte) bool {
	if !c.IsRunning() {
		return false
	}

	channel, ok := c.channelsIdx[chID]
	if !ok {
		log.Error(cmn.Fmt("Unknown channel %X", chID))
		return false
	}
	return channel.canSend()
}

func ( c * MConnection ) CanSend ( chID byte ) bool { if ! c . IsRunning ( ) { return false } channel , ok := c . channelsIdx [ chID ] if ! ok { log . Error ( cmn . Fmt ( " " , chID ) ) return false } return channel . canSend ( ) }

// CanSend returns true if you can send more data onto the chID, false
// otherwise. Use only as a heuristic.

CanSend returns true if you can send more data onto the chID false otherwise . Use only as a heuristic .


func (c *MConnection) sendRoutine() {
	defer c._recover()

FOR_LOOP:
	for {
		var n int
		var err error
		select {
		case <-c.flushTimer.Ch:
			// NOTE: flushTimer.Set() must be called every time
			// something is written to .bufWriter.
			c.flush()
		case <-c.chStatsTimer.Ch:
			for _, channel := range c.channels {
				channel.updateStats()
			}
		case <-c.pingTimer.Ch:
			log.Debug("Send Ping")
			wire.WriteByte(packetTypePing, c.bufWriter, &n, &err)
			c.sendMonitor.Update(int(n))
			c.flush()
		case <-c.pong:
			log.Debug("Send Pong")
			wire.WriteByte(packetTypePong, c.bufWriter, &n, &err)
			c.sendMonitor.Update(int(n))
			c.flush()
		case <-c.quit:
			break FOR_LOOP
		case <-c.send:
			// Send some msgPackets
			eof := c.sendSomeMsgPackets()
			if !eof {
				// Keep sendRoutine awake.
				select {
				case c.send <- struct{}{}:
				default:
				}
			}
		}

		if !c.IsRunning() {
			break FOR_LOOP
		}
		if err != nil {
			log.Warn("Connection failed @ sendRoutine", "conn", c, "error", err)
			c.stopForError(err)
			break FOR_LOOP
		}
	}

	// Cleanup
}

// sendRoutine polls for packets to send from channels.

sendRoutine polls for packets to send from channels .


func (c *MConnection) sendSomeMsgPackets() bool {
	// Block until .sendMonitor says we can write.
	// Once we're ready we send more than we asked for,
	// but amortized it should even out.
	c.sendMonitor.Limit(maxMsgPacketTotalSize, atomic.LoadInt64(&c.config.SendRate), true)

	// Now send some msgPackets.
	for i := 0; i < numBatchMsgPackets; i++ {
		if c.sendMsgPacket() {
			return true
		}
	}
	return false
}

// Returns true if messages from channels were exhausted.
// Blocks in accordance to .sendMonitor throttling.

Returns true if messages from channels were exhausted . Blocks in accordance to . sendMonitor throttling .


func (c *MConnection) sendMsgPacket() bool {
	// Choose a channel to create a msgPacket from.
	// The chosen channel will be the one whose recentlySent/priority is the least.
	var leastRatio float32 = math.MaxFloat32
	var leastChannel *Channel
	for _, channel := range c.channels {
		// If nothing to send, skip this channel
		if !channel.isSendPending() {
			continue
		}
		// Get ratio, and keep track of lowest ratio.
		ratio := float32(channel.recentlySent) / float32(channel.priority)
		if ratio < leastRatio {
			leastRatio = ratio
			leastChannel = channel
		}
	}

	// Nothing to send?
	if leastChannel == nil {
		return true
	} else {
		// log.Info("Found a msgPacket to send")
	}

	// Make & send a msgPacket from this channel
	n, err := leastChannel.writeMsgPacketTo(c.bufWriter)
	if err != nil {
		log.Warn("Failed to write msgPacket", "error", err)
		c.stopForError(err)
		return true
	}
	c.sendMonitor.Update(int(n))
	c.flushTimer.Set()
	return false
}

// Returns true if messages from channels were exhausted.

Returns true if messages from channels were exhausted .


func (ch *Channel) nextMsgPacket() msgPacket {
	packet := msgPacket{}
	packet.ChannelID = byte(ch.id)
	packet.Bytes = ch.sending[:cmn.MinInt(maxMsgPacketPayloadSize, len(ch.sending))]
	if len(ch.sending) <= maxMsgPacketPayloadSize {
		packet.EOF = byte(0x01)
		ch.sending = nil
		atomic.AddInt32(&ch.sendQueueSize, -1) // decrement sendQueueSize
	} else {
		packet.EOF = byte(0x00)
		ch.sending = ch.sending[cmn.MinInt(maxMsgPacketPayloadSize, len(ch.sending)):]
	}
	return packet
}

func
(
ch
*
Channel
)
nextMsgPacket
(
)
msgPacket
{
packet
:=
msgPacket
{
}
packet
.
ChannelID
=
byte
(
ch
.
id
)
packet
.
Bytes
=
ch
.
sending
[
:
cmn
.
MinInt
(
maxMsgPacketPayloadSize
,
len
(
ch
.
sending
)
)
]
if
len
(
ch
.
sending
)
<=
maxMsgPacketPayloadSize
{
packet
.
EOF
=
byte
(
0x01
)
ch
.
sending
=
atomic
.
AddInt32
(
&
ch
.
sendQueueSize
,
1
)
// decrement sendQueueSize
}
else
{
packet
.
EOF
=
byte
(
0x00
)
ch
.
sending
=
ch
.
sending
[
cmn
.
MinInt
(
maxMsgPacketPayloadSize
,
len
(
ch
.
sending
)
)
:
]
}
return
packet
}

// Creates a new msgPacket to send.
// Not goroutine-safe

Creates a new msgPacket to send . Not goroutine - safe


func (ch *Channel) writeMsgPacketTo(w io.Writer) (n int, err error) {
	packet := ch.nextMsgPacket()
	log.Debug("Write Msg Packet", "conn", ch.conn, "packet", packet)
	wire.WriteByte(packetTypeMsg, w, &n, &err)
	wire.WriteBinary(packet, w, &n, &err)
	if err == nil {
		ch.recentlySent += int64(n)
	}
	return
}

func ( ch * Channel ) writeMsgPacketTo ( w io . Writer ) ( n int , err error ) { packet := ch . nextMsgPacket ( ) log . Debug ( " " , " " , ch . conn , " " , packet ) wire . WriteByte ( packetTypeMsg , w , & n , & err ) wire . WriteBinary ( packet , w , & n , & err ) if err == nil { ch . recentlySent += int64 ( n ) } return }

// Writes next msgPacket to w.
// Not goroutine-safe

Writes next msgPacket to w . Not goroutine - safe


func (ch *Channel) recvMsgPacket(packet msgPacket) ([]byte, error) {
	// log.Debug("Read Msg Packet", "conn", ch.conn, "packet", packet)
	if ch.desc.RecvMessageCapacity < len(ch.recving)+len(packet.Bytes) {
		return nil, wire.ErrBinaryReadOverflow
	}
	ch.recving = append(ch.recving, packet.Bytes...)
	if packet.EOF == byte(0x01) {
		msgBytes := ch.recving
		// clear the slice without re-allocating.
		// http://stackoverflow.com/questions/16971741/how-do-you-clear-a-slice-in-go
		//   suggests this could be a memory leak, but we might as well keep the memory for the channel until it closes,
		//	at which point the recving slice stops being used and should be garbage collected
		ch.recving = ch.recving[:0] // make([]byte, 0, ch.desc.RecvBufferCapacity)
		return msgBytes, nil
	}
	return nil, nil
}

// Handles incoming msgPackets. Returns a msg bytes if msg is complete.
// Not goroutine-safe

Handles incoming msgPackets . Returns a msg bytes if msg is complete . Not goroutine - safe