<commit_before>package jap

import (
	"crypto/rsa"
	"encoding/json"
	"net/http"
	"net/url"

	"golang.org/x/net/context"
	"golang.org/x/net/context/ctxhttp"
	"golang.org/x/net/trace"
)

// GoogleLogin returns a handler which attempts to extract a client ID from its
// context and sends the information to Google to validate the user. If no
// client ID exists in the context it panics.
//
// The handler may return one of the following errors:
//
//   400 BadRequest          – If the id_token form param is missing.
//   408 RequestTimeout      – If the contexts deadline was exceeded.
//   500 InternalServerError – If the upstream returns a response we don't understand.
//   502 BadGateway          – If an upstream service fails to respond for another reason.
func GoogleLogin(ctx context.Context, key *rsa.PrivateKey) func(http.ResponseWriter, *http.Request) {
	cid, ok := CIDFromContext(ctx)
	if !ok {
		panic("No client ID found in the context")
	}

	return func(w http.ResponseWriter, r *http.Request) {
		tr := trace.New("jap.tokenlogin", r.URL.Path)
		defer tr.Finish()
		ctx = trace.NewContext(ctx, tr)

		idtoken := r.FormValue("id_token")
		if idtoken == "" {
			writeError(ctx, w, "id_token login param missing", http.StatusBadRequest)
			return
		}

		// TODO: We should skip the Post request and verify the JWT signature with
		//       Google's public key.
		tr.LazyPrintf("Starting Google token validation…")
		inforesp, err := ctxhttp.PostForm(ctx, http.DefaultClient,
			"https://www.googleapis.com/oauth2/v3/tokeninfo",
			url.Values{
				"id_token": []string{idtoken},
			},
		)
		if err != nil {
			switch err {
			case context.DeadlineExceeded:
				writeError(ctx, w, "The deadline was exceeded", http.StatusRequestTimeout)
			default:
				writeError(ctx, w, "Upstream request failed", http.StatusBadGateway)
			}
			return
		}
		defer inforesp.Body.Close()
		if inforesp.StatusCode < 200 || inforesp.StatusCode > 299 {
			writeError(ctx, w, "Unexpected response from upstream", http.StatusInternalServerError)
			return
		}
		tr.LazyPrintf("Received claims from Google…")
		claims := struct {
			Aud          string `json:"aud"`
			Email        string `json:"email"`
			HostedDomain string `json:"hd"`
			Locale       string `json:"locale"`
		}{}
		if err := json.NewDecoder(inforesp.Body).Decode(&claims); err != nil {
			writeError(ctx, w, "Error decoding upstream response", http.StatusInternalServerError)
			return
		}
		if claims.Aud != cid {
			writeError(ctx, w, "Error decoding upstream response", http.StatusInternalServerError)
			return
		}
	}
}
<commit_msg>Fix error with Google metadata<commit_after>package jap

import (
	"crypto/rsa"
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"time"

	"golang.org/x/net/context"
	"golang.org/x/net/context/ctxhttp"
	"golang.org/x/net/trace"
	"golang.org/x/oauth2/jws"
)

// GoogleLogin returns a handler which attempts to extract a client ID from its
// context and sends the information to Google to validate the user. If no
// client ID exists in the context it panics.
//
// The handler may return one of the following errors:
//
//   400 BadRequest          – If the id_token form param is missing.
//   408 RequestTimeout      – If the contexts deadline was exceeded.
//   500 InternalServerError – If the upstream returns a response we don't understand.
//   502 BadGateway          – If an upstream service fails to respond for another reason.
func GoogleLogin(ctx context.Context, key *rsa.PrivateKey) func(http.ResponseWriter, *http.Request) {
	cid, ok := CIDFromContext(ctx)
	if !ok {
		panic("No client ID found in the context")
	}

	return func(w http.ResponseWriter, r *http.Request) {
		tr := trace.New("jap.tokenlogin", r.URL.Path)
		defer tr.Finish()
		ctx = trace.NewContext(ctx, tr)

		idtoken := r.FormValue("id_token")
		if idtoken == "" {
			writeError(ctx, w, "id_token login param missing", http.StatusBadRequest)
			return
		}

		// TODO: We should skip the Post request and verify the JWT signature with
		//       Google's public key.
		tr.LazyPrintf("Starting Google token validation…")
		inforesp, err := ctxhttp.PostForm(ctx, http.DefaultClient,
			"https://www.googleapis.com/oauth2/v3/tokeninfo",
			url.Values{
				"id_token": []string{idtoken},
			},
		)
		if err != nil {
			switch err {
			case context.DeadlineExceeded:
				writeError(ctx, w, "The deadline was exceeded", http.StatusRequestTimeout)
			default:
				writeError(ctx, w, "Upstream request failed", http.StatusBadGateway)
			}
			return
		}
		defer inforesp.Body.Close()
		if inforesp.StatusCode < 200 || inforesp.StatusCode > 299 {
			writeError(ctx, w, "Unexpected response from upstream", http.StatusInternalServerError)
			return
		}
		tr.LazyPrintf("Received claims from Google.")
		meta := struct {
			Aud          string `json:"aud"`
			Email        string `json:"email"`
			Verified     string `json:"email_verified"` // For some reason Google make this a string.
			HostedDomain string `json:"hd"`
			Locale       string `json:"locale"`
		}{}
		tr.LazyPrintf("Decoding claims from Google…")
		if err := json.NewDecoder(inforesp.Body).Decode(&meta); err != nil {
			writeError(ctx, w, "Error decoding upstream response", http.StatusInternalServerError)
			return
		}
		if meta.Aud != cid || ((meta.Email == "" || meta.Verified != "true") && meta.HostedDomain == "") {
			writeError(ctx, w, "Error decoding upstream response", http.StatusInternalServerError)
			return
		}
		tr.LazyPrintf("Decoded claims from Google.")

		// Generate the JWT
		iat := time.Now().Unix()
		claims := jws.ClaimSet{
			Scope:         "login",
			Iss:           meta.Email,
			Exp:           iat + (5 * 60),
			Iat:           iat,
			PrivateClaims: map[string]interface{}{},
		}
		if meta.Locale != "" {
			claims.PrivateClaims["locale"] = meta.Locale
		}
		if meta.HostedDomain != "" {
			claims.PrivateClaims["domain"] = meta.HostedDomain
		}
		header := jws.Header{
			Algorithm: "RS256",
		}
		tr.LazyPrintf("Signing JWT…")
		tok, err := jws.Encode(&header, &claims, key)
		if err != nil {
			writeError(ctx, w, "Error encoding JWS", http.StatusInternalServerError)
			return
		}
		tr.LazyPrintf("Done signing JWT.")
		fmt.Fprintf(w, tok)
	}
}
<|endoftext|>


<commit_before>// Copyright 2012-2014 The GoSNMP Authors. All rights reserved.  Use of this
// source code is governed by a BSD-style license that can be found in the
// LICENSE file.

// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package gosnmp

import (
	"fmt"
	"math/big"
	"math/rand"
	"net"
	"strconv"
	"time"
)

const (
	// maxOids is the maximum number of oids allowed in a Get()
	maxOids = 60

	// Base OID for MIB-2 defined SNMP variables
	baseOid = "1.3.6.1.2.1"

	// Java SNMP uses 50, snmp-net uses 10
	defaultMaxRepetitions = 50

	// TODO comment
	defaultNonRepeaters = 0
)

//LoggingDisabled is set if the Logger is nil, short circuits any 'slog' calls
var LoggingDisabled bool

// GoSNMP represents GoSNMP library state
type GoSNMP struct {

	// Target is an ipv4 address
	Target string

	// Port is a udp port
	Port uint16

	// Community is an SNMP Community string
	Community string

	// Version is an SNMP Version
	Version SnmpVersion

	// Timeout is the timeout for the SNMP Query
	Timeout time.Duration

	// Set the number of retries to attempt within timeout.
	Retries int

	// Conn is net connection to use, typically establised using GoSNMP.Connect()
	Conn net.Conn

	// Logger is the GoSNMP.Logger to use for debugging. If nil, debugging
	// output will be discarded (/dev/null). For verbose logging to stdout:
	// x.Logger = log.New(os.Stdout, "", 0)
	Logger Logger

	// Internal - used to sync requests to responses
	requestID uint32
	random    *rand.Rand
}

// The default connection settings
var Default = &GoSNMP{
	Port:      161,
	Community: "public",
	Version:   Version2c,
	Timeout:   time.Duration(2) * time.Second,
	Retries:   3,
}

// SnmpPDU will be used when doing SNMP Set's
type SnmpPDU struct {

	// Name is an oid in string format eg "1.3.6.1.4.9.27"
	Name string

	// The type of the value eg Integer
	Type Asn1BER

	// The value to be set by the SNMP set
	Value interface{}
}

// Asn1BER is the type of the SNMP PDU
type Asn1BER byte

// Asn1BER's - http://www.ietf.org/rfc/rfc1442.txt
const (
	EndOfContents     Asn1BER = 0x00
	UnknownType               = 0x00 // TODO these should all be type Asn1BER, however
	Boolean                   = 0x01 // tests fail if implemented. See for example
	Integer                   = 0x02 /// http://stackoverflow.com/questions/5037610/typed-constant-declaration-list.
	BitString                 = 0x03
	OctetString               = 0x04
	Null                      = 0x05
	ObjectIdentifier          = 0x06
	ObjectDescription         = 0x07
	IPAddress                 = 0x40
	Counter32                 = 0x41
	Gauge32                   = 0x42
	TimeTicks                 = 0x43
	Opaque                    = 0x44
	NsapAddress               = 0x45
	Counter64                 = 0x46
	Uinteger32                = 0x47
	NoSuchObject              = 0x80
	NoSuchInstance            = 0x81
	EndOfMibView              = 0x82
)

//
// Public Functions (main interface)
//

// Connect initiates a connection to the target host
func (x *GoSNMP) Connect() error {
	if x.Logger == nil {
		LoggingDisabled = true
	}
	Conn, err := net.DialTimeout("udp", fmt.Sprintf("%s:%d", x.Target, x.Port), x.Timeout)
	if err == nil {
		x.Conn = Conn
	} else {
		return fmt.Errorf("Error establishing connection to host: %s\n", err.Error())
	}
	if x.random == nil {
		x.random = rand.New(rand.NewSource(time.Now().UTC().UnixNano()))
	}
	x.requestID = x.random.Uint32()
	return nil
}

// Get sends an SNMP GET request
func (x *GoSNMP) Get(oids []string) (result *SnmpPacket, err error) {
	oidCount := len(oids)
	if oidCount > maxOids {
		return nil, fmt.Errorf("oid count (%d) is greater than maxOids (%d)",
			oidCount, maxOids)
	}
	// convert oids slice to pdu slice
	var pdus []SnmpPDU
	for _, oid := range oids {
		pdus = append(pdus, SnmpPDU{oid, Null, nil})
	}
	// build up SnmpPacket
	packetOut := &SnmpPacket{
		Community:  x.Community,
		Error:      0,
		ErrorIndex: 0,
		PDUType:    GetRequest,
		Version:    x.Version,
	}
	return x.send(pdus, packetOut)
}

// Set sends an SNMP SET request
func (x *GoSNMP) Set(pdus []SnmpPDU) (result *SnmpPacket, err error) {
	if len(pdus) != 1 {
		return nil, fmt.Errorf("gosnmp currently only supports SNMP SETs for one oid")
	}
	if pdus[0].Type != Integer {
		return nil, fmt.Errorf("gosnmp currently only supports SNMP SETs for Integers")
	}
	// build up SnmpPacket
	packetOut := &SnmpPacket{
		Community:  x.Community,
		Error:      0,
		ErrorIndex: 0,
		PDUType:    SetRequest,
		Version:    x.Version,
	}
	return x.send(pdus, packetOut)
}

// GetNext sends an SNMP GETNEXT request
func (x *GoSNMP) GetNext(oids []string) (result *SnmpPacket, err error) {
	oidCount := len(oids)
	if oidCount > maxOids {
		return nil, fmt.Errorf("oid count (%d) is greater than maxOids (%d)",
			oidCount, maxOids)
	}

	// convert oids slice to pdu slice
	var pdus []SnmpPDU
	for _, oid := range oids {
		pdus = append(pdus, SnmpPDU{oid, Null, nil})
	}

	// Marshal and send the packet
	packetOut := &SnmpPacket{
		Community:  x.Community,
		Error:      0,
		ErrorIndex: 0,
		PDUType:    GetNextRequest,
		Version:    x.Version,
	}

	return x.send(pdus, packetOut)
}

// GetBulk sends an SNMP GETBULK request
func (x *GoSNMP) GetBulk(oids []string, nonRepeaters uint8, maxRepetitions uint8) (result *SnmpPacket, err error) {
	oidCount := len(oids)
	if oidCount > maxOids {
		return nil, fmt.Errorf("oid count (%d) is greater than maxOids (%d)",
			oidCount, maxOids)
	}

	// convert oids slice to pdu slice
	var pdus []SnmpPDU
	for _, oid := range oids {
		pdus = append(pdus, SnmpPDU{oid, Null, nil})
	}

	// Marshal and send the packet
	packetOut := &SnmpPacket{
		Community:      x.Community,
		PDUType:        GetBulkRequest,
		Version:        x.Version,
		NonRepeaters:   nonRepeaters,
		MaxRepetitions: maxRepetitions,
	}
	return x.send(pdus, packetOut)
}

//
// SNMP Walk functions - Analogous to net-snmp's snmpwalk commands
//

// WalkFunc is the type of the function called for each data unit visited
// by the Walk function.  If an error is returned processing stops.
type WalkFunc func(dataUnit SnmpPDU) error

// BulkWalk retrieves a subtree of values using GETBULK. As the tree is
// walked walkFn is called for each new value. The function immediately returns
// an error if either there is an underlaying SNMP error (e.g. GetBulk fails),
// or if walkFn returns an error.
func (x *GoSNMP) BulkWalk(rootOid string, walkFn WalkFunc) error {
	return x.walk(GetBulkRequest, rootOid, walkFn)
}

// BulkWalkAll is similar to BulkWalk but returns a filled array of all values
// rather than using a callback function to stream results.
func (x *GoSNMP) BulkWalkAll(rootOid string) (results []SnmpPDU, err error) {
	return x.walkAll(GetBulkRequest, rootOid)
}

// Walk retrieves a subtree of values using GETNEXT - a request is made for each
// value, unlike BulkWalk which does this operation in batches. As the tree is
// walked walkFn is called for each new value. The function immediately returns
// an error if either there is an underlaying SNMP error (e.g. GetNext fails),
// or if walkFn returns an error.
func (x *GoSNMP) Walk(rootOid string, walkFn WalkFunc) error {
	return x.walk(GetNextRequest, rootOid, walkFn)
}

// WalkAll is similar to Walk but returns a filled array of all values rather
// than using a callback function to stream results.
func (x *GoSNMP) WalkAll(rootOid string) (results []SnmpPDU, err error) {
	return x.walkAll(GetNextRequest, rootOid)
}

//
// Public Functions (helpers) - in alphabetical order
//

// Partition - returns true when dividing a slice into
// partitionSize lengths, including last partition which may be smaller
// than partitionSize. This is useful when you have a large array of OIDs
// to run Get() on. See the tests for example usage.
//
// For example for a slice of 8 items to be broken into partitions of
// length 3, Partition returns true for the currentPosition having
// the following values:
//
// 0  1  2  3  4  5  6  7
//       T        T     T
//
func Partition(currentPosition, partitionSize, sliceLength int) bool {
	if currentPosition < 0 || currentPosition >= sliceLength {
		return false
	}
	if partitionSize == 1 { // redundant, but an obvious optimisation
		return true
	}
	if currentPosition%partitionSize == partitionSize-1 {
		return true
	}
	if currentPosition == sliceLength-1 {
		return true
	}
	return false
}

// ToBigInt converts SnmpPDU.Value to big.Int, or returns a zero big.Int for
// non int-like types (eg strings).
//
// This is a convenience function to make working with SnmpPDU's easier - it
// reduces the need for type assertions. A big.Int is convenient, as SNMP can
// return int32, uint32, and uint64.
func ToBigInt(value interface{}) *big.Int {
	var val int64
	switch value := value.(type) { // shadow
	case int:
		val = int64(value)
	case int8:
		val = int64(value)
	case int16:
		val = int64(value)
	case int32:
		val = int64(value)
	case int64:
		val = int64(value)
	case uint:
		val = int64(value)
	case uint8:
		val = int64(value)
	case uint16:
		val = int64(value)
	case uint32:
		val = int64(value)
	case uint64:
		return (uint64ToBigInt(value))
	case string:
		// for testing and other apps - numbers may appear as strings
		var err error
		if val, err = strconv.ParseInt(value, 10, 64); err != nil {
			return new(big.Int)
		}
	default:
		return new(big.Int)
	}
	return big.NewInt(val)
}
<commit_msg>minor change to trigger travis...<commit_after>// Copyright 2012-2014 The GoSNMP Authors. All rights reserved.  Use of this
// source code is governed by a BSD-style license that can be found in the
// LICENSE file.

// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package gosnmp

import (
	"fmt"
	"math/big"
	"math/rand"
	"net"
	"strconv"
	"time"
)

const (
	// maxOids is the maximum number of oids allowed in a Get()
	maxOids = 60

	// Base OID for MIB-2 defined SNMP variables
	baseOid = "1.3.6.1.2.1"

	// Java SNMP uses 50, snmp-net uses 10
	defaultMaxRepetitions = 50

	// TODO comment
	defaultNonRepeaters = 0
)

// LoggingDisabled is set if the Logger is nil, short circuits any 'slog' calls
var LoggingDisabled bool

// GoSNMP represents GoSNMP library state
type GoSNMP struct {

	// Target is an ipv4 address
	Target string

	// Port is a udp port
	Port uint16

	// Community is an SNMP Community string
	Community string

	// Version is an SNMP Version
	Version SnmpVersion

	// Timeout is the timeout for the SNMP Query
	Timeout time.Duration

	// Set the number of retries to attempt within timeout.
	Retries int

	// Conn is net connection to use, typically establised using GoSNMP.Connect()
	Conn net.Conn

	// Logger is the GoSNMP.Logger to use for debugging. If nil, debugging
	// output will be discarded (/dev/null). For verbose logging to stdout:
	// x.Logger = log.New(os.Stdout, "", 0)
	Logger Logger

	// Internal - used to sync requests to responses
	requestID uint32
	random    *rand.Rand
}

// The default connection settings
var Default = &GoSNMP{
	Port:      161,
	Community: "public",
	Version:   Version2c,
	Timeout:   time.Duration(2) * time.Second,
	Retries:   3,
}

// SnmpPDU will be used when doing SNMP Set's
type SnmpPDU struct {

	// Name is an oid in string format eg "1.3.6.1.4.9.27"
	Name string

	// The type of the value eg Integer
	Type Asn1BER

	// The value to be set by the SNMP set
	Value interface{}
}

// Asn1BER is the type of the SNMP PDU
type Asn1BER byte

// Asn1BER's - http://www.ietf.org/rfc/rfc1442.txt
const (
	EndOfContents     Asn1BER = 0x00
	UnknownType               = 0x00 // TODO these should all be type Asn1BER, however
	Boolean                   = 0x01 // tests fail if implemented. See for example
	Integer                   = 0x02 /// http://stackoverflow.com/questions/5037610/typed-constant-declaration-list.
	BitString                 = 0x03
	OctetString               = 0x04
	Null                      = 0x05
	ObjectIdentifier          = 0x06
	ObjectDescription         = 0x07
	IPAddress                 = 0x40
	Counter32                 = 0x41
	Gauge32                   = 0x42
	TimeTicks                 = 0x43
	Opaque                    = 0x44
	NsapAddress               = 0x45
	Counter64                 = 0x46
	Uinteger32                = 0x47
	NoSuchObject              = 0x80
	NoSuchInstance            = 0x81
	EndOfMibView              = 0x82
)

//
// Public Functions (main interface)
//

// Connect initiates a connection to the target host
func (x *GoSNMP) Connect() error {
	if x.Logger == nil {
		LoggingDisabled = true
	}
	Conn, err := net.DialTimeout("udp", fmt.Sprintf("%s:%d", x.Target, x.Port), x.Timeout)
	if err == nil {
		x.Conn = Conn
	} else {
		return fmt.Errorf("Error establishing connection to host: %s\n", err.Error())
	}
	if x.random == nil {
		x.random = rand.New(rand.NewSource(time.Now().UTC().UnixNano()))
	}
	x.requestID = x.random.Uint32()
	return nil
}

// Get sends an SNMP GET request
func (x *GoSNMP) Get(oids []string) (result *SnmpPacket, err error) {
	oidCount := len(oids)
	if oidCount > maxOids {
		return nil, fmt.Errorf("oid count (%d) is greater than maxOids (%d)",
			oidCount, maxOids)
	}
	// convert oids slice to pdu slice
	var pdus []SnmpPDU
	for _, oid := range oids {
		pdus = append(pdus, SnmpPDU{oid, Null, nil})
	}
	// build up SnmpPacket
	packetOut := &SnmpPacket{
		Community:  x.Community,
		Error:      0,
		ErrorIndex: 0,
		PDUType:    GetRequest,
		Version:    x.Version,
	}
	return x.send(pdus, packetOut)
}

// Set sends an SNMP SET request
func (x *GoSNMP) Set(pdus []SnmpPDU) (result *SnmpPacket, err error) {
	if len(pdus) != 1 {
		return nil, fmt.Errorf("gosnmp currently only supports SNMP SETs for one oid")
	}
	if pdus[0].Type != Integer {
		return nil, fmt.Errorf("gosnmp currently only supports SNMP SETs for Integers")
	}
	// build up SnmpPacket
	packetOut := &SnmpPacket{
		Community:  x.Community,
		Error:      0,
		ErrorIndex: 0,
		PDUType:    SetRequest,
		Version:    x.Version,
	}
	return x.send(pdus, packetOut)
}

// GetNext sends an SNMP GETNEXT request
func (x *GoSNMP) GetNext(oids []string) (result *SnmpPacket, err error) {
	oidCount := len(oids)
	if oidCount > maxOids {
		return nil, fmt.Errorf("oid count (%d) is greater than maxOids (%d)",
			oidCount, maxOids)
	}

	// convert oids slice to pdu slice
	var pdus []SnmpPDU
	for _, oid := range oids {
		pdus = append(pdus, SnmpPDU{oid, Null, nil})
	}

	// Marshal and send the packet
	packetOut := &SnmpPacket{
		Community:  x.Community,
		Error:      0,
		ErrorIndex: 0,
		PDUType:    GetNextRequest,
		Version:    x.Version,
	}

	return x.send(pdus, packetOut)
}

// GetBulk sends an SNMP GETBULK request
func (x *GoSNMP) GetBulk(oids []string, nonRepeaters uint8, maxRepetitions uint8) (result *SnmpPacket, err error) {
	oidCount := len(oids)
	if oidCount > maxOids {
		return nil, fmt.Errorf("oid count (%d) is greater than maxOids (%d)",
			oidCount, maxOids)
	}

	// convert oids slice to pdu slice
	var pdus []SnmpPDU
	for _, oid := range oids {
		pdus = append(pdus, SnmpPDU{oid, Null, nil})
	}

	// Marshal and send the packet
	packetOut := &SnmpPacket{
		Community:      x.Community,
		PDUType:        GetBulkRequest,
		Version:        x.Version,
		NonRepeaters:   nonRepeaters,
		MaxRepetitions: maxRepetitions,
	}
	return x.send(pdus, packetOut)
}

//
// SNMP Walk functions - Analogous to net-snmp's snmpwalk commands
//

// WalkFunc is the type of the function called for each data unit visited
// by the Walk function.  If an error is returned processing stops.
type WalkFunc func(dataUnit SnmpPDU) error

// BulkWalk retrieves a subtree of values using GETBULK. As the tree is
// walked walkFn is called for each new value. The function immediately returns
// an error if either there is an underlaying SNMP error (e.g. GetBulk fails),
// or if walkFn returns an error.
func (x *GoSNMP) BulkWalk(rootOid string, walkFn WalkFunc) error {
	return x.walk(GetBulkRequest, rootOid, walkFn)
}

// BulkWalkAll is similar to BulkWalk but returns a filled array of all values
// rather than using a callback function to stream results.
func (x *GoSNMP) BulkWalkAll(rootOid string) (results []SnmpPDU, err error) {
	return x.walkAll(GetBulkRequest, rootOid)
}

// Walk retrieves a subtree of values using GETNEXT - a request is made for each
// value, unlike BulkWalk which does this operation in batches. As the tree is
// walked walkFn is called for each new value. The function immediately returns
// an error if either there is an underlaying SNMP error (e.g. GetNext fails),
// or if walkFn returns an error.
func (x *GoSNMP) Walk(rootOid string, walkFn WalkFunc) error {
	return x.walk(GetNextRequest, rootOid, walkFn)
}

// WalkAll is similar to Walk but returns a filled array of all values rather
// than using a callback function to stream results.
func (x *GoSNMP) WalkAll(rootOid string) (results []SnmpPDU, err error) {
	return x.walkAll(GetNextRequest, rootOid)
}

//
// Public Functions (helpers) - in alphabetical order
//

// Partition - returns true when dividing a slice into
// partitionSize lengths, including last partition which may be smaller
// than partitionSize. This is useful when you have a large array of OIDs
// to run Get() on. See the tests for example usage.
//
// For example for a slice of 8 items to be broken into partitions of
// length 3, Partition returns true for the currentPosition having
// the following values:
//
// 0  1  2  3  4  5  6  7
//       T        T     T
//
func Partition(currentPosition, partitionSize, sliceLength int) bool {
	if currentPosition < 0 || currentPosition >= sliceLength {
		return false
	}
	if partitionSize == 1 { // redundant, but an obvious optimisation
		return true
	}
	if currentPosition%partitionSize == partitionSize-1 {
		return true
	}
	if currentPosition == sliceLength-1 {
		return true
	}
	return false
}

// ToBigInt converts SnmpPDU.Value to big.Int, or returns a zero big.Int for
// non int-like types (eg strings).
//
// This is a convenience function to make working with SnmpPDU's easier - it
// reduces the need for type assertions. A big.Int is convenient, as SNMP can
// return int32, uint32, and uint64.
func ToBigInt(value interface{}) *big.Int {
	var val int64
	switch value := value.(type) { // shadow
	case int:
		val = int64(value)
	case int8:
		val = int64(value)
	case int16:
		val = int64(value)
	case int32:
		val = int64(value)
	case int64:
		val = int64(value)
	case uint:
		val = int64(value)
	case uint8:
		val = int64(value)
	case uint16:
		val = int64(value)
	case uint32:
		val = int64(value)
	case uint64:
		return (uint64ToBigInt(value))
	case string:
		// for testing and other apps - numbers may appear as strings
		var err error
		if val, err = strconv.ParseInt(value, 10, 64); err != nil {
			return new(big.Int)
		}
	default:
		return new(big.Int)
	}
	return big.NewInt(val)
}
<|endoftext|>


<commit_before>package main

import  (
        "fmt"
        "os"
        "../go-todotxt"
        "github.com/spf13/cobra"
        "os/user"
        "strings"
        "strconv"
        "github.com/rakyll/globalconf"
        "flag"
        "regexp"
        "os/exec"
        "io/ioutil"
)

func extendedLoader(filename string) (todotxt.TaskList, error) {
        usr, err := user.Current()
        if err != nil {
                return nil, err
        }

        filename = strings.Replace(filename, "~", usr.HomeDir, -1)
        tasks := todotxt.LoadTaskList(filename)

        return tasks, nil
}

type flagValue struct {
        str string
}

func (f *flagValue) String() string {
        return f.str
}

func (f *flagValue) Set(value string) error {
        f.str = value
        return nil
}

func newFlagValue(val string) *flagValue {
        return &flagValue{str: val}
}

func main() {

        conf, _ := globalconf.New("gotodo")

        var numtasks bool
        var sortby string
        var finished bool
        var prettyformat string
        var filename string

        var flagFilename = flag.String("file", "", "Location of the todo.txt file.")

        var flags = make(map[string]string)

        var cmdConfig = &cobra.Command{
            Use:   "config [key] [value]",
            Short: "Show and sets config values",
            Long:  `Config can be used to see and also set configuration variables.`,
            Run: func(cmd *cobra.Command, args []string) {
                    if len(args) == 0{
                            fmt.Printf("Available config variables:\n\n")
                            for k := range flags {
                                    fmt.Printf("%s\n", k)
                            }
                    }
                    if len(args) == 1 {
                            val, exists := flags[args[0]]
                            if exists {
                                    fmt.Printf("%s\n", val)
                            } else {
                                    // otherwise exit with non-zero status
                                    os.Exit(1)
                            }
                    }
                    if len(args) == 2 {
                            _, exists := flags[args[0]]
                            if exists {
                                    f := &flag.Flag{Name: args[0], Value: newFlagValue(args[1])}
                                    conf.Set("", f)
                            } else {
                                    os.Exit(1)
                            }
                    }
            },
        }

        var cmdList = &cobra.Command{
            Use:   "list [keyword]",
            Short: "Lists tasks that contain keyword, if any",
            Long:  `List is the most basic command that is used for listing tasks.
                    You can specify a keyword as well as other options.`,
            Run: func(cmd *cobra.Command, args []string) {
                tasks, err := extendedLoader(filename)
                if err != nil {
                        fmt.Println(err)
                        return
                }

                if numtasks {
                    fmt.Println(tasks.Len())
                } else {
                    tasks.Sort(sortby)

                    var filteredTasks todotxt.TaskList
                    for _, task := range tasks {
                        if (!task.Finished() && !finished) ||
                           (task.Finished() && finished) {
                           if (len(args) > 0) {
                                   match, _ := regexp.MatchString(args[0], task.Text())
                                   if match {
                                           filteredTasks = append(filteredTasks, task)
                                   }
                           } else {
                                   filteredTasks = append(filteredTasks, task)
                           }
                        }
                    }

                    for _, task := range filteredTasks {
                            task.SetIdPaddingBy(tasks)
                            fmt.Println(task.PrettyPrint(prettyformat))
                    }
                }
            },
        }
        cmdList.Flags().BoolVarP(&numtasks, "num-tasks", "n", false,
                                 "Show the number of tasks")
        cmdList.Flags().BoolVarP(&finished, "finished", "f", false,
                                 "Show finished tasks")
        cmdList.Flags().StringVarP(&sortby, "sort", "s", "prio",
                                   "Sort tasks by parameter (prio|date|len|prio-rev|date-rev|len-rev|id|rand)")
        cmdList.Flags().StringVarP(&prettyformat, "pretty", "", "%i %p %t",
                                   "Pretty print tasks")

        var cmdAdd = &cobra.Command{
            Use:   "add [task]",
            Short: "Adds a task to the todo list.",
            Long:  `Adds a task to the todo list.`,
            Run: func(cmd *cobra.Command, args []string) {
                tasks, err := extendedLoader(filename)
                if err != nil {
                        fmt.Println(err)
                        return
                }

                task := strings.Join(args, " ")
                tasks.Add(task)

                tasks.Save(filename)
            },
        }

        var nofinishdate bool
        var cmdDone = &cobra.Command{
            Use:   "done [taskid]",
            Short: "Marks task as done.",
            Long:  `Marks task as done.`,
            Run: func(cmd *cobra.Command, args []string) {
                tasks, err := extendedLoader(filename)
                if err != nil {
                        fmt.Println(err)
                        return
                }

                if len(args) < 1 {
                        fmt.Println("So what needs to be done?")
                        return
                }

                taskid, err := strconv.Atoi(args[0])
                if err != nil {
                        fmt.Printf("Do you really consider that a number? %v\n", err)
                        return
                }

                err = tasks.Done(taskid, !nofinishdate)
                if err != nil {
                        fmt.Printf("There was an error %v\n", err)
                }

                tasks.Save(filename)
            },
        }
        cmdDone.Flags().BoolVarP(&nofinishdate, "no-finish-date", "D", false,
                                        "Do not mark finished tasks with date.")

        var cmdArchive = &cobra.Command{
            Use:   "archive [taskid]",
            Short: "Archives task.",
            Long:  `Archives task.`,
            Run: func(cmd *cobra.Command, args []string) {
                tasks, err := extendedLoader(filename)
                if err != nil {
                        fmt.Println(err)
                        return
                }

                if len(args) < 1 {
                        fmt.Println("So what needs to be done?")
                        return
                }

                taskid, err := strconv.Atoi(args[0])
                if err != nil {
                        fmt.Printf("Do you really consider that a number? %v\n", err)
                        return
                }

                fmt.Printf("Archiving task %v\n", taskid)

                tasks.Save(filename)
            },
        }

        var setprio string
        var settodo string
        var cmdSet = &cobra.Command{
            Use:   "set [taskid]",
            Short: "Sets given task's parameters.",
            Long:  `Sets given task's parameters.`,
            Run: func(cmd *cobra.Command, args []string) {
                tasks, err := extendedLoader(filename)
                if err != nil {
                        fmt.Println(err)
                        return
                }

                if len(args) < 1 {
                        fmt.Println("So what do you want to edit?")
                        return
                }

                taskid, err := strconv.Atoi(args[0])
                if err != nil {
                        fmt.Printf("Do you really consider that a number? %v\n", err)
                        return
                }

                if len(setprio) > 0 {
                        tasks[taskid].SetPriority(setprio[0])
                        tasks[taskid].RebuildRawTodo()
                }

                if len(settodo) > 0 {
                        tasks[taskid].SetTodo(settodo)
                        tasks[taskid].RebuildRawTodo()
                }

              //if len(edittodo) == 0 && len(editprio) == 0 {
              //        // FIXME: nost just vim
              //        out, err := exec.Command("vim", filename).Output()
              //}

                tasks.Save(filename)
            },
        }

        var cmdEdit = &cobra.Command{
            Use:   "edit [taskid]",
            Short: "Edit given task",
            Long:  `Edit given task with your prefered editor.`,
            Run: func(cmd *cobra.Command, args []string) {
                tasks, err := extendedLoader(filename)
                if err != nil {
                        fmt.Println(err)
                        return
                }

                if len(args) < 1 {
                        fmt.Println("So what do you want to edit?")
                        return
                }

                taskid, err := strconv.Atoi(args[0])
                if err != nil {
                        fmt.Printf("Do you really consider that a number? %v\n", err)
                        return
                }

                text := tasks[taskid].RawText()

                file, err := ioutil.TempFile(os.TempDir(), "gotodo")
                defer os.Remove(file.Name())

                if err != nil {
                        panic(err)
                }

                e := ioutil.WriteFile(file.Name(), []byte(text), 0644)
                if e != nil {
                        panic(e)
                }

                exec.Command("vim", file.Name()).Output()

                dat, err := ioutil.ReadFile(file.Name())
                if err != nil {
                        panic(err)
                }

                tasks[taskid].SetTodo(string(dat))
                tasks[taskid].RebuildRawTodo()

                tasks.Save(filename)
            },
        }

        cmdSet.PersistentFlags().StringVarP(&setprio, "priority", "p", "",
                                     "Sets task's priority.")
        cmdSet.PersistentFlags().StringVarP(&settodo, "todo", "t", "",
                                     "Sets task's todo.")

        var GotodoCmd = &cobra.Command{
            Use:   "gotodo",
            Short: "Gotodo is a go implementation of todo.txt.",
            Long: `A small, fast and fun implementation of todo.txt`,
            Run: func(cmd *cobra.Command, args []string) {
                cmdList.Run(cmd, nil)
            },
        }

        GotodoCmd.PersistentFlags().StringVarP(&filename, "filename", "", "",
                                     "Load tasks from this file.")

        conf.ParseAll()

        // values here
        flags["file"] = *flagFilename

        // sadly, this is the best we can do right now
        if filename == "" {
                if *flagFilename == "" {
                        filename = "todo.txt"
                } else {
                        filename = *flagFilename
                }
        }

        GotodoCmd.AddCommand(cmdList)
        GotodoCmd.AddCommand(cmdAdd)
        GotodoCmd.AddCommand(cmdDone)
        GotodoCmd.AddCommand(cmdArchive)
        GotodoCmd.AddCommand(cmdSet)
        GotodoCmd.AddCommand(cmdEdit)
        GotodoCmd.AddCommand(cmdConfig)
        GotodoCmd.Execute()
}
<commit_msg>Running vim<commit_after>package main

import  (
        "fmt"
        "os"
        "../go-todotxt"
        "github.com/spf13/cobra"
        "os/user"
        "strings"
        "strconv"
        "github.com/rakyll/globalconf"
        "flag"
        "regexp"
        "os/exec"
        "io/ioutil"
)

func extendedLoader(filename string) (todotxt.TaskList, error) {
        usr, err := user.Current()
        if err != nil {
                return nil, err
        }

        filename = strings.Replace(filename, "~", usr.HomeDir, -1)
        tasks := todotxt.LoadTaskList(filename)

        return tasks, nil
}

type flagValue struct {
        str string
}

func (f *flagValue) String() string {
        return f.str
}

func (f *flagValue) Set(value string) error {
        f.str = value
        return nil
}

func newFlagValue(val string) *flagValue {
        return &flagValue{str: val}
}

func main() {

        conf, _ := globalconf.New("gotodo")

        var numtasks bool
        var sortby string
        var finished bool
        var prettyformat string
        var filename string

        var flagFilename = flag.String("file", "", "Location of the todo.txt file.")

        var flags = make(map[string]string)

        var cmdConfig = &cobra.Command{
            Use:   "config [key] [value]",
            Short: "Show and sets config values",
            Long:  `Config can be used to see and also set configuration variables.`,
            Run: func(cmd *cobra.Command, args []string) {
                    if len(args) == 0{
                            fmt.Printf("Available config variables:\n\n")
                            for k := range flags {
                                    fmt.Printf("%s\n", k)
                            }
                    }
                    if len(args) == 1 {
                            val, exists := flags[args[0]]
                            if exists {
                                    fmt.Printf("%s\n", val)
                            } else {
                                    // otherwise exit with non-zero status
                                    os.Exit(1)
                            }
                    }
                    if len(args) == 2 {
                            _, exists := flags[args[0]]
                            if exists {
                                    f := &flag.Flag{Name: args[0], Value: newFlagValue(args[1])}
                                    conf.Set("", f)
                            } else {
                                    os.Exit(1)
                            }
                    }
            },
        }

        var cmdList = &cobra.Command{
            Use:   "list [keyword]",
            Short: "Lists tasks that contain keyword, if any",
            Long:  `List is the most basic command that is used for listing tasks.
                    You can specify a keyword as well as other options.`,
            Run: func(cmd *cobra.Command, args []string) {
                tasks, err := extendedLoader(filename)
                if err != nil {
                        fmt.Println(err)
                        return
                }

                if numtasks {
                    fmt.Println(tasks.Len())
                } else {
                    tasks.Sort(sortby)

                    var filteredTasks todotxt.TaskList
                    for _, task := range tasks {
                        if (!task.Finished() && !finished) ||
                           (task.Finished() && finished) {
                           if (len(args) > 0) {
                                   match, _ := regexp.MatchString(args[0], task.Text())
                                   if match {
                                           filteredTasks = append(filteredTasks, task)
                                   }
                           } else {
                                   filteredTasks = append(filteredTasks, task)
                           }
                        }
                    }

                    for _, task := range filteredTasks {
                            task.SetIdPaddingBy(tasks)
                            fmt.Println(task.PrettyPrint(prettyformat))
                    }
                }
            },
        }
        cmdList.Flags().BoolVarP(&numtasks, "num-tasks", "n", false,
                                 "Show the number of tasks")
        cmdList.Flags().BoolVarP(&finished, "finished", "f", false,
                                 "Show finished tasks")
        cmdList.Flags().StringVarP(&sortby, "sort", "s", "prio",
                                   "Sort tasks by parameter (prio|date|len|prio-rev|date-rev|len-rev|id|rand)")
        cmdList.Flags().StringVarP(&prettyformat, "pretty", "", "%i %p %t",
                                   "Pretty print tasks")

        var cmdAdd = &cobra.Command{
            Use:   "add [task]",
            Short: "Adds a task to the todo list.",
            Long:  `Adds a task to the todo list.`,
            Run: func(cmd *cobra.Command, args []string) {
                tasks, err := extendedLoader(filename)
                if err != nil {
                        fmt.Println(err)
                        return
                }

                task := strings.Join(args, " ")
                tasks.Add(task)

                tasks.Save(filename)
            },
        }

        var nofinishdate bool
        var cmdDone = &cobra.Command{
            Use:   "done [taskid]",
            Short: "Marks task as done.",
            Long:  `Marks task as done.`,
            Run: func(cmd *cobra.Command, args []string) {
                tasks, err := extendedLoader(filename)
                if err != nil {
                        fmt.Println(err)
                        return
                }

                if len(args) < 1 {
                        fmt.Println("So what needs to be done?")
                        return
                }

                taskid, err := strconv.Atoi(args[0])
                if err != nil {
                        fmt.Printf("Do you really consider that a number? %v\n", err)
                        return
                }

                err = tasks.Done(taskid, !nofinishdate)
                if err != nil {
                        fmt.Printf("There was an error %v\n", err)
                }

                tasks.Save(filename)
            },
        }
        cmdDone.Flags().BoolVarP(&nofinishdate, "no-finish-date", "D", false,
                                        "Do not mark finished tasks with date.")

        var cmdArchive = &cobra.Command{
            Use:   "archive [taskid]",
            Short: "Archives task.",
            Long:  `Archives task.`,
            Run: func(cmd *cobra.Command, args []string) {
                tasks, err := extendedLoader(filename)
                if err != nil {
                        fmt.Println(err)
                        return
                }

                if len(args) < 1 {
                        fmt.Println("So what needs to be done?")
                        return
                }

                taskid, err := strconv.Atoi(args[0])
                if err != nil {
                        fmt.Printf("Do you really consider that a number? %v\n", err)
                        return
                }

                fmt.Printf("Archiving task %v\n", taskid)

                tasks.Save(filename)
            },
        }

        var setprio string
        var settodo string
        var cmdSet = &cobra.Command{
            Use:   "set [taskid]",
            Short: "Sets given task's parameters.",
            Long:  `Sets given task's parameters.`,
            Run: func(cmd *cobra.Command, args []string) {
                tasks, err := extendedLoader(filename)
                if err != nil {
                        fmt.Println(err)
                        return
                }

                if len(args) < 1 {
                        fmt.Println("So what do you want to edit?")
                        return
                }

                taskid, err := strconv.Atoi(args[0])
                if err != nil {
                        fmt.Printf("Do you really consider that a number? %v\n", err)
                        return
                }

                if len(setprio) > 0 {
                        tasks[taskid].SetPriority(setprio[0])
                        tasks[taskid].RebuildRawTodo()
                }

                if len(settodo) > 0 {
                        tasks[taskid].SetTodo(settodo)
                        tasks[taskid].RebuildRawTodo()
                }

              //if len(edittodo) == 0 && len(editprio) == 0 {
              //        // FIXME: nost just vim
              //        out, err := exec.Command("vim", filename).Output()
              //}

                tasks.Save(filename)
            },
        }

        var cmdEdit = &cobra.Command{
            Use:   "edit [taskid]",
            Short: "Edit given task",
            Long:  `Edit given task with your prefered editor.`,
            Run: func(cmd *cobra.Command, args []string) {
                tasks, err := extendedLoader(filename)
                if err != nil {
                        fmt.Println(err)
                        return
                }

                if len(args) < 1 {
                        fmt.Println("So what do you want to edit?")
                        return
                }

                taskid, err := strconv.Atoi(args[0])
                if err != nil {
                        fmt.Printf("Do you really consider that a number? %v\n", err)
                        return
                }

                text := tasks[taskid].RawText()

                file, err := ioutil.TempFile(os.TempDir(), "gotodo")
                defer os.Remove(file.Name())

                if err != nil {
                        panic(err)
                }

                e := ioutil.WriteFile(file.Name(), []byte(text), 0644)
                if e != nil {
                        panic(e)
                }

                c := exec.Command("vim", file.Name())

                // nasty hack, see http://stackoverflow.com/a/12089980
                c.Stdin = os.Stdin
                c.Stdout = os.Stdout
                c.Stderr = os.Stderr

                er := c.Run()

                if er != nil {
                        fmt.Println(er.Error())
                        panic(er)
                }

                dat, err := ioutil.ReadFile(file.Name())
                if err != nil {
                        panic(err)
                }

                // FIXME: take just the first line
                tasks[taskid] = todotxt.ParseTask(strings.TrimSpace(string(dat)), taskid)

                tasks.Save(filename)
            },
        }

        cmdSet.PersistentFlags().StringVarP(&setprio, "priority", "p", "",
                                     "Sets task's priority.")
        cmdSet.PersistentFlags().StringVarP(&settodo, "todo", "t", "",
                                     "Sets task's todo.")

        var GotodoCmd = &cobra.Command{
            Use:   "gotodo",
            Short: "Gotodo is a go implementation of todo.txt.",
            Long: `A small, fast and fun implementation of todo.txt`,
            Run: func(cmd *cobra.Command, args []string) {
                cmdList.Run(cmd, nil)
            },
        }

        GotodoCmd.PersistentFlags().StringVarP(&filename, "filename", "", "",
                                     "Load tasks from this file.")

        conf.ParseAll()

        // values here
        flags["file"] = *flagFilename

        // sadly, this is the best we can do right now
        if filename == "" {
                if *flagFilename == "" {
                        filename = "todo.txt"
                } else {
                        filename = *flagFilename
                }
        }

        GotodoCmd.AddCommand(cmdList)
        GotodoCmd.AddCommand(cmdAdd)
        GotodoCmd.AddCommand(cmdDone)
        GotodoCmd.AddCommand(cmdArchive)
        GotodoCmd.AddCommand(cmdSet)
        GotodoCmd.AddCommand(cmdEdit)
        GotodoCmd.AddCommand(cmdConfig)
        GotodoCmd.Execute()
}
<|endoftext|>


<commit_before>// Copyright 2014 Josh Finnie. All rights reserved.
//
// Use of this source code is governed by the MIT License license that can be
// found in the LICENSE file or at http://www.joshfinnie.com/license.txt

// This package Goweet takes an input of a Twitter handle and returns that
// person's last tweet.
package main

import (
	"fmt"
	"os"
    "net/url"

	"github.com/ChimeraCoder/anaconda"
)

// returns the current implementation version
func Version() string {
	return "0.0.1"
}

// main application
func main() {
    anaconda.SetConsumerKey("US55QyDCABM9jjOYG4q4IThde")
    anaconda.SetConsumerSecret("xujBz77BlHgkQ0L8ns9WPPiSCL2ixGBd5nx2Timlo8hMO2ml11")
    api := anaconda.NewTwitterApi("8820492-ru3XP6qzsDIevjbg0YbU2OeBw3kj6P431ixesFhSOG", "Aqh0fmAlZeFUlRWkxzjizkEAieLsCGfkFhKZqgqCpcmBb")
	arg := os.Args[1:]
    v := url.Values{}
    v.Set("from", string(arg[0]))
    v.Set("count", "1")
    searchResult, _ := api.GetSearch("", v)
    for _ , tweet := range searchResult {
        fmt.Println(tweet.Text)
    }
}
<commit_msg>fixing formatting<commit_after>// Copyright 2014 Josh Finnie. All rights reserved.
//
// Use of this source code is governed by the MIT License license that can be
// found in the LICENSE file or at http://www.joshfinnie.com/license.txt

// This package Goweet takes an input of a Twitter handle and returns that
// person's last tweet.
package main

import (
	"fmt"
    	"net/url"
	"os"

	"github.com/ChimeraCoder/anaconda"
)

// returns the current implementation version
func Version() string {
	return "0.0.1"
}

// main application
func main() {
    anaconda.SetConsumerKey("US55QyDCABM9jjOYG4q4IThde")
    anaconda.SetConsumerSecret("xujBz77BlHgkQ0L8ns9WPPiSCL2ixGBd5nx2Timlo8hMO2ml11")
    api := anaconda.NewTwitterApi("8820492-ru3XP6qzsDIevjbg0YbU2OeBw3kj6P431ixesFhSOG", "Aqh0fmAlZeFUlRWkxzjizkEAieLsCGfkFhKZqgqCpcmBb")
	arg := os.Args[1:]
    v := url.Values{}
    v.Set("from", string(arg[0]))
    v.Set("count", "1")
    searchResult, _ := api.GetSearch("", v)
    for _ , tweet := range searchResult {
        fmt.Println(tweet.Text)
    }
}
<|endoftext|>


<commit_before>package rabbithole

//
// GET /api/overview
//

// QueueTotals represents queue metrics across the entire cluster.
type QueueTotals struct {
	Messages        int         `json:"messages"`
	MessagesDetails RateDetails `json:"messages_details"`

	MessagesReady        int         `json:"messages_ready"`
	MessagesReadyDetails RateDetails `json:"messages_ready_details"`

	MessagesUnacknowledged        int         `json:"messages_unacknowledged"`
	MessagesUnacknowledgedDetails RateDetails `json:"messages_unacknowledged_details"`
}

// ObjectTotals represents object (connections, queues, consumers, etc) metrics
// across the entire cluster.
type ObjectTotals struct {
	Consumers   int `json:"consumers"`
	Queues      int `json:"queues"`
	Exchanges   int `json:"exchanges"`
	Connections int `json:"connections"`
	Channels    int `json:"channels"`
}

// Listener represents a TCP listener on a node.
type Listener struct {
	Node      string `json:"node"`
	Protocol  string `json:"protocol"`
	IpAddress string `json:"ip_address"`
	Port      Port   `json:"port"`
}

// Overview provides a point-in-time overview of cluster state and some of its key aggregated metrics.
type Overview struct {
	ManagementVersion string          `json:"management_version"`
	StatisticsLevel   string          `json:"statistics_level"`
	RabbitMQVersion   string          `json:"rabbitmq_version"`
	ErlangVersion     string          `json:"erlang_version"`
	FullErlangVersion string          `json:"erlang_full_version"`
	ExchangeTypes     []ExchangeType  `json:"exchange_types"`
	MessageStats      MessageStats    `json:"message_stats"`
	QueueTotals       QueueTotals     `json:"queue_totals"`
	ObjectTotals      ObjectTotals    `json:"object_totals"`
	Node              string          `json:"node"`
	StatisticsDBNode  string          `json:"statistics_db_node"`
	Listeners         []Listener      `json:"listeners"`
	Contexts          []BrokerContext `json:"contexts"`
}

// Overview returns an overview of cluster state with some key aggregated metrics.
func (c *Client) Overview() (rec *Overview, err error) {
	req, err := newGETRequest(c, "overview")
	if err != nil {
		return nil, err
	}

	if err = executeAndParseRequest(c, req, &rec); err != nil {
		return nil, err
	}

	return rec, nil
}

type Aliveness struct {
	Status string `json:"status"`
}

// Aliveness ...
func (c *Client) Aliveness(vhost string) (rec *Aliveness, err error) {
	req, err := newGETRequest(c, "overview")
	if err != nil {
		return nil, err
	}

	if err = executeAndParseRequest(c, req, &rec); err != nil {
		return nil, err
	}

	return rec, nil
}<commit_msg>fixed path for alivness request<commit_after>package rabbithole

//
// GET /api/overview
//

// QueueTotals represents queue metrics across the entire cluster.
type QueueTotals struct {
	Messages        int         `json:"messages"`
	MessagesDetails RateDetails `json:"messages_details"`

	MessagesReady        int         `json:"messages_ready"`
	MessagesReadyDetails RateDetails `json:"messages_ready_details"`

	MessagesUnacknowledged        int         `json:"messages_unacknowledged"`
	MessagesUnacknowledgedDetails RateDetails `json:"messages_unacknowledged_details"`
}

// ObjectTotals represents object (connections, queues, consumers, etc) metrics
// across the entire cluster.
type ObjectTotals struct {
	Consumers   int `json:"consumers"`
	Queues      int `json:"queues"`
	Exchanges   int `json:"exchanges"`
	Connections int `json:"connections"`
	Channels    int `json:"channels"`
}

// Listener represents a TCP listener on a node.
type Listener struct {
	Node      string `json:"node"`
	Protocol  string `json:"protocol"`
	IpAddress string `json:"ip_address"`
	Port      Port   `json:"port"`
}

// Overview provides a point-in-time overview of cluster state and some of its key aggregated metrics.
type Overview struct {
	ManagementVersion string          `json:"management_version"`
	StatisticsLevel   string          `json:"statistics_level"`
	RabbitMQVersion   string          `json:"rabbitmq_version"`
	ErlangVersion     string          `json:"erlang_version"`
	FullErlangVersion string          `json:"erlang_full_version"`
	ExchangeTypes     []ExchangeType  `json:"exchange_types"`
	MessageStats      MessageStats    `json:"message_stats"`
	QueueTotals       QueueTotals     `json:"queue_totals"`
	ObjectTotals      ObjectTotals    `json:"object_totals"`
	Node              string          `json:"node"`
	StatisticsDBNode  string          `json:"statistics_db_node"`
	Listeners         []Listener      `json:"listeners"`
	Contexts          []BrokerContext `json:"contexts"`
}

// Overview returns an overview of cluster state with some key aggregated metrics.
func (c *Client) Overview() (rec *Overview, err error) {
	req, err := newGETRequest(c, "overview")
	if err != nil {
		return nil, err
	}

	if err = executeAndParseRequest(c, req, &rec); err != nil {
		return nil, err
	}

	return rec, nil
}

type Aliveness struct {
	Status string `json:"status"`
}

// Aliveness ...
func (c *Client) Aliveness(vhost string) (rec *Aliveness, err error) {
	req, err := newGETRequest(c, "aliveness-test/" + vhost)
	if err != nil {
		return nil, err
	}

	if err = executeAndParseRequest(c, req, &rec); err != nil {
		return nil, err
	}

	return rec, nil
}<|endoftext|>


<commit_before>package mitm

import (
	"crypto/tls"
	"errors"
	"io"
	"log"
	"net"
	"net/http"
	"net/http/httputil"
	"sync"
	"time"
)

type ServerParam struct {
	CA        *tls.Certificate // the Root CA for generatng on the fly MITM certificates
	TLSConfig *tls.Config      // a template TLS config for the server.
}

// A ServerConn is a net.Conn that holds its clients SNI header in ServerName
// after the handshake.
type ServerConn struct {
	*tls.Conn

	// ServerName is set during Conn's handshake to the client's requested
	// server name set in the SNI header. It is not safe to access across
	// multiple goroutines while Conn is performing the handshake.
	ServerName string
}

// Server wraps cn with a ServerConn configured with p so that during its
// Handshake, it will generate a new certificate using p.CA. After a successful
// Handshake, its ServerName field will be set to the clients requested
// ServerName in the SNI header.
func Server(cn net.Conn, p ServerParam) *ServerConn {
	conf := new(tls.Config)
	if p.TLSConfig != nil {
		*conf = *p.TLSConfig
	}
	sc := new(ServerConn)
	conf.GetCertificate = func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
		sc.ServerName = hello.ServerName
		return GenerateCert(p.CA, hello.ServerName)
	}
	sc.Conn = tls.Server(cn, conf)
	return sc
}

type listener struct {
	net.Listener
	ca   *tls.Certificate
	conf *tls.Config
}

// NewListener returns a net.Listener that generates a new cert from ca for
// each new Accept. It uses SNI to generate the cert, and herefore only
// works with clients that send SNI headers.
//
// This is useful for building transparent MITM proxies.
func NewListener(inner net.Listener, ca *tls.Certificate, conf *tls.Config) net.Listener {
	return &listener{inner, ca, conf}
}

func (l *listener) Accept() (net.Conn, error) {
	cn, err := l.Listener.Accept()
	if err != nil {
		return nil, err
	}
	sc := Server(cn, ServerParam{
		CA:        l.ca,
		TLSConfig: l.conf,
	})
	return sc, nil
}

// Proxy is a forward proxy that substitutes its own certificate
// for incoming TLS connections in place of the upstream server's
// certificate.
type Proxy struct {
	// Wrap specifies a function for optionally wrapping upstream for
	// inspecting the decrypted HTTP request and response.
	Wrap func(upstream http.Handler) http.Handler

	// CA specifies the root CA for generating leaf certs for each incoming
	// TLS request.
	CA *tls.Certificate

	// TLSServerConfig specifies the tls.Config to use when generating leaf
	// cert using CA.
	TLSServerConfig *tls.Config

	// TLSClientConfig specifies the tls.Config to use when establishing
	// an upstream connection for proxying.
	TLSClientConfig *tls.Config

	// FlushInterval specifies the flush interval
	// to flush to the client while copying the
	// response body.
	// If zero, no periodic flushing is done.
	FlushInterval time.Duration

	// Director is function which modifies the request into a new
	// request to be sent using Transport. See the documentation for
	// httputil.ReverseProxy for more details. For mitm proxies, the
	// director defaults to HTTPDirector, but for transparent TLS
	// proxies it should be set to HTTPSDirector.
	Director func(*http.Request)
}

var (
	okHeader           = "HTTP/1.1 200 OK\r\n\r\n"
	noUpstreamHeader   = "HTTP/1.1 503 No Upstream\r\n\r\n"
	noDownstreamHeader = "HTTP/1.1 503 No Downstream\r\n\r\n"
	errHeader          = "HTTP/1.1 500 Internal Server Error\r\n\r\n"
)

func (p *Proxy) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	if req.Method != "CONNECT" {
		rp := &httputil.ReverseProxy{
			Director:      p.Director,
			FlushInterval: p.FlushInterval,
		}
		if rp.Director == nil {
			rp.Director = HTTPDirector
		}
		p.Wrap(rp).ServeHTTP(w, req)
		return
	}

	cn, _, err := w.(http.Hijacker).Hijack()
	if err != nil {
		log.Println("Hijack:", err)
		http.Error(w, "No Upstream", 503)
		return
	}
	defer cn.Close()

	_, err = io.WriteString(cn, okHeader)
	if err != nil {
		log.Println("Write:", err)
		return
	}

	sc, ok := cn.(*ServerConn)
	if !ok {
		name := dnsName(req.Host)
		if name == "" {
			log.Println("cannot determine cert name for " + req.Host)
			io.WriteString(cn, noDownstreamHeader)
			return
		}
		sc = Server(cn, ServerParam{
			CA:        p.CA,
			TLSConfig: p.TLSServerConfig,
		})
		if err := sc.Handshake(); err != nil {
			log.Println("Server Handshake:", err)
			return
		}
	}

	cc, err := p.tlsDial(req.Host, sc.ServerName)
	if err != nil {
		log.Println("tlsDial:", err)
		io.WriteString(cn, noUpstreamHeader)
		return
	}
	p.proxyMITM(sc, cc)
}

func (p *Proxy) tlsDial(addr, serverName string) (net.Conn, error) {
	conf := new(tls.Config)
	if p.TLSClientConfig != nil {
		*conf = *p.TLSClientConfig
	}
	conf.ServerName = serverName
	return tls.Dial("tcp", addr, conf)
}

func (p *Proxy) proxyMITM(upstream, downstream net.Conn) {
	var mu sync.Mutex
	dial := func(network, addr string) (net.Conn, error) {
		mu.Lock()
		defer mu.Unlock()
		if downstream == nil {
			return nil, io.EOF
		}
		cn := downstream
		downstream = nil
		return cn, nil
	}
	rp := &httputil.ReverseProxy{
		Director:      HTTPSDirector,
		Transport:     &http.Transport{DialTLS: dial},
		FlushInterval: p.FlushInterval,
	}
	ch := make(chan struct{})
	wc := &onCloseConn{upstream, func() { ch <- struct{}{} }}
	http.Serve(&oneShotListener{wc}, p.Wrap(rp))
	<-ch
}

// HTTPDirector is director designed for use in Proxy for http
// proxies.
func HTTPDirector(r *http.Request) {
	r.URL.Host = r.Host
	r.URL.Scheme = "http"
}

// HTTPSDirector is a director designed for use in Proxy for
// transparent TLS proxies.
func HTTPSDirector(req *http.Request) {
	req.URL.Host = req.Host
	req.URL.Scheme = "https"
}

// A oneShotListener implements net.Listener whos Accept only returns a
// net.Conn as specified by c followed by an error for each subsequent Accept.
type oneShotListener struct {
	c net.Conn
}

func (l *oneShotListener) Accept() (net.Conn, error) {
	if l.c == nil {
		return nil, errors.New("closed")
	}
	c := l.c
	l.c = nil
	return c, nil
}

func (l *oneShotListener) Close() error {
	return nil
}

func (l *oneShotListener) Addr() net.Addr {
	return l.c.LocalAddr()
}

// A onCloseConn implements net.Conn and calls its f on Close.
type onCloseConn struct {
	net.Conn
	f func()
}

func (c *onCloseConn) Close() error {
	if c.f != nil {
		c.f()
		c.f = nil
	}
	return c.Conn.Close()
}

// dnsName returns the DNS name in addr, if any.
func dnsName(addr string) string {
	host, _, err := net.SplitHostPort(addr)
	if err != nil {
		return ""
	}
	return host
}
<commit_msg>Cache certificates to avoid unnecessary generation<commit_after>package mitm

import (
	"crypto/tls"
	"errors"
	"io"
	"log"
	"net"
	"net/http"
	"net/http/httputil"
	"sync"
	"time"
)

type ServerParam struct {
	CA        *tls.Certificate // the Root CA for generatng on the fly MITM certificates
	TLSConfig *tls.Config      // a template TLS config for the server.
}

// A ServerConn is a net.Conn that holds its clients SNI header in ServerName
// after the handshake.
type ServerConn struct {
	*tls.Conn

	// ServerName is set during Conn's handshake to the client's requested
	// server name set in the SNI header. It is not safe to access across
	// multiple goroutines while Conn is performing the handshake.
	ServerName string
}

// Server wraps cn with a ServerConn configured with p so that during its
// Handshake, it will generate a new certificate using p.CA. After a successful
// Handshake, its ServerName field will be set to the clients requested
// ServerName in the SNI header.
func Server(cn net.Conn, p ServerParam) *ServerConn {
	conf := new(tls.Config)
	if p.TLSConfig != nil {
		*conf = *p.TLSConfig
	}
	sc := new(ServerConn)
	conf.GetCertificate = func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
		sc.ServerName = hello.ServerName
		return getCert(p.CA, hello.ServerName)
	}
	sc.Conn = tls.Server(cn, conf)
	return sc
}

type listener struct {
	net.Listener
	ca   *tls.Certificate
	conf *tls.Config
}

// NewListener returns a net.Listener that generates a new cert from ca for
// each new Accept. It uses SNI to generate the cert, and herefore only
// works with clients that send SNI headers.
//
// This is useful for building transparent MITM proxies.
func NewListener(inner net.Listener, ca *tls.Certificate, conf *tls.Config) net.Listener {
	return &listener{inner, ca, conf}
}

func (l *listener) Accept() (net.Conn, error) {
	cn, err := l.Listener.Accept()
	if err != nil {
		return nil, err
	}
	sc := Server(cn, ServerParam{
		CA:        l.ca,
		TLSConfig: l.conf,
	})
	return sc, nil
}

// Proxy is a forward proxy that substitutes its own certificate
// for incoming TLS connections in place of the upstream server's
// certificate.
type Proxy struct {
	// Wrap specifies a function for optionally wrapping upstream for
	// inspecting the decrypted HTTP request and response.
	Wrap func(upstream http.Handler) http.Handler

	// CA specifies the root CA for generating leaf certs for each incoming
	// TLS request.
	CA *tls.Certificate

	// TLSServerConfig specifies the tls.Config to use when generating leaf
	// cert using CA.
	TLSServerConfig *tls.Config

	// TLSClientConfig specifies the tls.Config to use when establishing
	// an upstream connection for proxying.
	TLSClientConfig *tls.Config

	// FlushInterval specifies the flush interval
	// to flush to the client while copying the
	// response body.
	// If zero, no periodic flushing is done.
	FlushInterval time.Duration

	// Director is function which modifies the request into a new
	// request to be sent using Transport. See the documentation for
	// httputil.ReverseProxy for more details. For mitm proxies, the
	// director defaults to HTTPDirector, but for transparent TLS
	// proxies it should be set to HTTPSDirector.
	Director func(*http.Request)
}

var (
	okHeader           = "HTTP/1.1 200 OK\r\n\r\n"
	noUpstreamHeader   = "HTTP/1.1 503 No Upstream\r\n\r\n"
	noDownstreamHeader = "HTTP/1.1 503 No Downstream\r\n\r\n"
	errHeader          = "HTTP/1.1 500 Internal Server Error\r\n\r\n"
)

func (p *Proxy) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	if req.Method != "CONNECT" {
		rp := &httputil.ReverseProxy{
			Director:      p.Director,
			FlushInterval: p.FlushInterval,
		}
		if rp.Director == nil {
			rp.Director = HTTPDirector
		}
		p.Wrap(rp).ServeHTTP(w, req)
		return
	}

	cn, _, err := w.(http.Hijacker).Hijack()
	if err != nil {
		log.Println("Hijack:", err)
		http.Error(w, "No Upstream", 503)
		return
	}
	defer cn.Close()

	_, err = io.WriteString(cn, okHeader)
	if err != nil {
		log.Println("Write:", err)
		return
	}

	sc, ok := cn.(*ServerConn)
	if !ok {
		name := dnsName(req.Host)
		if name == "" {
			log.Println("cannot determine cert name for " + req.Host)
			io.WriteString(cn, noDownstreamHeader)
			return
		}
		sc = Server(cn, ServerParam{
			CA:        p.CA,
			TLSConfig: p.TLSServerConfig,
		})
		if err := sc.Handshake(); err != nil {
			log.Println("Server Handshake:", err)
			return
		}
	}

	cc, err := p.tlsDial(req.Host, sc.ServerName)
	if err != nil {
		log.Println("tlsDial:", err)
		io.WriteString(cn, noUpstreamHeader)
		return
	}
	p.proxyMITM(sc, cc)
}

func (p *Proxy) tlsDial(addr, serverName string) (net.Conn, error) {
	conf := new(tls.Config)
	if p.TLSClientConfig != nil {
		*conf = *p.TLSClientConfig
	}
	conf.ServerName = serverName
	return tls.Dial("tcp", addr, conf)
}

func (p *Proxy) proxyMITM(upstream, downstream net.Conn) {
	var mu sync.Mutex
	dial := func(network, addr string) (net.Conn, error) {
		mu.Lock()
		defer mu.Unlock()
		if downstream == nil {
			return nil, io.EOF
		}
		cn := downstream
		downstream = nil
		return cn, nil
	}
	rp := &httputil.ReverseProxy{
		Director:      HTTPSDirector,
		Transport:     &http.Transport{DialTLS: dial},
		FlushInterval: p.FlushInterval,
	}
	ch := make(chan struct{})
	wc := &onCloseConn{upstream, func() { ch <- struct{}{} }}
	http.Serve(&oneShotListener{wc}, p.Wrap(rp))
	<-ch
}

// HTTPDirector is director designed for use in Proxy for http
// proxies.
func HTTPDirector(r *http.Request) {
	r.URL.Host = r.Host
	r.URL.Scheme = "http"
}

// HTTPSDirector is a director designed for use in Proxy for
// transparent TLS proxies.
func HTTPSDirector(req *http.Request) {
	req.URL.Host = req.Host
	req.URL.Scheme = "https"
}

// A oneShotListener implements net.Listener whos Accept only returns a
// net.Conn as specified by c followed by an error for each subsequent Accept.
type oneShotListener struct {
	c net.Conn
}

func (l *oneShotListener) Accept() (net.Conn, error) {
	if l.c == nil {
		return nil, errors.New("closed")
	}
	c := l.c
	l.c = nil
	return c, nil
}

func (l *oneShotListener) Close() error {
	return nil
}

func (l *oneShotListener) Addr() net.Addr {
	return l.c.LocalAddr()
}

// A onCloseConn implements net.Conn and calls its f on Close.
type onCloseConn struct {
	net.Conn
	f func()
}

func (c *onCloseConn) Close() error {
	if c.f != nil {
		c.f()
		c.f = nil
	}
	return c.Conn.Close()
}

// dnsName returns the DNS name in addr, if any.
func dnsName(addr string) string {
	host, _, err := net.SplitHostPort(addr)
	if err != nil {
		return ""
	}
	return host
}

// Certificates are cached locally to avoid unnecessary regeneration
const certCacheMaxSize = 1000

var (
	certCache      = make(map[*tls.Certificate]map[string]*tls.Certificate)
	certCacheMutex sync.RWMutex
)

func getCert(ca *tls.Certificate, host string) (*tls.Certificate, error) {
	if c := getCachedCert(ca, host); c != nil {
		return c, nil
	}
	cert, err := GenerateCert(ca, host)
	if err != nil {
		return nil, err
	}
	cacheCert(ca, host, cert)
	return cert, nil
}

func getCachedCert(ca *tls.Certificate, host string) *tls.Certificate {
	certCacheMutex.RLock()
	defer certCacheMutex.RUnlock()

	if certCache[ca] == nil {
		return nil
	}
	cert := certCache[ca][host]
	if cert == nil || cert.Leaf.NotAfter.Before(time.Now()) {
		return nil
	} else {
		return cert
	}
}

func cacheCert(ca *tls.Certificate, host string, cert *tls.Certificate) {
	certCacheMutex.Lock()
	defer certCacheMutex.Unlock()

	if certCache[ca] == nil || len(certCache[ca]) > certCacheMaxSize {
		certCache[ca] = make(map[string]*tls.Certificate)
	}
	certCache[ca][host] = cert
}
<|endoftext|>


<commit_before>// Copyright 2013 Andreas Koch. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package repository

import (
	"time"
)

type MetaData struct {
	Language         string
	CreationDate     time.Time
	LastModifiedDate time.Time
	Tags             Tags
	ItemType         string
	Alias            string
	Author           string
	Locations        Locations
	GeoData          GeoInformation
}

func NewMetaData() MetaData {
	return MetaData{}
}

type GeoInformation struct {
	Street    string
	City      string
	Postcode  string
	Country   string
	Latitude  string
	Longitude string
	MapType   string
	Zoom      int
}

func NewGeoInformation() GeoInformation {
	return GeoInformation{}
}
<commit_msg>Meta Data Default: Set default values for the language, creationdate and last modified date. The language should come from the config at some point.<commit_after>// Copyright 2013 Andreas Koch. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package repository

import (
	"time"
)

type MetaData struct {
	Language         string
	CreationDate     time.Time
	LastModifiedDate time.Time
	Tags             Tags
	ItemType         string
	Alias            string
	Author           string
	Locations        Locations
	GeoData          GeoInformation
}

func NewMetaData() MetaData {

	now := time.Now()

	return MetaData{
		Language:         "en",
		CreationDate:     now,
		LastModifiedDate: now,
	}
}

type GeoInformation struct {
	Street    string
	City      string
	Postcode  string
	Country   string
	Latitude  string
	Longitude string
	MapType   string
	Zoom      int
}

func NewGeoInformation() GeoInformation {
	return GeoInformation{}
}
<|endoftext|>


<commit_before>// +build integração

package testes

import (
	"bytes"
	"context"
	"encoding/json"
	"flag"
	"fmt"
	"net/http"
	"os"
	"testing"
	"time"

	"github.com/docker/libcompose/docker"
	"github.com/docker/libcompose/docker/ctx"
	"github.com/docker/libcompose/project"
	"github.com/docker/libcompose/project/options"
	"github.com/rafaeljusto/atiradorfrequente/núcleo/protocolo"
)

var endereçoServidor string

func TestCriaçãoDeFrequência(t *testing.T) {
	cenários := []struct {
		descrição          string
		requisição         *http.Request
		códigoHTTPEsperado int
		corpoEsperado      string
	}{
		{
			descrição: "deve criar corretamente uma frequência",
			requisição: func() *http.Request {
				frequênciaPedido := protocolo.FrequênciaPedido{
					Calibre:           "calibre .380",
					ArmaUtilizada:     "arma do clube",
					NúmeroSérie:       "za785671",
					GuiaDeTráfego:     762556223,
					QuantidadeMunição: 50,
					DataInício:        time.Now().Add(-30 * time.Minute),
					DataTérmino:       time.Now().Add(-10 * time.Minute),
				}

				corpo, err := json.Marshal(frequênciaPedido)
				if err != nil {
					t.Fatalf("Erro ao gerar os dados da requisição. Detalhes: %s", err)
				}

				url := fmt.Sprintf("http://%s/frequencia/380308", endereçoServidor)
				r, err := http.NewRequest("POST", url, bytes.NewReader(corpo))
				if err != nil {
					t.Fatalf("Erro ao gerar a requisição. Detalhes: %s", err)
				}

				return r
			}(),
			códigoHTTPEsperado: http.StatusCreated,
		},
	}

	for _, cenário := range cenários {
		t.Run(cenário.descrição, func(t *testing.T) {
			var cliente http.Client

			resposta, err := cliente.Do(cenário.requisição)
			if err != nil {
				t.Fatalf("Erro inesperado ao enviar a requisição. Detalhes: %s", err)
			}

			if resposta.StatusCode != cenário.códigoHTTPEsperado {
				t.Errorf("Código HTTP inesperado. Esperava “%d” e obteve “%d”", cenário.códigoHTTPEsperado, resposta.StatusCode)
			}
		})
	}
}

func TestMain(m *testing.M) {
	flag.Parse()

	código := 0
	defer func() {
		os.Exit(código)
	}()

	projeto, err := docker.NewProject(&ctx.Context{
		Context: project.Context{
			ComposeFiles: []string{"docker-compose.yml"},
			ProjectName:  "atiradorfrequente",
		},
	}, nil)

	if err != nil {
		fmt.Printf("Erro ao inicializar o projeto para testes. Detalhes: %s\n", err)
		código = 1
		return
	}

	err = projeto.Up(context.Background(), options.Up{
		Create: options.Create{
			ForceRecreate: true,
			ForceBuild:    true,
		},
	})

	if err != nil {
		fmt.Printf("Erro ao executar o projeto para testes. Detalhes: %s\n", err)
		código = 2
		return
	}

	defer func() {
		err = projeto.Down(context.Background(), options.Down{
			RemoveVolume:  true,
			RemoveImages:  options.ImageType("all"),
			RemoveOrphans: true,
		})

		if err != nil {
			fmt.Printf("Erro ao finalizar o projeto de testes. Detalhes: %s\n", err)
		}
	}()

	// temos que aguardar todos as dependências serem executadas antes de rodar o
	// teste principal
	time.Sleep(10 * time.Second)

	endereçoServidor, err = projeto.Port(context.Background(), 1, "tcp", "restaf", "80")
	if err != nil {
		fmt.Printf("Erro ao obter informações da porta do servidor rest.af. Detalhes: %s\n", err)
		código = 3
		return
	}

	código = m.Run()
}
<commit_msg>Sempre remove os containers de teste<commit_after>// +build integração

package testes

import (
	"bytes"
	"context"
	"encoding/json"
	"flag"
	"fmt"
	"net/http"
	"os"
	"testing"
	"time"

	"github.com/docker/libcompose/docker"
	"github.com/docker/libcompose/docker/ctx"
	"github.com/docker/libcompose/project"
	"github.com/docker/libcompose/project/options"
	"github.com/rafaeljusto/atiradorfrequente/núcleo/protocolo"
)

var endereçoServidor string

func TestCriaçãoDeFrequência(t *testing.T) {
	cenários := []struct {
		descrição          string
		requisição         *http.Request
		códigoHTTPEsperado int
		corpoEsperado      string
	}{
		{
			descrição: "deve criar corretamente uma frequência",
			requisição: func() *http.Request {
				frequênciaPedido := protocolo.FrequênciaPedido{
					Calibre:           "calibre .380",
					ArmaUtilizada:     "arma do clube",
					NúmeroSérie:       "za785671",
					GuiaDeTráfego:     762556223,
					QuantidadeMunição: 50,
					DataInício:        time.Now().Add(-30 * time.Minute),
					DataTérmino:       time.Now().Add(-10 * time.Minute),
				}

				corpo, err := json.Marshal(frequênciaPedido)
				if err != nil {
					t.Fatalf("Erro ao gerar os dados da requisição. Detalhes: %s", err)
				}

				url := fmt.Sprintf("http://%s/frequencia/380308", endereçoServidor)
				r, err := http.NewRequest("POST", url, bytes.NewReader(corpo))
				if err != nil {
					t.Fatalf("Erro ao gerar a requisição. Detalhes: %s", err)
				}

				return r
			}(),
			códigoHTTPEsperado: http.StatusCreated,
		},
	}

	for _, cenário := range cenários {
		t.Run(cenário.descrição, func(t *testing.T) {
			var cliente http.Client

			resposta, err := cliente.Do(cenário.requisição)
			if err != nil {
				t.Fatalf("Erro inesperado ao enviar a requisição. Detalhes: %s", err)
			}

			if resposta.StatusCode != cenário.códigoHTTPEsperado {
				t.Errorf("Código HTTP inesperado. Esperava “%d” e obteve “%d”", cenário.códigoHTTPEsperado, resposta.StatusCode)
			}
		})
	}
}

func TestMain(m *testing.M) {
	flag.Parse()

	código := 0
	defer func() {
		os.Exit(código)
	}()

	projeto, err := docker.NewProject(&ctx.Context{
		Context: project.Context{
			ComposeFiles: []string{"docker-compose.yml"},
			ProjectName:  "atiradorfrequente",
		},
	}, nil)

	if err != nil {
		fmt.Printf("Erro ao inicializar o projeto para testes. Detalhes: %s\n", err)
		código = 1
		return
	}

	defer func() {
		err = projeto.Down(context.Background(), options.Down{
			RemoveVolume:  true,
			RemoveImages:  options.ImageType("all"),
			RemoveOrphans: true,
		})

		if err != nil {
			fmt.Printf("Erro ao finalizar o projeto de testes. Detalhes: %s\n", err)
		}
	}()

	err = projeto.Up(context.Background(), options.Up{
		Create: options.Create{
			ForceRecreate: true,
			ForceBuild:    true,
		},
	})

	if err != nil {
		fmt.Printf("Erro ao executar o projeto para testes. Detalhes: %s\n", err)
		código = 2
		return
	}

	// temos que aguardar todos as dependências serem executadas antes de rodar o
	// teste principal
	time.Sleep(10 * time.Second)

	endereçoServidor, err = projeto.Port(context.Background(), 1, "tcp", "restaf", "80")
	if err != nil {
		fmt.Printf("Erro ao obter informações da porta do servidor rest.af. Detalhes: %s\n", err)
		código = 3
		return
	}

	código = m.Run()
}
<|endoftext|>


<commit_before>package kiwi_test

/*
Copyright (c) 2016, Alexander I.Grafov aka Axel
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

* Neither the name of kvlog nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

ॐ तारे तुत्तारे तुरे स्व
*/

import (
	"bytes"
	"strings"
	"testing"

	"github.com/grafov/kiwi"
)

func TestGlobalLog_IntValuesInLogfmt(t *testing.T) {
	output := bytes.NewBufferString("")
	out := kiwi.SinkTo(output, kiwi.UseLogfmt()).Start()
	defer out.Close()

	kiwi.Log("k", 123)

	out.Flush()
	if strings.TrimSpace(output.String()) != "k=123" {
		t.Fail()
	}
}

func TestGlobalLog_StringValuesInLogfmt(t *testing.T) {
	output := bytes.NewBufferString("")
	out := kiwi.SinkTo(output, kiwi.UseLogfmt()).Start()
	defer out.Close()

	kiwi.Log("k", "value")

	out.Flush()
	if strings.TrimSpace(output.String()) != "k=\"value\"" {
		t.Fail()
	}
}
<commit_msg>Add unit tests for global logger.<commit_after>package kiwi_test

/*
Copyright (c) 2016, Alexander I.Grafov aka Axel
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

* Neither the name of kvlog nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

ॐ तारे तुत्तारे तुरे स्व
*/

import (
	"github.com/grafov/kiwi"

	"bytes"
	"fmt"
	"strings"
	"testing"
	"time"
)

// Test logging of string value.
func TestGlobalLogger_LogStringValue_Logfmt(t *testing.T) {
	output := bytes.NewBufferString("")
	out := kiwi.SinkTo(output, kiwi.UseLogfmt()).Start()
	defer out.Close()

	kiwi.Log("k", "The sample string with a lot of spaces.")

	out.Flush()
	if strings.TrimSpace(output.String()) != "k=\"The sample string with a lot of spaces.\"" {
		t.Fail()
	}
}

// Test logging of byte array.
func TestGlobalLogger_LogBytesValue_Logfmt(t *testing.T) {
	output := bytes.NewBufferString("")
	out := kiwi.SinkTo(output, kiwi.UseLogfmt()).Start()
	defer out.Close()

	kiwi.Log("k", []byte("The sample string with a lot of spaces."))

	out.Flush()
	if strings.TrimSpace(output.String()) != "k=\"The sample string with a lot of spaces.\"" {
		t.Fail()
	}
}

// Test logging of integer value.
func TestGlobalLogger_LogIntValue_Logfmt(t *testing.T) {
	output := bytes.NewBufferString("")
	out := kiwi.SinkTo(output, kiwi.UseLogfmt()).Start()
	defer out.Close()

	kiwi.Log("k", 123)

	out.Flush()
	if strings.TrimSpace(output.String()) != "k=123" {
		t.Fail()
	}
}

// Test logging of negative integer value.
func TestGlobalLogger_LogNegativeIntValue_Logfmt(t *testing.T) {
	output := bytes.NewBufferString("")
	out := kiwi.SinkTo(output, kiwi.UseLogfmt()).Start()
	defer out.Close()

	kiwi.Log("k", 123)

	out.Flush()
	if strings.TrimSpace(output.String()) != "k=123" {
		t.Fail()
	}
}

// Test logging of float value in default (scientific) format.
func TestGlobalLogger_LogFloatValue_Logfmt(t *testing.T) {
	output := bytes.NewBufferString("")
	out := kiwi.SinkTo(output, kiwi.UseLogfmt()).Start()
	defer out.Close()

	kiwi.Log("k", 3.14159265359)

	out.Flush()
	if strings.TrimSpace(output.String()) != "k=3.14159265359e+00" {
		t.Fail()
	}
}

// Test logging of float value in fixed format.
func TestGlobalLogger_LogFixedFloatValue_Logfmt(t *testing.T) {
	output := bytes.NewBufferString("")
	out := kiwi.SinkTo(output, kiwi.UseLogfmt()).Start()
	defer out.Close()

	kiwi.FloatFormat = 'f'
	kiwi.Log("k", 3.14159265359)

	out.Flush()
	if strings.TrimSpace(output.String()) != "k=3.14159265359" {
		t.Fail()
	}
	// Turn back to default format.
	kiwi.FloatFormat = 'e'
}

// Test logging of boolean value.
func TestGlobalLogger_LogBoolValue_Logfmt(t *testing.T) {
	output := bytes.NewBufferString("")
	out := kiwi.SinkTo(output, kiwi.UseLogfmt()).Start()
	defer out.Close()

	kiwi.Log("k", true, "k2", false)

	out.Flush()
	if strings.TrimSpace(output.String()) != "k=true k2=false" {
		t.Fail()
	}
}

// Test logging of complex number.
func TestGlobalLogger_LogComplexValue_Logfmt(t *testing.T) {
	output := bytes.NewBufferString("")
	out := kiwi.SinkTo(output, kiwi.UseLogfmt()).Start()
	defer out.Close()

	kiwi.Log("k", .12345E+5i, "k2", 1.e+0i)

	out.Flush()
	if strings.TrimSpace(output.String()) != "k=(0.000000+12345.000000i) k2=(0.000000+1.000000i)" {
		t.Fail()
	}
}

// Test logging of time literal.
func TestGlobalLogger_LogTimeValue_Logfmt(t *testing.T) {
	output := bytes.NewBufferString("")
	out := kiwi.SinkTo(output, kiwi.UseLogfmt()).Start()
	value := time.Now()
	valueString := value.Format(kiwi.TimeLayout)
	defer out.Close()

	kiwi.Log("k", value)

	out.Flush()
	if strings.TrimSpace(output.String()) != fmt.Sprintf("k=%s", valueString) {
		t.Fail()
	}
}
<|endoftext|>


<commit_before>package main

import (
	"github.com/toorop/go-bitcoind"
	"log"
)

const (
	SERVER_HOST       = ""
	SERVER_PORT       = 8334
	USER              = "bitcoinrpc"
	PASSWD            = ""
	USESSL            = false
	WALLET_PASSPHRASE = ""
)

func main() {
	bc, err := bitcoind.New(SERVER_HOST, SERVER_PORT, USER, PASSWD, USESSL)
	if err != nil {
		log.Fatalln(err)
	}

	// backupwallet
	/*
		err = bc.BackupWallet("/tmp/wallet.dat")
		log.Println(err)
	*/

	// dumpprivkey
	/*
		privKey, err := bc.DumpPrivKey("1KU5DX7jKECLxh1nYhmQ7CahY7GMNMVLP3")
		log.Println(err, privKey)
	*/

	// encryptwallet
	/*
		err = bc.EncryptWallet(WALLET_PASSPHRASE)
		log.Println(err)
	*/

	// getaccount
	/*
		account, err := bc.GetAccount("1KU5DX7jKECLxh1nYhmQ7CahY7GMNMVLP3")
		log.Println(err, account)
	*/

	//getaccountaddress
	/*
		address, err := bc.GetAccountAddress("tests")
		log.Println(err, address)
	*/

	// GetAddressesByAccount
	/*
		addresses, err := bc.GetAddressesByAccount("tests")
		log.Println(err, addresses)
	*/

	// getbalance
	/*
		balance, err := bc.GetBalance("tests", 10)
		log.Println(err, balance)
	*/

	// getbestblockhash
	/*
		bestblockhash, err := bc.GetBestBlockhash()
		log.Println(err, bestblockhash)
	*/

	// getbestblockhash

	/*
		 bestBlockHash, err := bc.GetBestBlockhash()
		log.Println(err, bestBlockHash)
	*/

	// getblock
	/*
		block, err := bc.GetBlock("00000000000000003f8d1861d035e44d4297c49bd2517dc0a44ad73c7091926c")
		log.Println(err, block)
	*/

	// getblockcount
	/*
		count, err := bc.GetBlockCount()
		log.Println(err, count)
	*/

	// getblockhash
	/*
		hash, err := bc.GetBlockHash(0)
		log.Println(err, hash)
	*/

	// TODO a finir
	// getBlockTemplate
	/*
		template, err := bc.GetBlockTemplate([]string{"longpoll"}, "template")
		log.Println(err, template)
	*/

	// getconnectioncount
	/*
		count, err := bc.GetConnectionCount()
		log.Println(err, count)
	*/

	// getdifficulty
	difficulty, err := bc.GetDifficulty()
	log.Println(err, difficulty)

	// getinfo
	/*
		info, err := bc.GetInfo()
		log.Println(err, info)
	*/

	// getnewaddress
	/*
		newAddress, err := bc.GetNewAddress("tests", "toto")
		log.Println(err, newAddress)
	*/

}
<commit_msg>add examples<commit_after>package main

import (
	"github.com/toorop/go-bitcoind"
	"log"
)

const (
	SERVER_HOST        = ""
	SERVER_PORT        = 8334
	USER               = "bitcoinrpc"
	PASSWD             = "sss"
	USESSL             = false
	WALLET_PASSPHRASE  = "p1"
	WALLET_PASSPHRASE2 = "p2"
)

func main() {
	bc, err := bitcoind.New(SERVER_HOST, SERVER_PORT, USER, PASSWD, USESSL)
	if err != nil {
		log.Fatalln(err)
	}

	//walletpassphrase
	err = bc.WalletPassphrase(WALLET_PASSPHRASE, 3600)
	log.Println(err)

	// backupwallet
	/*
		err = bc.BackupWallet("/tmp/wallet.dat")
		log.Println(err)
	*/

	// dumpprivkey
	/*
		privKey, err := bc.DumpPrivKey("1KU5DX7jKECLxh1nYhmQ7CahY7GMNMVLP3")
		log.Println(err, privKey)
	*/

	// encryptwallet
	/*
		err = bc.EncryptWallet(WALLET_PASSPHRASE)
		log.Println(err)
	*/

	// getaccount
	/*
		account, err := bc.GetAccount("1KU5DX7jKECLxh1nYhmQ7CahY7GMNMVLP3")
		log.Println(err, account)
	*/

	//getaccountaddress
	/*
		address, err := bc.GetAccountAddress("tests")
		log.Println(err, address)
	*/
	// GetAddressesByAccount
	/*
		addresses, err := bc.GetAddressesByAccount("tests")
		log.Println(err, addresses)
	*/

	// getaddressbyaccount
	/*
		address, err := bc.GetAddressesByAccount("tests")
		log.Println(err, address)
	*/

	// getbalance
	/*
		balance, err := bc.GetBalance("tests", 0)
		log.Println(err, balance)
	*/

	// getbestblockhash
	/*
		bestblockhash, err := bc.GetBestBlockhash()
		log.Println(err, bestblockhash)
	*/

	// getblock
	/*
		block, err := bc.GetBlock("00000000000000003f8d1861d035e44d4297c49bd2517dc0a44ad73c7091926c")
		log.Println(err, block)
	*/

	// getblockcount
	/*
		count, err := bc.GetBlockCount()
		log.Println(err, count)
	*/

	// getblockhash
	/*
		hash, err := bc.GetBlockHash(0)
		log.Println(err, hash)
	*/
	// TODO a finir
	// getBlockTemplate
	/*
		template, err := bc.GetBlockTemplate([]string{"longpoll"}, "template")
		log.Println(err, template)
	*/

	// getconnectioncount
	/*
		count, err := bc.GetConnectionCount()
		log.Println(err, count)
	*/
	// getdifficulty
	/*
		difficulty, err := bc.GetDifficulty()
		log.Println(err, difficulty)
	*/

	// getgenerate
	/*
		generate, err := bc.GetGenerate()
		log.Println(err, generate)
	*/

	// gethashespersec
	/*
		hashpersec, err := bc.GetHashesPerSec()
		log.Println(hashpersec, err)
	*/

	// getinfo
	/*
		info, err := bc.GetInfo()

		log.Println(err, info)
	*/

	// getmininginfo
	/*
		mininginfo, err := bc.GetMiningInfo()
		log.Println(err, mininginfo)
	*/

	// getnewaddress
	/*
		newAddress, err := bc.GetNewAddress("test2")
		log.Println(err, newAddress)
	*/

	// getpeerinfo
	/*
		peerInfo, err := bc.GetPeerInfo()
		log.Println(err, peerInfo)
	*/

	// GetRawChangeAddress
	/*
		rawAddress, err := bc.GetRawChangeAddress("tests")
		log.Println(err, rawAddress)
	*/

	// GetRawMempool
	/*
		txIds, err := bc.GetRawMempool()
		log.Println(err, txIds)
	*/

	// getrawtransaction
	/*
		 rawTransaction, err := bc.GetRawTransaction("00010589f7c108a4fd546df03a17bf485ede3baf52b35ddd5b83e974ec360abf", 1)
		log.Println(err, rawTransaction)
	*/

	// GetReceivedByAccount
	/*
		amount, err := bc.GetReceivedByAccount("all", 1)
		log.Println(err, amount)
	*/

	// GetReceivedByAddress
	/*
		amount, err := bc.GetReceivedByAddress("1Pyizp4HK7Bfz7CdbSwHHtprk7Ghumhxmy", 0)
		log.Println(err, amount)
	*/

	// GetTransaction
	/*
		transaction, err := bc.GetTransaction("a1b7093d041bc1b763ba1ad894d2bd5376b38e6c7369613684e7140e8d9f7515")
		log.Println(err, transaction)
	*/

	// GetTxOut
	/*
		transaction, err := bc.GetTxOut("a1b7093d041bc1b763ba1ad894d2bd5376b38e6c7369613684e7140e8d9f7515", 1, false)
		log.Println(err, transaction)
	*/

	// GetTxOutsetInfo
	/*
		tx, err := bc.GetTxOutsetInfo()
		log.Println(err, tx)
	*/

	// GetWork
	/*
		work, err := bc.GetWork("00000002439aa25207d0b0d91162ecaad3e306d7df6a514d0f1c372c0000000000000000ea834758ea6ed14b00f9951befe6a6c819dcf9f32c20b37ba1308e66305fca4e537cf6b4187c305300000000000000800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000")
		//work, err := bc.GetWork()
		log.Println(err, work)
	*/

	// ImportPrivKey
	/*
		err = bc.ImportPrivKey("KFAKEZmymFAKECuxFAKECmFAKEcFAKEjxFAKEUoFAKE85FAKEi9", "imported from space", false)
		log.Println(err)
	*/

	// KeyPoolRefill
	/*
		err = bc.KeyPoolRefill()
		log.Println(err)
	*/

	// ListAccount
	/*
		accounts, err := bc.ListAccounts(1)
		log.Println(err, accounts)
	*/

	// ListAddressGroupings
	/*
		list, err := bc.ListAddressGroupings()
		log.Println(err, list)
	*/

	// ListReceivedByAccount
	/*
		list, err := bc.ListReceivedByAccount(1, true)
		log.Println(err, list)
	*/
	// ListReceivedByAddress
	/*
		list, err := bc.ListReceivedByAddress(1, true)
		log.Println(err, list)
	*/

	// ListSinceBlock
	/*
		 transactions, err := bc.ListSinceBlock("00000000000000003f8d1861d035e44d4297c49bd2517dc0a44ad73c7091926c", 1)
		log.Println(err, transactions)
	*/

	// ListTransactions
	/*
		transactions, err := bc.ListTransactions("tests", 10, 0)
		log.Println(err, transactions)
	*/

	// ListUnspent
	/*
		transactions, err := bc.ListUnspent(1, 9999)
		log.Println(err, transactions)
	*/

	// LockUnspent
	/*
		success, err := bc.LockUnspent(false, []bitcoind.UnspendableOutput{{"61195c9a04eb4bb6ef7c1d360e472b1620c4befed611ddcab46a6b2711344cd5", 0}, {"a1b7093d041bc1b763ba1ad894d2bd5376b38e6c7369613684e7140e8d9f7515", 0}})
		log.Println(err, success)
	*/

	// ListLockUnspent
	/*
		unspentLocked, err := bc.ListLockUnspent()
		log.Println(err, unspentLocked)
	*/

	// Move
	/*
		success, err := bc.Move("tests1", "test2", 0.0001, 1, "Move test")
		log.Println(err, success)
	*/

	// senfrom
	/*
		txID, err := bc.SendFrom("test2", "1HgpsmxV52eAjDcoNpVGpYEhGfgN7mM1JB", 0.0001, 1, "Comment: Envoit depuis test2", "commentTo: envoit depuis test2")
		log.Println(err, txID)
	*/

	// sendmany
	/*
		amounts := make(map[string]float64)
		amounts["1HgpsmxV52eAjDcoNpVGpYEhGfgN7mM1JB"] = 0.0001
		amounts["1Ldfez73eanxUZhudrS62BXqk8BrLxYQFj"] = 0.0001
		txID, err := bc.SendMany("tests", amounts, 1, "test sendMany")
		log.Println(err, txID)
	*/

	// sendtoaddress
	/*
		txID, err := bc.SendToAddress("1Ldfez73eanxUZhudrS62BXqk8BrLxYQFj", 0.0001, "send to address test", "send to cx")
		log.Println(err, txID)
	*/

	// setaccount
	/*
		err = bc.SetAccount("1KU5DX7jKECLxh1nYhmQ7CahY7GMNMVLP3", "tests")
		log.Println(err)
	*/

	// setgenerate
	/*
		err = bc.SetGenerate(false, 1)
		log.Println(err)
	*/

	// settxfee
	/*
		err = bc.SetTxFee(0.00001)
		log.Println(err)
	*/

	// SignMessage
	/*
		sig, err := bc.SignMessage("1Pyizp4HK7Bfz7CdbSwHHtprk7Ghumhxmy", "test message")
		log.Println(err, sig)
	*/

	// stop
	/*
		err = bc.Stop()
		log.Println(err)
	*/

	// ValidateAddress
	/*
		va, err := bc.ValidateAddress("1HgpsmxV52eAjDcoNpVGpYEhGfgN7mM1JB")
		log.Println(err, va)
	*/

	// verifymessage
	/*
		err = bc.VerifyMessage("1Pyizp4HK7Bfz7CdbSwHHtprk7Ghumhxmy", "IDIM8ITWfjyf/e9jaY3+P1ErTDRVdpD3YKmTlVlhuBhwZ/qgnLf+M0GTSXgFWCv4dL3rV+x5ymZJagqy19iRFg4=", "test message")
		log.Println(err)
	*/

	// walletlock
	/*
		err = bc.WalletLock()
		log.Println(err)
	*/

	// WalletPassphraseChange
	/*
		err = bc.WalletPassphraseChange(WALLET_PASSPHRASE2, WALLET_PASSPHRASE)
		log.Println(err)
	*/
}
<|endoftext|>