<commit_before>package main

import (
	"github.com/prometheus/client_golang/prometheus"
	"strings"
)

// Resets the guageVecs back to 0
// Ensures we start from a clean sheet
func (e *Exporter) resetGaugeVecs() {
	for _, m := range e.gaugeVecs {
		m.Reset()
	}
}

// Describe describes all the metrics ever exported by the Rancher exporter
func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {
	for _, m := range e.gaugeVecs {
		m.Describe(ch)
	}
}

// Collect function, called on by Prometheus Client library
func (e *Exporter) Collect(ch chan<- prometheus.Metric) {
	e.mutex.Lock() // To protect metrics from concurrent collects.
	defer e.mutex.Unlock()

	e.resetGaugeVecs() // Clean starting point

	var endpointOfApi []string
	if strings.HasSuffix(rancherURL, "v3") || strings.HasSuffix(rancherURL, "v3/") {
		endpointOfApi = endpointsV3
	} else {
		endpointOfApi = endpoints
	}
	// Range over the pre-configured endpoints array
	for _, p := range endpointOfApi {

		var data, err = e.gatherData(e.rancherURL, e.resourceLimit, e.accessKey, e.secretKey, p, ch)

		if err != nil {
			log.Error("Error getting JSON from URL ", p)
			return
		}

		if err := e.processMetrics(data, p, e.hideSys, ch); err != nil {
			log.Errorf("Error scraping rancher url: %s", err)
			return
		}
		log.Infof("Metrics successfully processed for %s", p)

	}

	for _, m := range e.gaugeVecs {
		m.Collect(ch)
	}
}
<commit_msg>small fix syntax<commit_after>package main

import (
	"strings"

	"github.com/prometheus/client_golang/prometheus"
)

// Resets the guageVecs back to 0
// Ensures we start from a clean sheet
func (e *Exporter) resetGaugeVecs() {
	for _, m := range e.gaugeVecs {
		m.Reset()
	}
}

// Describe describes all the metrics ever exported by the Rancher exporter
func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {
	for _, m := range e.gaugeVecs {
		m.Describe(ch)
	}
}

// Collect function, called on by Prometheus Client library
func (e *Exporter) Collect(ch chan<- prometheus.Metric) {
	e.mutex.Lock() // To protect metrics from concurrent collects.
	defer e.mutex.Unlock()

	e.resetGaugeVecs() // Clean starting point

	var endpointOfAPI []string
	if strings.HasSuffix(rancherURL, "v3") || strings.HasSuffix(rancherURL, "v3/") {
		endpointOfAPI = endpointsV3
	} else {
		endpointOfAPI = endpoints
	}
	// Range over the pre-configured endpoints array
	for _, p := range endpointOfAPI {

		var data, err = e.gatherData(e.rancherURL, e.resourceLimit, e.accessKey, e.secretKey, p, ch)

		if err != nil {
			log.Error("Error getting JSON from URL ", p)
			return
		}

		if err := e.processMetrics(data, p, e.hideSys, ch); err != nil {
			log.Errorf("Error scraping rancher url: %s", err)
			return
		}
		log.Infof("Metrics successfully processed for %s", p)

	}

	for _, m := range e.gaugeVecs {
		m.Collect(ch)
	}
}
<|endoftext|>


<commit_before>package txtdirect

import (
	"sync"
	"time"

	"github.com/prometheus/client_golang/prometheus"
)

// Prometheus contains Prometheus's configuration
type Prometheus struct {
	Enable  bool
	Address string
	Path    string
}

var (
	RequestsCount = prometheus.NewCounterVec(prometheus.CounterOpts{
		Namespace: "txtdirect",
		Name:      "total_requests_per_host",
		Help:      "Total requests per host",
	}, []string{"host"})
	RequestsByStatus = prometheus.NewCounterVec(prometheus.CounterOpts{
		Namespace: "txtdirect",
		Name:      "total_returned_statuses_per_host",
		Help:      "Total returned statuses per host",
	}, []string{"host", "status"})

	once sync.Once
)

const (
	shutdownTimeout time.Duration = time.Second * 5
	// prometheusAddr is the address the where the metrics are exported by default.
	prometheusAddr string = "localhost:9191"
	prometheusPath string = "/metrics"
)

func NewPrometheus(addr, path string) *Prometheus {
	if addr == "" || path == "" {
		addr = prometheusAddr
		path = prometheusPath
	}
	p := &Prometheus{
		Path:    path,
		Address: addr,
	}
	return p
}

func (p *Prometheus) Start() {
	prometheus.Register(RequestsCount)
	prometheus.Register(RequestsByStatus)
}
<commit_msg>(prometheus): Only register counters once<commit_after>package txtdirect

import (
	"sync"
	"time"

	"github.com/prometheus/client_golang/prometheus"
)

// Prometheus contains Prometheus's configuration
type Prometheus struct {
	Enable  bool
	Address string
	Path    string
}

var (
	RequestsCount = prometheus.NewCounterVec(prometheus.CounterOpts{
		Namespace: "txtdirect",
		Name:      "total_requests_per_host",
		Help:      "Total requests per host",
	}, []string{"host"})

	RequestsByStatus = prometheus.NewCounterVec(prometheus.CounterOpts{
		Namespace: "txtdirect",
		Name:      "total_returned_statuses_per_host",
		Help:      "Total returned statuses per host",
	}, []string{"host", "status"})

	once sync.Once
)

const (
	shutdownTimeout time.Duration = time.Second * 5
	// prometheusAddr is the address the where the metrics are exported by default.
	prometheusAddr string = "localhost:9191"
	prometheusPath string = "/metrics"
)

func NewPrometheus(addr, path string) *Prometheus {
	if addr == "" {
		addr = prometheusAddr
	}
	if path == "" {
		path = prometheusPath
	}
	p := &Prometheus{
		Path:    path,
		Address: addr,
	}
	return p
}

func (p *Prometheus) Start() {
	once.Do(func() {
		prometheus.MustRegister(RequestsCount)
		prometheus.MustRegister(RequestsByStatus)
	})
}
<|endoftext|>


<commit_before>package main

import (
"log"
	"os"
	"strings"

	"github.com/abadojack/whatlanggo"
	"github.com/donomii/throfflib"
)

//_ "net/http/pprof"

var lang = "en"

func main() {
	go func() {
		//log.Println(http.ListenAndServe("localhost:6060", nil))
	}()
	t := throfflib.MakeEngine()
	//t = throfflib.LoadGraphics(t)  //Add this to throfflib so it can be called from Throff as a word?
	//t = throfflib.LoadAudio(t)
	strs := os.Args[1:]
	log.Printf("Evaluating %v\n", strs)
	if len(strs) == 1 {
		for _, arg := range strs {
			if whatlanggo.Jpn == whatlanggo.Detect(arg).Lang {
				lang = "jp"
				//log.Println("Japanese detected")
			}
		}
	}
	//t = t.RunFile("bootstrapgo.lib")
	t = t.RunString(throfflib.BootStrapString(), "Internal Bootstrap")

	if len(strs) == 0 {
		t = t.RunString("PRINTLN [ Welcome to THROFF  v0.1.  Type HELP for help. ]", "repl")
		//t = t.RunString(" [ \nTHROFF v0.1.  Type HELP for help. ]", "repl")
		throfflib.Repl(t)
	} else {
		throfflib.PrintWarnings = false
		if lang == "jp" {
			throfflib.BraceMode = "forth"
			strs = strings.Split(strs[0], "　")
		}

		t = t.RunString("SPACE", "Command line evaluator") //We print the top of the stack after the calculation.  If the calculation returns nothing, we don't want to print "Stack empty"

		tokens := throfflib.StringsToTokens(strs)
		t.LoadTokens(tokens)

		t = t.Run()
		t.RunString("PRINTLN", "replprint")
	}
}
<commit_msg>Improve japanese prompt<commit_after>package main

import (
	//"log"
	"os"
	"strings"

	"github.com/abadojack/whatlanggo"
	"github.com/donomii/throfflib"
)

//_ "net/http/pprof"

var lang = "en"

func main() {
	go func() {
		//log.Println(http.ListenAndServe("localhost:6060", nil))
	}()
	t := throfflib.MakeEngine()
	//t = throfflib.LoadGraphics(t)  //Add this to throfflib so it can be called from Throff as a word?
	//t = throfflib.LoadAudio(t)
	strs := os.Args[1:]
	//log.Printf("Evaluating %v\n", strs)
	if len(strs) == 1 {
		for _, arg := range strs {
			if whatlanggo.Jpn == whatlanggo.Detect(arg).Lang {
				lang = "jp"
				//log.Println("Japanese detected")
			}
		}
	}
	//t = t.RunFile("bootstrapgo.lib")
	t = t.RunString(throfflib.BootStrapString(), "Internal Bootstrap")

	if len(strs) == 0 {
		//log.Printf("progname %v", os.Args[0])
		if strings.Contains(os.Args[0], "小日本語") {
			lang = "jp"
			t = t.RunString("PRINTLN [ 小日本語　0.1.  使い方ヘップを入力しなさい ] PRINTLN NEWLINE ", "repl")
		} else {
			t = t.RunString("PRINTLN [ Welcome to Throff　v0.1.  Type HELP for help. ] PRINTLN NEWLINE ", "repl")
		}
		//t = t.RunString(" [ \nTHROFF v0.1.  Type HELP for help. ]", "repl")
		throfflib.Repl(t, lang == "jp")
	} else {
		throfflib.PrintWarnings = false
		if lang == "jp" {
			throfflib.BraceMode = "forth"
			strs = strings.Split(strs[0], "　")
		}

		t = t.RunString("SPACE", "Command line evaluator") //We print the top of the stack after the calculation.  If the calculation returns nothing, we don't want to print "Stack empty"

		tokens := throfflib.StringsToTokens(strs)
		t.LoadTokens(tokens)

		t = t.Run()
		t.RunString("PRINTLN", "replprint")
	}
}
<|endoftext|>


<commit_before>package tddbc

import(
    "fmt"
)

type GridPoint struct {
    X int
    Y int
}

func (gridPoint GridPoint) getNotation() string {
    return fmt.Sprintf("(%v,%v)", gridPoint.X, gridPoint.Y)
}

func (gridPoint GridPoint) isNeighborOf(other GridPoint) bool {
    return (gridPoint.X == other.X     && gridPoint.Y == other.Y - 1) ||
           (gridPoint.X == other.X - 1 && gridPoint.Y == other.Y    ) ||
           (gridPoint.X == other.X     && gridPoint.Y == other.Y + 1) ||
           (gridPoint.X == other.X + 1 && gridPoint.Y == other.Y    )
}
<commit_msg>Do refactoring isNeighborOf() method.<commit_after>package tddbc

import(
    "fmt"
)

type GridPoint struct {
    X int
    Y int
}

func (gridPoint GridPoint) getNotation() string {
    return fmt.Sprintf("(%v,%v)", gridPoint.X, gridPoint.Y)
}

func (gridPoint GridPoint) isNeighborOf(other GridPoint) bool {
    return gridPoint.isTopOf(other) ||
           gridPoint.isBottomOf(other) ||
           gridPoint.isRightOf(other) ||
           gridPoint.isLeftOf(other)
}

func (gridPoint GridPoint) isTopOf(other GridPoint) bool {
    return gridPoint.X == other.X && gridPoint.Y == other.Y + 1
}
func (gridPoint GridPoint) isBottomOf(other GridPoint) bool {
    return gridPoint.X == other.X && gridPoint.Y == other.Y - 1
}
func (gridPoint GridPoint) isRightOf(other GridPoint) bool {
    return gridPoint.X == other.X + 1 && gridPoint.Y == other.Y
}
func (gridPoint GridPoint) isLeftOf(other GridPoint) bool {
    return gridPoint.X == other.X - 1 && gridPoint.Y == other.Y
}
<|endoftext|>


<commit_before>package somaproto

type ProtoRequestProperty struct {
	Custom  *ProtoPropertyCustom  `json:"custom,omitempty"`
	System  *ProtoPropertySystem  `json:"system,omitempty"`
	Service *ProtoPropertyService `json:"service,omitempty"`
	Native  *ProtoPropertyNative  `json:"native,omitempty"`
	Filter  *ProtoPropertyFilter  `json:"filter,omitempty"`
}

type ProtoResultProperty struct {
	Code    uint16                 `json:"code,omitempty"`
	Status  string                 `json:"status,omitempty"`
	Text    []string               `json:"text,omitempty"`
	Custom  []ProtoPropertyCustom  `json:"custom,omitempty"`
	System  []ProtoPropertySystem  `json:"system,omitempty"`
	Service []ProtoPropertyService `json:"service,omitempty"`
	Native  []ProtoPropertyNative  `json:"native,omitempty"`
	JobId   string                 `json:"jobid,omitempty"`
}

type ProtoPropertyCustom struct {
	Id         string `json:"id,omitempty"`
	Repository string `json:"repository,omitempty"`
	Property   string `json:"property,omitempty"`
	Value      string `json:"value,omitempty"`
}

type ProtoPropertySystem struct {
	Property string `json:"property,omitempty"`
	Value    string `json:"value,omitempty"`
}

type ProtoPropertyService struct {
	Property   string                 `json:"property,omitempty"`
	Team       string                 `json:"team,omitempty"`
	Attributes ProtoServiceAttributes `json:"attributes,omitempty"`
}

type ProtoPropertyNative struct {
	Property string `json:"property,omitempty"`
}

type ProtoServiceAttributes struct {
	ProtoTransport   []string `json:"proto_transport,omitempty"`
	ProtoApplication []string `json:"proto_application,omitempty"`
	Port             []string `json:"port,omitempty"`
	ProcessComm      []string `json:"process_comm,omitempty"`
	ProcessArgs      []string `json:"process_args,omitempty"`
	FilePath         []string `json:"file_path,omitempty"`
	DirectoryPath    []string `json:"directory_path,omitempty"`
	UnixSocketPath   []string `json:"unix_socket_path,omitempty"`
	Uid              []string `json:"uid,omitempty"`
	Tls              []string `json:"tls,omitempty"`
	SoftwareProvider []string `json:"software_provider,omitempty"`
}

type ProtoPropertyFilter struct {
	Property string `json:"property,omitempty"`
	Type     string `json:"type,omitempty"`
}

// vim: ts=4 sw=4 sts=4 noet fenc=utf-8 ffs=unix
<commit_msg>Update structs for properties<commit_after>package somaproto

type ProtoRequestProperty struct {
	Custom  *ProtoPropertyCustom  `json:"custom,omitempty"`
	System  *ProtoPropertySystem  `json:"system,omitempty"`
	Service *ProtoPropertyService `json:"service,omitempty"`
	Native  *ProtoPropertyNative  `json:"native,omitempty"`
	Filter  *ProtoPropertyFilter  `json:"filter,omitempty"`
}

type ProtoResultProperty struct {
	Code    uint16                 `json:"code,omitempty"`
	Status  string                 `json:"status,omitempty"`
	Text    []string               `json:"text,omitempty"`
	Custom  []ProtoPropertyCustom  `json:"custom,omitempty"`
	System  []ProtoPropertySystem  `json:"system,omitempty"`
	Service []ProtoPropertyService `json:"service,omitempty"`
	Native  []ProtoPropertyNative  `json:"native,omitempty"`
	JobId   string                 `json:"jobid,omitempty"`
}

type ProtoPropertyCustom struct {
	Id         string `json:"id,omitempty"`
	Repository string `json:"repository,omitempty"`
	Property   string `json:"property,omitempty"`
	Value      string `json:"value,omitempty"`
}

type ProtoPropertySystem struct {
	Property string `json:"property,omitempty"`
	Value    string `json:"value,omitempty"`
}

type ProtoPropertyService struct {
	Property   string                 `json:"property,omitempty"`
	Team       string                 `json:"team,omitempty"`
	Attributes ProtoServiceAttributes `json:"attributes,omitempty"`
}

type ProtoPropertyNative struct {
	Property string `json:"property,omitempty"`
}

type ProtoServiceAttributes struct {
	ProtoTransport   []string `json:"proto_transport,omitempty"`
	ProtoApplication []string `json:"proto_application,omitempty"`
	Port             []string `json:"port,omitempty"`
	ProcessComm      []string `json:"process_comm,omitempty"`
	ProcessArgs      []string `json:"process_args,omitempty"`
	FilePath         []string `json:"file_path,omitempty"`
	DirectoryPath    []string `json:"directory_path,omitempty"`
	UnixSocketPath   []string `json:"unix_socket_path,omitempty"`
	Uid              []string `json:"uid,omitempty"`
	Tls              []string `json:"tls,omitempty"`
	SoftwareProvider []string `json:"software_provider,omitempty"`
}

type ProtoPropertyFilter struct {
	Property   string `json:"property,omitempty"`
	Type       string `json:"type,omitempty"`
	Repository string `json:"type,omitempty"`
}

//
func (p *ProtoResultProperty) ErrorMark(err error, imp bool, found bool,
	length int) bool {
	if p.markError(err) {
		return true
	}
	if p.markImplemented(imp) {
		return true
	}
	if p.markFound(found, length) {
		return true
	}
	return p.markOk()
}

func (p *ProtoResultProperty) markError(err error) bool {
	if err != nil {
		p.Code = 500
		p.Status = "ERROR"
		p.Text = []string{err.Error()}
		return true
	}
	return false
}

func (p *ProtoResultProperty) markImplemented(f bool) bool {
	if f {
		p.Code = 501
		p.Status = "NOT IMPLEMENTED"
		return true
	}
	return false
}

func (p *ProtoResultProperty) markFound(f bool, i int) bool {
	if f || i == 0 {
		p.Code = 404
		p.Status = "NOT FOUND"
		return true
	}
	return false
}

func (p *ProtoResultProperty) markOk() bool {
	p.Code = 200
	p.Status = "OK"
	return false
}

// vim: ts=4 sw=4 sts=4 noet fenc=utf-8 ffs=unix
<|endoftext|>


<commit_before>package main

import (
	"bufio"
	"io"
	"strings"
)

type ServerProperties map[string]string

var (
	defaultMapSettings = ServerProperties{
		"allow-flight":                 "false",
		"allow-nether":                 "true",
		"announce-player-achievements": "true",
		"difficulty":                   "1",
		"enable-command-block":         "false",
		"force-gamemode":               "false",
		"gamemode":                     "0",
		"generate-structures":          "true",
		"generator-settings":           "",
		"hardcore":                     "false",
		"level-seed":                   "",
		"level-type":                   "DEFAULT",
		"max-build-height":             "256",
		"max-world-size":               "29999984",
		"motd":                         "A MineWebGen Server",
		"player-idle-timeout":          "0",
		"pvp":                  "true",
		"resource-pack":        "",
		"resource-pack-hash":   "",
		"spawn-animals":        "true",
		"spawn-monsters":       "true",
		"spawn-npcs":           "true",
		"spawn-protection":     "16",
		"use-native-transport": "true",
		"view-distance":        "10",
		"grow-trees":           "true",
	}
	defaultServerSettings = ServerProperties{
		"enable-query":                  "false",
		"enable-rcon":                   "false",
		"max-players":                   "20",
		"max-tick-time":                 "60000",
		"network-compression-threshold": "256",
		"online-mode":                   "true",
		"op-permission-level":           "4",
		"query.port":                    "25565",
		"rcon.password":                 "",
		"rcon.port":                     "25575",
		"server-ip":                     "",
		"server-port":                   "25565",
		"snooper-enabled":               "false",
		"white-list":                    "false",
		"verify-names":                  "true",
		"admin-slot":                    "false",
		"public":                        "true",
		"server-name":                   "",
		"max-connections":               "3",
	}
)

func DefaultMapSettings() ServerProperties {
	return defaultMapSettings.Clone()
}

func DefaultServerSettings() ServerProperties {
	return defaultServerSettings.Clone()
}

func (s ServerProperties) Clone() ServerProperties {
	m := make(ServerProperties)
	for k, v := range s {
		m[k] = v
	}
	return m
}

func (s ServerProperties) ReadFrom(r io.Reader) error {
	br := bufio.NewReader(r)
	data := make(map[string]string)
	for {
		l, err := br.ReadString('\n')
		if err != nil {
			if err == io.EOF {
				return nil
			}
			return err
		}
		if l[0] == '#' {
			continue
		}
		if l[len(l)-1] == '\r' {
			l = l[:len(l)-1]
		}
		parts := strings.SplitN(l, "=", 2)
		if len(parts) != 2 {
			continue
		}
		data[parts[0]] = parts[1]
	}
}

func (s ServerProperties) WriteTo(w io.Writer) error {
	toWrite := make([]byte, 0, 1024)
	for k, v := range s {
		toWrite = toWrite[:0]
		toWrite = append(toWrite, k...)
		toWrite = append(toWrite, '=')
		toWrite = append(toWrite, v...)
		toWrite = append(toWrite, '\n')
		_, err := w.Write(toWrite)
		if err != nil {
			return err
		}
	}
	return nil
}
<commit_msg>Corrected ServerProperties.ReadFrom<commit_after>package main

import (
	"bufio"
	"io"
	"strings"
)

type ServerProperties map[string]string

var (
	defaultMapSettings = ServerProperties{
		"allow-flight":                 "false",
		"allow-nether":                 "true",
		"announce-player-achievements": "true",
		"difficulty":                   "1",
		"enable-command-block":         "false",
		"force-gamemode":               "false",
		"gamemode":                     "0",
		"generate-structures":          "true",
		"generator-settings":           "",
		"hardcore":                     "false",
		"level-seed":                   "",
		"level-type":                   "DEFAULT",
		"max-build-height":             "256",
		"max-world-size":               "29999984",
		"motd":                         "A MineWebGen Server",
		"player-idle-timeout":          "0",
		"pvp":                  "true",
		"resource-pack":        "",
		"resource-pack-hash":   "",
		"spawn-animals":        "true",
		"spawn-monsters":       "true",
		"spawn-npcs":           "true",
		"spawn-protection":     "16",
		"use-native-transport": "true",
		"view-distance":        "10",
		"grow-trees":           "true",
	}
	defaultServerSettings = ServerProperties{
		"enable-query":                  "false",
		"enable-rcon":                   "false",
		"max-players":                   "20",
		"max-tick-time":                 "60000",
		"network-compression-threshold": "256",
		"online-mode":                   "true",
		"op-permission-level":           "4",
		"query.port":                    "25565",
		"rcon.password":                 "",
		"rcon.port":                     "25575",
		"server-ip":                     "",
		"server-port":                   "25565",
		"snooper-enabled":               "false",
		"white-list":                    "false",
		"verify-names":                  "true",
		"admin-slot":                    "false",
		"public":                        "true",
		"server-name":                   "",
		"max-connections":               "3",
	}
)

func DefaultMapSettings() ServerProperties {
	return defaultMapSettings.Clone()
}

func DefaultServerSettings() ServerProperties {
	return defaultServerSettings.Clone()
}

func (s ServerProperties) Clone() ServerProperties {
	m := make(ServerProperties)
	for k, v := range s {
		m[k] = v
	}
	return m
}

func (s ServerProperties) ReadFrom(r io.Reader) error {
	br := bufio.NewReader(r)
	for {
		l, err := br.ReadString('\n')
		if err != nil {
			if err == io.EOF {
				return nil
			}
			return err
		}
		if l[0] == '#' {
			continue
		}
		if l[len(l)-1] == '\r' {
			l = l[:len(l)-1]
		}
		parts := strings.SplitN(l, "=", 2)
		if len(parts) != 2 {
			continue
		}
		s[parts[0]] = parts[1]
	}
}

func (s ServerProperties) WriteTo(w io.Writer) error {
	toWrite := make([]byte, 0, 1024)
	for k, v := range s {
		toWrite = toWrite[:0]
		toWrite = append(toWrite, k...)
		toWrite = append(toWrite, '=')
		toWrite = append(toWrite, v...)
		toWrite = append(toWrite, '\n')
		_, err := w.Write(toWrite)
		if err != nil {
			return err
		}
	}
	return nil
}
<|endoftext|>


<commit_before>// Package crypto provides NaCl based encryption libraries.
package main

import (
	"log"

	"github.com/andmarios/crypto/nacl/padsecret"
	"github.com/andmarios/crypto/nacl/saltsecret"
)

// A 1 kilobyte message
var msg1K = []byte(`Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam egestas mi ut nisl lobortis rhoncus. Cras et tempus elit. Maecenas dictum viverra pretium. Integer porta felis lacus, ac maximus risus volutpat vel. Vivamus fermentum vitae turpis vitae lobortis. Quisque dictum, nunc eget blandit porttitor, risus nisl aliquam ante, vel congue nibh metus at velit. Suspendisse potenti. Pellentesque quis ipsum vitae tortor condimentum malesuada id vitae enim. Mauris mattis elit quis nibh venenatis, ut finibus mauris pulvinar. Duis facilisis tellus nec laoreet cursus. Sed mattis condimentum condimentum. Aenean a leo vel urna pharetra scelerisque tempor accumsan augue. Sed vel ante id turpis tempus ornare. Quisque lobortis enim auctor ipsum lacinia, et bibendum tortor pellentesque.

Vivamus ut elit nec arcu congue malesuada nec eget enim. Aliquam erat volutpat. Phasellus auctor consequat est et hendrerit. Nullam vitae odio ac nisi blandit viverra. Curabitur consequat urna quis ante molestie viverra. Donec malesuada amet.`)

func main() {
	// Saltsecret //
	// Create a saltsecret instance with "qwerty" key and no compression.
	skey := []byte("qwerty")
	s := saltsecret.New(skey, false)
	// Encrypt message
	sMsg, err := s.Encrypt(msg1K)
	if err != nil {
		log.Fatalln(err.Error())
	}
	log.Printf("Saltsecret uncompressed encrypted 1K message size is %d bytes due to overhead.\n", len(sMsg))
	// Decrypt message
	dMsg, err := s.Decrypt(sMsg)
	if err != nil {
		log.Fatalln("Could not decrypt message")
	}
	log.Println("Saltsecret decrypted message is:\n" + string(dMsg))
	// Create a cryptographer instance with "qwerty" key and compression.
	s = saltsecret.New(skey, true)
	// Encrypt message
	sMsg, err = s.Encrypt(msg1K)
	if err != nil {
		log.Fatalln(err.Error())
	}
	log.Printf("Saltsecret compressed encrypted 1K message size is %d bytes despite overhead.\n", len(sMsg))

	// Padsecret //
	// Create a padsecret instance with "qwerty" key and no compression.
	p, err := padsecret.New("qwerty", "qwertyuiopasdfghjklzxcvbnm123456", false)
	if err != nil {
		log.Fatalln(err)
	}
	// Encrypt message
	pMsg, err := p.Encrypt(msg1K)
	if err != nil {
		log.Fatalln(err.Error())
	}
	log.Printf("Padsecret uncompressed encrypted 1K message size is %d bytes due to overhead.\n", len(pMsg))
	// Decrypt message
	dMsg, err = p.Decrypt(pMsg)
	if err != nil {
		log.Fatalln("Could not decrypt message")
	}
	log.Println("Padsecret decrypted message is:\n" + string(dMsg))
}
<commit_msg>better crypto godoc<commit_after>// Package crypto provides NaCl based encryption libraries.
// For more information have a loot at:
// https://godoc.org/github.com/andmarios/crypto/nacl/padsecret
// https://godoc.org/github.com/andmarios/crypto/nacl/saltsecret
package main

import (
	"log"

	"github.com/andmarios/crypto/nacl/padsecret"
	"github.com/andmarios/crypto/nacl/saltsecret"
)

// A 1 kilobyte message
var msg1K = []byte(`Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam egestas mi ut nisl lobortis rhoncus. Cras et tempus elit. Maecenas dictum viverra pretium. Integer porta felis lacus, ac maximus risus volutpat vel. Vivamus fermentum vitae turpis vitae lobortis. Quisque dictum, nunc eget blandit porttitor, risus nisl aliquam ante, vel congue nibh metus at velit. Suspendisse potenti. Pellentesque quis ipsum vitae tortor condimentum malesuada id vitae enim. Mauris mattis elit quis nibh venenatis, ut finibus mauris pulvinar. Duis facilisis tellus nec laoreet cursus. Sed mattis condimentum condimentum. Aenean a leo vel urna pharetra scelerisque tempor accumsan augue. Sed vel ante id turpis tempus ornare. Quisque lobortis enim auctor ipsum lacinia, et bibendum tortor pellentesque.

Vivamus ut elit nec arcu congue malesuada nec eget enim. Aliquam erat volutpat. Phasellus auctor consequat est et hendrerit. Nullam vitae odio ac nisi blandit viverra. Curabitur consequat urna quis ante molestie viverra. Donec malesuada amet.`)

func main() {
	// Saltsecret //
	// Create a saltsecret instance with "qwerty" key and no compression.
	skey := []byte("qwerty")
	s := saltsecret.New(skey, false)
	// Encrypt message
	sMsg, err := s.Encrypt(msg1K)
	if err != nil {
		log.Fatalln(err.Error())
	}
	log.Printf("Saltsecret uncompressed encrypted 1K message size is %d bytes due to overhead.\n", len(sMsg))
	// Decrypt message
	dMsg, err := s.Decrypt(sMsg)
	if err != nil {
		log.Fatalln("Could not decrypt message")
	}
	log.Println("Saltsecret decrypted message is:\n" + string(dMsg))
	// Create a cryptographer instance with "qwerty" key and compression.
	s = saltsecret.New(skey, true)
	// Encrypt message
	sMsg, err = s.Encrypt(msg1K)
	if err != nil {
		log.Fatalln(err.Error())
	}
	log.Printf("Saltsecret compressed encrypted 1K message size is %d bytes despite overhead.\n", len(sMsg))

	// Padsecret //
	// Create a padsecret instance with "qwerty" key and no compression.
	p, err := padsecret.New("qwerty", "qwertyuiopasdfghjklzxcvbnm123456", false)
	if err != nil {
		log.Fatalln(err)
	}
	// Encrypt message
	pMsg, err := p.Encrypt(msg1K)
	if err != nil {
		log.Fatalln(err.Error())
	}
	log.Printf("Padsecret uncompressed encrypted 1K message size is %d bytes due to overhead.\n", len(pMsg))
	// Decrypt message
	dMsg, err = p.Decrypt(pMsg)
	if err != nil {
		log.Fatalln("Could not decrypt message")
	}
	log.Println("Padsecret decrypted message is:\n" + string(dMsg))
}
<|endoftext|>


<commit_before>package main

import (
	"mysql";
	"flag";
	"rand";
	"fmt";
	"os";
	"db";
)

var (
	host	string;
	port	int;
	user	string;
	pass	string;
	dbname	string;
	help	bool;
)

func init() {
	flag.StringVar(&host, "host", "127.0.0.1",
		"Connect to this MySQL host");
	flag.IntVar(&port, "port", 3306,
		"Connect on this port");
	flag.StringVar(&user, "user", "root",
		"Connect with this username");
	flag.StringVar(&pass, "pass", "",
		"Connect with this password");
	flag.StringVar(&dbname, "database", "test", "Default database");
	flag.BoolVar(&help, "help", false, "Print this help message and quit");
}

func main() {
	flag.Parse();
	if help { flag.Usage(); os.Exit(1) }

	conn, err := mysql.Open(map[string]interface{} {
		"host": host,
		"port": port,
		"user": user,
		"pass": pass,
		"database": dbname
	});
	fconn := conn.(db.FancyConnection);

	if err != nil {
		fmt.Printf("Error connecting to %s:%d: %s\n",
			host, port, err);
		flag.Usage();
		os.Exit(1)
	}
	var stmt db.Statement;

	fmt.Println("Creating temporary table __hello");
	_, e := fconn.ExecuteDirectly("CREATE TEMPORARY TABLE __hello (i INT)");
	if e != nil { fmt.Printf("Error: %s", err); os.Exit(1); }

	fmt.Println("Inserting 100 random numbers");
	stmt, e = conn.Prepare("INSERT INTO __hello (i) VALUE (?)");
	if e != nil { fmt.Printf("Error: %s\n", err); os.Exit(1); }

	for i := 0; i < 100; i+=1 {
		_, err = conn.Execute(stmt, rand.Int());
		if err != nil { fmt.Printf("Error: %s\n", err); os.Exit(1); }
	}
	stmt.Close();

	fmt.Println("Reading numbers in lexical order");
	stmt, e = conn.Prepare("SELECT i FROM __hello ORDER BY i ASC");
	if e != nil { fmt.Printf("Error: %s\n", err); os.Exit(1); }

	cur, _ := conn.Execute(stmt);
	for t, _ := cur.FetchOne(); t != nil; t, _ = cur.FetchOne() {
		if v, ok := t[0].(int); ok {
			fmt.Printf("%d\n", v)
		} else {
			fmt.Printf("Error converting %T to int\n", v)
		}
	}
	cur.Close();
	stmt.Close();

	conn.Close();
}
<commit_msg>add notice<commit_after>// Copyright 2009 Eden Li. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Example usage of mysqlgo.

package main

import (
	"mysql";
	"flag";
	"rand";
	"fmt";
	"os";
	"db";
)

var (
	host	string;
	port	int;
	user	string;
	pass	string;
	dbname	string;
	help	bool;
)

func init() {
	flag.StringVar(&host, "host", "127.0.0.1",
		"Connect to this MySQL host");
	flag.IntVar(&port, "port", 3306,
		"Connect on this port");
	flag.StringVar(&user, "user", "root",
		"Connect with this username");
	flag.StringVar(&pass, "pass", "",
		"Connect with this password");
	flag.StringVar(&dbname, "database", "test", "Default database");
	flag.BoolVar(&help, "help", false, "Print this help message and quit");
}

func main() {
	flag.Parse();
	if help { flag.Usage(); os.Exit(1) }

	conn, err := mysql.Open(map[string]interface{} {
		"host": host,
		"port": port,
		"user": user,
		"pass": pass,
		"database": dbname
	});
	fconn := conn.(db.FancyConnection);

	if err != nil {
		fmt.Printf("Error connecting to %s:%d: %s\n",
			host, port, err);
		flag.Usage();
		os.Exit(1)
	}
	var stmt db.Statement;

	fmt.Println("Creating temporary table __hello");
	_, e := fconn.ExecuteDirectly("CREATE TEMPORARY TABLE __hello (i INT)");
	if e != nil { fmt.Printf("Error: %s", err); os.Exit(1); }

	fmt.Println("Inserting 100 random numbers");
	stmt, e = conn.Prepare("INSERT INTO __hello (i) VALUE (?)");
	if e != nil { fmt.Printf("Error: %s\n", err); os.Exit(1); }

	for i := 0; i < 100; i+=1 {
		_, err = conn.Execute(stmt, rand.Int());
		if err != nil { fmt.Printf("Error: %s\n", err); os.Exit(1); }
	}
	stmt.Close();

	fmt.Println("Reading numbers in lexical order");
	stmt, e = conn.Prepare("SELECT i FROM __hello ORDER BY i ASC");
	if e != nil { fmt.Printf("Error: %s\n", err); os.Exit(1); }

	cur, _ := conn.Execute(stmt);
	for t, _ := cur.FetchOne(); t != nil; t, _ = cur.FetchOne() {
		if v, ok := t[0].(int); ok {
			fmt.Printf("%d\n", v)
		} else {
			fmt.Printf("Error converting %T to int\n", v)
		}
	}
	cur.Close();
	stmt.Close();

	conn.Close();
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"github.com/thanhson1085/go-dockerclient"
)

func main() {
	endpoint := "http://192.168.1.191:12375"
	client, _ := docker.NewClient(endpoint)
	// list of images
	imgs, _ := client.ListImages(docker.ListImagesOptions{All: false})
	for _, img := range imgs {
		fmt.Println(img.ID, img.RepoTags)
	}
	// top
	top, _ := client.TopContainer("7d1e304579e4", "aux")
	fmt.Println(top.Titles)
	for _, p := range top.Processes {
		fmt.Println(p)
	}
	statsOption := docker.StatsOptions{}
	stats := make(chan *docker.Stats)
	statsOption.ID = "7d1e304579e4"
	statsOption.Stream = true
	statsOption.Stats = stats
	done := make(chan bool)
	statsOption.Done = done
	errC := make(chan error, 1)
	go func() {
		errC <- client.Stats(statsOption)
		close(errC)
	}()
	for {
		s, ok := <-stats
		if !ok {
			break
		}
		fmt.Println("Network Stats", s.Networks["eth0"])
		fmt.Println("Memory Stats", s.MemoryStats)
	}
}
<commit_msg>add params<commit_after>package main

import (
	"fmt"
	"github.com/thanhson1085/go-dockerclient"
	"os"
)

func main() {
	args := os.Args
	endpoint := args[1]    //"http://192.168.1.191:12375"
	containerId := args[2] //7d1e304579e4

	client, _ := docker.NewClient(endpoint)
	// list of images
	imgs, _ := client.ListImages(docker.ListImagesOptions{All: false})
	for _, img := range imgs {
		fmt.Println(img.ID, img.RepoTags)
	}
	// top
	top, _ := client.TopContainer(containerId, "aux")
	fmt.Println(top.Titles)
	for _, p := range top.Processes {
		fmt.Println(p)
	}
	statsOption := docker.StatsOptions{}
	stats := make(chan *docker.Stats)
	statsOption.ID = containerId
	statsOption.Stream = true
	statsOption.Stats = stats
	done := make(chan bool)
	statsOption.Done = done
	errC := make(chan error, 1)
	go func() {
		errC <- client.Stats(statsOption)
		close(errC)
	}()
	for {
		s, ok := <-stats
		if !ok {
			break
		}
		fmt.Println("Network Stats", s.Networks["eth0"])
		fmt.Println("Memory Stats", s.MemoryStats)
	}
}
<|endoftext|>


<commit_before>package service

import (
	"context"
	"sync"
	"sync/atomic"
	"time"

	"github.com/zitryss/aye-and-nay/domain/model"
	"github.com/zitryss/aye-and-nay/pkg/errors"
)

func NewQueue(name string, q model.Queuer) *Queue {
	return &Queue{
		name:   name,
		queue:  q,
		cond:   sync.NewCond(&sync.Mutex{}),
		closed: false,
		valid:  true,
	}
}

type Queue struct {
	name   string
	queue  model.Queuer
	cond   *sync.Cond
	closed bool
	valid  bool
}

func (q *Queue) Monitor(ctx context.Context) {
	if q == nil || !q.valid {
		return
	}
	go func() {
		<-ctx.Done()
		q.cond.L.Lock()
		defer q.cond.L.Unlock()
		q.closed = true
		q.cond.Broadcast()
	}()
}

func (q *Queue) add(ctx context.Context, album string) error {
	if q == nil || !q.valid {
		return nil
	}
	err := q.queue.Add(ctx, q.name, album)
	if err != nil {
		return errors.Wrap(err)
	}
	q.cond.Signal()
	return nil
}

func (q *Queue) poll(ctx context.Context) (string, error) {
	if q == nil || !q.valid {
		return "", nil
	}
	q.cond.L.Lock()
	defer q.cond.L.Unlock()
	n, err := q.queue.Size(ctx, q.name)
	if err != nil {
		return "", errors.Wrap(err)
	}
	for n == 0 {
		q.cond.Wait()
		if q.closed {
			return "", nil
		}
		n, err = q.queue.Size(ctx, q.name)
		if err != nil {
			return "", errors.Wrap(err)
		}
	}
	album, err := q.queue.Poll(ctx, q.name)
	if err != nil {
		return "", errors.Wrap(err)
	}
	return album, nil
}

func NewPQueue(name string, pq model.PQueuer) *PQueue {
	return &PQueue{
		name:    name,
		pqueue:  pq,
		addCh:   make(chan struct{}),
		addBuff: make(chan struct{}, 1),
		done:    0,
		closed:  make(chan struct{}),
		valid:   true,
	}
}

type PQueue struct {
	name    string
	pqueue  model.PQueuer
	addCh   chan struct{}
	addBuff chan struct{}
	done    uint32
	closed  chan struct{}
	valid   bool
}

func (pq *PQueue) Monitor(ctx context.Context) {
	if pq == nil || !pq.valid {
		return
	}
	go func() {
		<-ctx.Done()
		pq.closed <- struct{}{}
	}()
	go func() {
		for {
			<-pq.addBuff
			pq.addCh <- struct{}{}
			atomic.StoreUint32(&pq.done, 0)
		}
	}()
}

func (pq *PQueue) add(ctx context.Context, album string, expires time.Time) error {
	if pq == nil || !pq.valid {
		return nil
	}
	err := pq.pqueue.PAdd(ctx, pq.name, album, expires)
	if err != nil {
		return errors.Wrap(err)
	}
	if atomic.CompareAndSwapUint32(&pq.done, 0, 1) {
		pq.addBuff <- struct{}{}
	}
	return nil
}

func (pq *PQueue) poll(ctx context.Context) (string, error) {
	if pq == nil || !pq.valid {
		return "", nil
	}
	n, err := pq.pqueue.PSize(ctx, pq.name)
	if err != nil {
		return "", errors.Wrap(err)
	}
	if n == 0 {
		select {
		case <-pq.closed:
			return "", nil
		case <-pq.addCh:
		}
	}
	select {
	case <-pq.addCh:
	default:
	}
	album, expires, err := pq.pqueue.PPoll(ctx, pq.name)
	if err != nil {
		return "", errors.Wrap(err)
	}
	t := time.NewTimer(time.Until(expires))
	defer t.Stop()
	for {
		select {
		case <-pq.closed:
			return "", nil
		case <-pq.addCh:
			newAlbum, newExpires, err := pq.pqueue.PPoll(ctx, pq.name)
			if err != nil {
				err = errors.Wrap(err)
				handleError(err)
				continue
			}
			if newExpires.After(expires) {
				err := pq.pqueue.PAdd(ctx, pq.name, newAlbum, newExpires)
				if err != nil {
					return "", errors.Wrap(err)
				}
				continue
			}
			err = pq.pqueue.PAdd(ctx, pq.name, album, expires)
			if err != nil {
				return "", errors.Wrap(err)
			}
			if !t.Stop() {
				<-t.C
			}
			t.Reset(time.Until(newExpires))
			album = newAlbum
			expires = newExpires
		case <-t.C:
			return album, nil
		}
	}
}
<commit_msg>Check edge cases<commit_after>package service

import (
	"context"
	"sync"
	"sync/atomic"
	"time"

	"github.com/zitryss/aye-and-nay/domain/model"
	"github.com/zitryss/aye-and-nay/pkg/errors"
)

func NewQueue(name string, q model.Queuer) *Queue {
	return &Queue{
		name:   name,
		queue:  q,
		cond:   sync.NewCond(&sync.Mutex{}),
		closed: false,
		valid:  true,
	}
}

type Queue struct {
	name   string
	queue  model.Queuer
	cond   *sync.Cond
	closed bool
	valid  bool
}

func (q *Queue) Monitor(ctx context.Context) {
	if q == nil || !q.valid {
		return
	}
	go func() {
		<-ctx.Done()
		q.cond.L.Lock()
		defer q.cond.L.Unlock()
		q.closed = true
		q.cond.Broadcast()
	}()
}

func (q *Queue) add(ctx context.Context, album string) error {
	if q == nil || !q.valid {
		return nil
	}
	err := q.queue.Add(ctx, q.name, album)
	if err != nil {
		return errors.Wrap(err)
	}
	q.cond.Signal()
	return nil
}

func (q *Queue) poll(ctx context.Context) (string, error) {
	if q == nil || !q.valid {
		return "", nil
	}
	q.cond.L.Lock()
	defer q.cond.L.Unlock()
	n, err := q.queue.Size(ctx, q.name)
	if err != nil {
		return "", errors.Wrap(err)
	}
	for n == 0 {
		q.cond.Wait()
		if q.closed {
			return "", nil
		}
		n, err = q.queue.Size(ctx, q.name)
		if err != nil {
			return "", errors.Wrap(err)
		}
	}
	album, err := q.queue.Poll(ctx, q.name)
	if err != nil {
		return "", errors.Wrap(err)
	}
	return album, nil
}

func NewPQueue(name string, pq model.PQueuer) *PQueue {
	return &PQueue{
		name:    name,
		pqueue:  pq,
		addCh:   make(chan struct{}),
		addBuff: make(chan struct{}, 1),
		done:    0,
		closed:  make(chan struct{}),
		valid:   true,
	}
}

type PQueue struct {
	name    string
	pqueue  model.PQueuer
	addCh   chan struct{}
	addBuff chan struct{}
	done    uint32
	closed  chan struct{}
	valid   bool
}

func (pq *PQueue) Monitor(ctx context.Context) {
	if pq == nil || !pq.valid {
		return
	}
	go func() {
		<-ctx.Done()
		pq.closed <- struct{}{}
	}()
	go func() {
		for {
			<-pq.addBuff
			pq.addCh <- struct{}{}
			atomic.StoreUint32(&pq.done, 0)
		}
	}()
}

func (pq *PQueue) add(ctx context.Context, album string, expires time.Time) error {
	if pq == nil || !pq.valid {
		return nil
	}
	err := pq.pqueue.PAdd(ctx, pq.name, album, expires)
	if err != nil {
		return errors.Wrap(err)
	}
	if atomic.CompareAndSwapUint32(&pq.done, 0, 1) {
		pq.addBuff <- struct{}{}
	}
	return nil
}

func (pq *PQueue) poll(ctx context.Context) (string, error) {
	if pq == nil || !pq.valid {
		return "", nil
	}
	n, err := pq.pqueue.PSize(ctx, pq.name)
	if err != nil {
		return "", errors.Wrap(err)
	}
	if n == 0 {
		select {
		case <-pq.closed:
			return "", nil
		case <-pq.addCh:
		}
	}
	select {
	case <-pq.addCh:
	default:
	}
	album, expires, err := pq.pqueue.PPoll(ctx, pq.name)
	if err != nil {
		return "", errors.Wrap(err)
	}
	t := time.NewTimer(time.Until(expires))
	defer t.Stop()
	for {
		select {
		case <-pq.closed:
			return "", nil
		case <-pq.addCh:
			newAlbum, newExpires, err := pq.pqueue.PPoll(ctx, pq.name)
			if errors.Is(err, model.ErrUnknown) {
				err = errors.Wrap(err)
				handleError(err)
				continue
			}
			if err != nil {
				return "", errors.Wrap(err)
			}
			if newExpires.After(expires) {
				err := pq.pqueue.PAdd(ctx, pq.name, newAlbum, newExpires)
				if err != nil {
					return "", errors.Wrap(err)
				}
				continue
			}
			err = pq.pqueue.PAdd(ctx, pq.name, album, expires)
			if err != nil {
				return "", errors.Wrap(err)
			}
			if !t.Stop() {
				<-t.C
			}
			t.Reset(time.Until(newExpires))
			album = newAlbum
			expires = newExpires
		case <-t.C:
			return album, nil
		}
	}
}
<|endoftext|>


<commit_before><commit_msg>option for databug to be dumped into GAE log storage.<commit_after><|endoftext|>


<commit_before>package main

import (
	"io"
	"time"
)

type NodeType int
type NodeMap [][]NodeType

const (
	T21Node NodeType = iota
	T30Node
	T31Node
)

type Tis100 struct {
	clock <-chan time.Time
	nodes [][]*T21
}

func NewTis100(nodes NodeMap) *Tis100 {
	// All rows need to be the same length
	l := len(nodes[0])
	for i := 1; i < len(nodes); i++ {
		if len(nodes[i]) != l {
			panic("all rows must be the same length")
		}
	}

	t := &Tis100{
		clock: time.Tick(time.Millisecond * 100),
	}

	for _, list := range nodes {
		var cnodes []*T21

		for _, node := range list {
			switch node {
			case T21Node:
				cnodes = append(cnodes, NewT21())
			default:
				panic("uknown node type")
			}
		}

		t.nodes = append(t.nodes, cnodes)
	}

	// Connect nodes
	for r, row := range t.nodes {
		for i := 0; i < len(row)-1; i++ {
			row[i].ConnectRight(row[i+1])
		}

		for i := 0; i < len(row); i++ {
			if r < len(t.nodes)-1 {
				row[i].ConnectDown(t.nodes[r+1][i])
			}
		}
	}

	return t
}

func (t *Tis100) Input(in chan int, node int) {
	row, col := t.nodeOffsets(node)
	t.nodes[row][col].up = in
}

func (t *Tis100) Output(node int) chan int {
	row, col := t.nodeOffsets(node)

	out := make(chan int)
	t.nodes[row][col].down = out
	return out
}

func (t *Tis100) Program(r io.Reader) {
	p := NewParser(r)

	curNode := 0
	programs := make(map[int][]Statement, 0)

	for {
		stmt, err := p.Parse()
		if err != nil {
			panic(err)
		}
		if stmt.Op == EOF {
			break
		} else if stmt.Op == NODE {
			curNode = int(stmt.Src)
		} else {
			programs[curNode] = append(programs[curNode], stmt)
		}
	}

	for idx, program := range programs {
		row, col := t.nodeOffsets(idx)
		t.nodes[row][col].Program(program)
	}
}

func (t *Tis100) Run() {
	for _, nodes := range t.nodes {
		for _, node := range nodes {
			node.Run()
		}
	}

	go func() {
		for {
			<-t.clock
			for _, nodes := range t.nodes {
				for _, node := range nodes {
					node.tick()
				}
			}
		}
	}()
}

func (t *Tis100) nodeOffsets(node int) (int, int) {
	row := node / len(t.nodes[0])
	col := node % len(t.nodes[0])
	return row, col
}
<commit_msg>speed up a little<commit_after>package main

import (
	"io"
	"time"
)

type NodeType int
type NodeMap [][]NodeType

const (
	T21Node NodeType = iota
	T30Node
	T31Node
)

type Tis100 struct {
	clock <-chan time.Time
	nodes [][]*T21 // TODO: Need to support other node types
}

func NewTis100(nodes NodeMap) *Tis100 {
	// All rows need to be the same length
	l := len(nodes[0])
	for i := 1; i < len(nodes); i++ {
		if len(nodes[i]) != l {
			panic("all rows must be the same length")
		}
	}

	t := &Tis100{
		clock: time.Tick(time.Millisecond * 10),
	}

	for _, list := range nodes {
		var cnodes []*T21

		for _, node := range list {
			switch node {
			case T21Node:
				cnodes = append(cnodes, NewT21())
			default:
				panic("uknown node type")
			}
		}

		t.nodes = append(t.nodes, cnodes)
	}

	// Connect nodes
	for r, row := range t.nodes {
		for i := 0; i < len(row)-1; i++ {
			row[i].ConnectRight(row[i+1])
		}

		for i := 0; i < len(row); i++ {
			if r < len(t.nodes)-1 {
				row[i].ConnectDown(t.nodes[r+1][i])
			}
		}
	}

	return t
}

func (t *Tis100) Input(in chan int, node int) {
	row, col := t.nodeOffsets(node)
	t.nodes[row][col].up = in
}

func (t *Tis100) Output(node int) chan int {
	row, col := t.nodeOffsets(node)

	out := make(chan int)
	t.nodes[row][col].down = out
	return out
}

func (t *Tis100) Program(r io.Reader) {
	p := NewParser(r)

	curNode := 0
	programs := make(map[int][]Statement, 0)

	for {
		stmt, err := p.Parse()
		if err != nil {
			panic(err)
		}
		if stmt.Op == EOF {
			break
		} else if stmt.Op == NODE {
			curNode = int(stmt.Src)
		} else {
			programs[curNode] = append(programs[curNode], stmt)
		}
	}

	for idx, program := range programs {
		row, col := t.nodeOffsets(idx)
		t.nodes[row][col].Program(program)
	}
}

func (t *Tis100) Run() {
	for _, nodes := range t.nodes {
		for _, node := range nodes {
			node.Run()
		}
	}

	go func() {
		for {
			<-t.clock
			for _, nodes := range t.nodes {
				for _, node := range nodes {
					node.tick()
				}
			}
		}
	}()
}

func (t *Tis100) nodeOffsets(node int) (int, int) {
	row := node / len(t.nodes[0])
	col := node % len(t.nodes[0])
	return row, col
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"log"
	"os"
	"text/tabwriter"

	"github.com/coreos-inc/updatectl/client/update/v1"
	"github.com/coreos-inc/updatectl/third_party/github.com/codegangsta/cli"
)

func ChannelCommands() []cli.Command {
	return []cli.Command{
		{
			Name:        "update-channel",
			Usage:       "update-channel <appId> <channel> <version>",
			Description: `Update a given channel given a group, app, channel and version.`,
			Action:      handle(updateChannel),
		},
	}
}

func updateChannel(c *cli.Context, service *update.Service, out *tabwriter.Writer) {
	args := c.Args()

	if len(args) != 3 {
		fmt.Println("usage: <appid> <channel> <version>")
		os.Exit(1)
	}

	channelReq := &update.ChannelRequest{Version: args[2]}

	call := service.Channel.Update(args[0], args[1], channelReq)
	channel, err := call.Do()
	if err != nil {
		log.Fatal(err)
	}

	fmt.Fprintf(out, "%s\n", channel.Version)
	out.Flush()
}
<commit_msg>feat(list-channels): List all channels for a given application.<commit_after>package main

import (
	"fmt"
	"log"
	"os"
	"text/tabwriter"

	"github.com/coreos-inc/updatectl/client/update/v1"
	"github.com/coreos-inc/updatectl/third_party/github.com/codegangsta/cli"
)

func ChannelCommands() []cli.Command {
	return []cli.Command{
		{
			Name:        "list-channels",
			Usage:       "list-channels <appId>",
			Description: `List all channels for an application.`,
			Action:      handle(listChannels),
		},
		{
			Name:        "update-channel",
			Usage:       "update-channel <appId> <channel> <version>",
			Description: `Update a given channel given a group, app, channel and version.`,
			Action:      handle(updateChannel),
		},
	}
}

func formatChannel(channel *update.AppChannel) string {
	return fmt.Sprintf("%s\t%s\n", channel.Label, channel.Version)
}

func listChannels(c *cli.Context, service *update.Service, out *tabwriter.Writer) {
	args := c.Args()

	if len(args) != 1 {
		cli.ShowCommandHelp(c, "list-channels")
		os.Exit(1)
	}

	listCall := service.Channel.List(args[0])
	list, err := listCall.Do()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Fprint(out, "Label\tVersion\n")
	for _, channel := range list.Items {
		fmt.Fprintf(out, "%s", formatChannel(channel))
	}
	out.Flush()
}

func updateChannel(c *cli.Context, service *update.Service, out *tabwriter.Writer) {
	args := c.Args()

	if len(args) != 3 {
		fmt.Println("usage: <appid> <channel> <version>")
		os.Exit(1)
	}

	channelReq := &update.ChannelRequest{Version: args[2]}

	call := service.Channel.Update(args[0], args[1], channelReq)
	channel, err := call.Do()
	if err != nil {
		log.Fatal(err)
	}

	fmt.Fprintf(out, "%s\n", channel.Version)
	out.Flush()
}
<|endoftext|>


<commit_before>package kuiperbelt

import (
	"bytes"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"golang.org/x/net/websocket"
)

func TestProxySendHandlerFunc__BulkSend(t *testing.T) {
	var pool SessionPool
	s1 := &TestSession{
		key:  "hogehoge",
		send: make(chan Message, 4),
	}
	s2 := &TestSession{
		key:  "fugafuga",
		send: make(chan Message, 4),
	}

	pool.Add(s1)
	pool.Add(s2)

	tc := TestConfig
	p := NewProxy(tc, NewStats(), &pool)
	ts := httptest.NewServer(http.HandlerFunc(p.SendHandlerFunc))
	defer ts.Close()

	req, err := http.NewRequest("POST", ts.URL, bytes.NewBufferString("test message"))
	if err != nil {
		t.Fatal("proxy handler new request unexpected error:", err)
	}
	req.Header.Add(tc.SessionHeader, "hogehoge")
	req.Header.Add(tc.SessionHeader, "fugafuga")

	client := new(http.Client)
	resp, err := client.Do(req)
	if err != nil {
		t.Fatal("proxy handler request unexpected error:", err)
	}
	defer resp.Body.Close()

	dec := json.NewDecoder(resp.Body)
	result := struct {
		Result string `json:"result"`
	}{}
	err = dec.Decode(&result)
	if err != nil {
		t.Fatal("proxy handler response unexpected error:", err)
	}
	if result.Result != "OK" {
		t.Fatalf("proxy handler response unexpected response: %+v", result)
	}

	msg1 := <-s1.send
	if string(msg1.Body) != "test message" {
		t.Errorf("proxy handler s1 not receive message: %s", string(msg1.Body))
	}
	if msg1.LastWord {
		t.Error("s1 receives last word")
	}
	msg2 := <-s2.send
	if string(msg2.Body) != "test message" {
		t.Errorf("proxy handler s2 not receive message: %s", string(msg2.Body))
	}
	if msg2.LastWord {
		t.Error("s2 receives last word")
	}
}

func TestProxySendHandlerFunc__SendInBinary(t *testing.T) {
	var pool SessionPool
	callbackServer := new(testSuccessConnectCallbackServer)
	tcc := httptest.NewServer(http.HandlerFunc(callbackServer.SuccessHandler))

	tc := TestConfig
	tc.Callback.Connect = tcc.URL
	st := NewStats()
	p := NewProxy(tc, st, &pool)
	ts := httptest.NewServer(http.HandlerFunc(p.SendHandlerFunc))
	server := NewWebSocketServer(tc, st, &pool)
	th := httptest.NewServer(http.HandlerFunc(server.Handler))

	wsURL := strings.Replace(th.URL, "http://", "ws://", -1)
	wsConfig, err := websocket.NewConfig(wsURL, "http://localhost/")
	if err != nil {
		t.Fatal("cannot create connection config error:", err)
	}
	wsConfig.Header.Add(testRequestSessionHeader, "hogehoge")
	conn, err := websocket.DialConfig(wsConfig)
	if err != nil {
		t.Fatal("cannot connect error:", err)
	}

	// ignore hello message
	var hello string
	websocket.Message.Receive(conn, &hello)

	codec := &websocket.Codec{
		Unmarshal: func(data []byte, payloadType byte, v interface{}) error {
			rb, _ := v.(*byte)
			*rb = payloadType
			return nil
		},
		Marshal: nil,
	}

	req, err := http.NewRequest("POST", ts.URL, bytes.NewBuffer([]byte("hogehoge")))
	if err != nil {
		t.Fatal("creadrequest unexpected error:", err)
	}
	req.Header.Add("Content-Type", "APPLICATION/octet-stream ;param=foobar")
	req.Header.Add(tc.SessionHeader, "hogehoge")
	_, err = http.DefaultClient.Do(req)
	if err != nil {
		t.Fatal("send request unexpected error:", err)
	}

	var rb byte
	codec.Receive(conn, &rb)
	if rb != websocket.BinaryFrame {
		t.Fatal("receved message is not binary frame:", rb)
	}
}

func TestProxyCloseHandlerFunc__BulkClose(t *testing.T) {
	var pool SessionPool
	s1 := &TestSession{
		key:  "hogehoge",
		send: make(chan Message, 4),
	}
	s2 := &TestSession{
		key:  "fugafuga",
		send: make(chan Message, 4),
	}

	pool.Add(s1)
	pool.Add(s2)

	tc := TestConfig
	p := NewProxy(tc, NewStats(), &pool)
	ts := httptest.NewServer(http.HandlerFunc(p.CloseHandlerFunc))
	defer ts.Close()

	req, err := http.NewRequest("POST", ts.URL, bytes.NewBufferString("test message"))
	if err != nil {
		t.Fatal("proxy handler new request unexpected error:", err)
	}
	req.Header.Add(tc.SessionHeader, "hogehoge")
	req.Header.Add(tc.SessionHeader, "fugafuga")

	client := new(http.Client)
	resp, err := client.Do(req)
	if err != nil {
		t.Fatal("proxy handler request unexpected error:", err)
	}
	defer resp.Body.Close()

	dec := json.NewDecoder(resp.Body)
	result := struct {
		Result string `json:"result"`
	}{}
	err = dec.Decode(&result)
	if err != nil {
		t.Fatal("proxy handler response unexpected error:", err)
	}
	if result.Result != "OK" {
		t.Fatalf("proxy handler response unexpected response: %+v", result)
	}

	msg1 := <-s1.send
	if string(msg1.Body) != "test message" {
		t.Errorf("proxy handler s1 not receive message: %s", string(msg1.Body))
	}
	if !msg1.LastWord {
		t.Error("s1 does not receive last word")
	}
	msg2 := <-s2.send
	if string(msg2.Body) != "test message" {
		t.Errorf("proxy handler s2 not receive message: %s", string(msg2.Body))
	}
	if !msg2.LastWord {
		t.Error("s2 does not receive last word")
	}
}

func TestProxySendHandlerFunc__StrictBroadcastFalse(t *testing.T) {
	var pool SessionPool
	s1 := &TestSession{
		key:  "hogehoge",
		send: make(chan Message, 4),
	}
	pool.Add(s1)

	tc := TestConfig // StrictBroadcast == false (default)
	p := NewProxy(tc, NewStats(), &pool)
	ts := httptest.NewServer(http.HandlerFunc(p.SendHandlerFunc))
	defer ts.Close()

	req, err := http.NewRequest("POST", ts.URL, bytes.NewBufferString("test message"))
	if err != nil {
		t.Fatal("proxy handler new request unexpected error:", err)
	}
	req.Header.Add(tc.SessionHeader, "hogehog") // missing "e" invalid session
	client := new(http.Client)
	resp, err := client.Do(req)
	if err != nil {
		t.Fatal("proxy handler request unexpected error:", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		// StrictBroadcast == false returns always OK
		t.Fatal("proxy handler response unexpected status:", resp.StatusCode)
	}
	dec := json.NewDecoder(resp.Body)
	result := struct {
		Result string        `json:"result"`
		Errors []interface{} `json:"errors,omitempty"`
	}{}
	err = dec.Decode(&result)
	if err != nil {
		t.Fatal("proxy handler response unexpected error:", err)
	}
	if result.Result != "OK" {
		t.Fatalf("proxy handler response unexpected response: %+v", result)
	}
	if len(result.Errors) != 1 {
		t.Fatalf("proxy handler response unexpected response: %+v", result)
	}
	/* fix me!!
	if s1.String() == "test message" {
		t.Fatalf("proxy handler s1 must not receive message: %s", s1.String())
	}
	*/
}

func TestProxySendHandlerFunc__StrictBroadcastTrue1(t *testing.T) {
	var pool SessionPool
	s1 := &TestSession{
		key:  "hogehoge",
		send: make(chan Message, 4),
	}
	pool.Add(s1)

	tc := TestConfig
	tc.StrictBroadcast = true
	p := NewProxy(tc, NewStats(), &pool)
	ts := httptest.NewServer(http.HandlerFunc(p.SendHandlerFunc))
	defer ts.Close()

	req, err := http.NewRequest("POST", ts.URL, bytes.NewBufferString("test message"))
	if err != nil {
		t.Fatal("proxy handler new request unexpected error:", err)
	}
	req.Header.Add(tc.SessionHeader, "hogehog") // missing "e" invalid session
	client := new(http.Client)
	resp, err := client.Do(req)
	if err != nil {
		t.Fatal("proxy handler request unexpected error:", err)
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusBadRequest {
		// StrictBroadcast == true returns Bad Request if requested sessions missing
		t.Fatal("proxy handler response unexpected status:", resp.StatusCode)
	}

	dec := json.NewDecoder(resp.Body)
	result := struct {
		Result string        `json:"result"`
		Errors []interface{} `json:"errors,omitempty"`
	}{}
	err = dec.Decode(&result)
	if err != nil {
		t.Fatal("proxy handler response unexpected error:", err)
	}
	if result.Result != "NG" {
		t.Fatalf("proxy handler response unexpected response: %+v", result)
	}
	if len(result.Errors) != 1 {
		t.Fatalf("proxy handler response unexpected response: %+v", result)
	}
	select {
	case msg := <-s1.send:
		t.Fatalf("proxy handler s1 must not receive message: %#v", msg)
	default:
	}
}

func TestProxySendHandlerFunc__StrictBroadcastTrue2(t *testing.T) {
	var pool SessionPool
	s1 := &TestSession{
		key:  "hogehoge",
		send: make(chan Message, 4),
	}
	s2 := &TestSession{
		key:  "fugafuga",
		send: make(chan Message, 4),
	}
	pool.Add(s1)
	pool.Add(s2)

	tc := TestConfig
	tc.StrictBroadcast = true
	p := NewProxy(tc, NewStats(), &pool)
	ts := httptest.NewServer(http.HandlerFunc(p.SendHandlerFunc))
	defer ts.Close()

	req, err := http.NewRequest("POST", ts.URL, bytes.NewBufferString("test message"))
	if err != nil {
		t.Fatal("proxy handler new request unexpected error:", err)
	}
	req.Header.Add(tc.SessionHeader, "hogehog") // missing "e" invalid session
	req.Header.Add(tc.SessionHeader, "fugafuga")
	client := new(http.Client)
	resp, err := client.Do(req)
	if err != nil {
		t.Fatal("proxy handler request unexpected error:", err)
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusBadRequest {
		// StrictBroadcast == true returns Bad Request if requested sessions missing
		t.Fatal("proxy handler response unexpected status:", resp.StatusCode)
	}

	dec := json.NewDecoder(resp.Body)
	result := struct {
		Result string        `json:"result"`
		Errors []interface{} `json:"errors,omitempty"`
	}{}
	err = dec.Decode(&result)
	if err != nil {
		t.Fatal("proxy handler response unexpected error:", err)
	}
	if result.Result != "NG" {
		t.Fatalf("proxy handler response unexpected response: %+v", result)
	}
	if len(result.Errors) != 1 {
		t.Fatalf("proxy handler response unexpected response: %+v", result)
	}
	/* TODO: fix me!
	if s1.String() == "test message" {
		t.Fatalf("proxy handler s1 must not receive message: %s", s1.String())
	}
	if s2.String() == "test message" {
		t.Fatalf("proxy handler s2 must not receive message: %s", s1.String())
	}
	*/
}

func TestProxyPingHandlerFunc(t *testing.T) {
	var pool SessionPool
	tc := TestConfig
	p := NewProxy(tc, NewStats(), &pool)
	ts := httptest.NewServer(http.HandlerFunc(p.PingHandlerFunc))
	defer ts.Close()

	req, err := http.NewRequest("GET", ts.URL, nil)
	if err != nil {
		t.Fatal("proxy handler new request unexpected error:", err)
	}
	client := new(http.Client)
	resp, err := client.Do(req)
	if err != nil {
		t.Fatal("proxy handler request unexpected error:", err)
	}
	defer resp.Body.Close()

	dec := json.NewDecoder(resp.Body)
	result := struct {
		Result string `json:"result"`
	}{}
	err = dec.Decode(&result)
	if err != nil {
		t.Fatal("proxy handler response unexpected error:", err)
	}
	if result.Result != "OK" {
		t.Fatalf("proxy handler response unexpected response: %+v", result)
	}
}
<commit_msg>fix TestProxySendHandlerFunc__StrictBroadcastTrue2<commit_after>package kuiperbelt

import (
	"bytes"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"golang.org/x/net/websocket"
)

func TestProxySendHandlerFunc__BulkSend(t *testing.T) {
	var pool SessionPool
	s1 := &TestSession{
		key:  "hogehoge",
		send: make(chan Message, 4),
	}
	s2 := &TestSession{
		key:  "fugafuga",
		send: make(chan Message, 4),
	}

	pool.Add(s1)
	pool.Add(s2)

	tc := TestConfig
	p := NewProxy(tc, NewStats(), &pool)
	ts := httptest.NewServer(http.HandlerFunc(p.SendHandlerFunc))
	defer ts.Close()

	req, err := http.NewRequest("POST", ts.URL, bytes.NewBufferString("test message"))
	if err != nil {
		t.Fatal("proxy handler new request unexpected error:", err)
	}
	req.Header.Add(tc.SessionHeader, "hogehoge")
	req.Header.Add(tc.SessionHeader, "fugafuga")

	client := new(http.Client)
	resp, err := client.Do(req)
	if err != nil {
		t.Fatal("proxy handler request unexpected error:", err)
	}
	defer resp.Body.Close()

	dec := json.NewDecoder(resp.Body)
	result := struct {
		Result string `json:"result"`
	}{}
	err = dec.Decode(&result)
	if err != nil {
		t.Fatal("proxy handler response unexpected error:", err)
	}
	if result.Result != "OK" {
		t.Fatalf("proxy handler response unexpected response: %+v", result)
	}

	msg1 := <-s1.send
	if string(msg1.Body) != "test message" {
		t.Errorf("proxy handler s1 not receive message: %s", string(msg1.Body))
	}
	if msg1.LastWord {
		t.Error("s1 receives last word")
	}
	msg2 := <-s2.send
	if string(msg2.Body) != "test message" {
		t.Errorf("proxy handler s2 not receive message: %s", string(msg2.Body))
	}
	if msg2.LastWord {
		t.Error("s2 receives last word")
	}
}

func TestProxySendHandlerFunc__SendInBinary(t *testing.T) {
	var pool SessionPool
	callbackServer := new(testSuccessConnectCallbackServer)
	tcc := httptest.NewServer(http.HandlerFunc(callbackServer.SuccessHandler))

	tc := TestConfig
	tc.Callback.Connect = tcc.URL
	st := NewStats()
	p := NewProxy(tc, st, &pool)
	ts := httptest.NewServer(http.HandlerFunc(p.SendHandlerFunc))
	server := NewWebSocketServer(tc, st, &pool)
	th := httptest.NewServer(http.HandlerFunc(server.Handler))

	wsURL := strings.Replace(th.URL, "http://", "ws://", -1)
	wsConfig, err := websocket.NewConfig(wsURL, "http://localhost/")
	if err != nil {
		t.Fatal("cannot create connection config error:", err)
	}
	wsConfig.Header.Add(testRequestSessionHeader, "hogehoge")
	conn, err := websocket.DialConfig(wsConfig)
	if err != nil {
		t.Fatal("cannot connect error:", err)
	}

	// ignore hello message
	var hello string
	websocket.Message.Receive(conn, &hello)

	codec := &websocket.Codec{
		Unmarshal: func(data []byte, payloadType byte, v interface{}) error {
			rb, _ := v.(*byte)
			*rb = payloadType
			return nil
		},
		Marshal: nil,
	}

	req, err := http.NewRequest("POST", ts.URL, bytes.NewBuffer([]byte("hogehoge")))
	if err != nil {
		t.Fatal("creadrequest unexpected error:", err)
	}
	req.Header.Add("Content-Type", "APPLICATION/octet-stream ;param=foobar")
	req.Header.Add(tc.SessionHeader, "hogehoge")
	_, err = http.DefaultClient.Do(req)
	if err != nil {
		t.Fatal("send request unexpected error:", err)
	}

	var rb byte
	codec.Receive(conn, &rb)
	if rb != websocket.BinaryFrame {
		t.Fatal("receved message is not binary frame:", rb)
	}
}

func TestProxyCloseHandlerFunc__BulkClose(t *testing.T) {
	var pool SessionPool
	s1 := &TestSession{
		key:  "hogehoge",
		send: make(chan Message, 4),
	}
	s2 := &TestSession{
		key:  "fugafuga",
		send: make(chan Message, 4),
	}

	pool.Add(s1)
	pool.Add(s2)

	tc := TestConfig
	p := NewProxy(tc, NewStats(), &pool)
	ts := httptest.NewServer(http.HandlerFunc(p.CloseHandlerFunc))
	defer ts.Close()

	req, err := http.NewRequest("POST", ts.URL, bytes.NewBufferString("test message"))
	if err != nil {
		t.Fatal("proxy handler new request unexpected error:", err)
	}
	req.Header.Add(tc.SessionHeader, "hogehoge")
	req.Header.Add(tc.SessionHeader, "fugafuga")

	client := new(http.Client)
	resp, err := client.Do(req)
	if err != nil {
		t.Fatal("proxy handler request unexpected error:", err)
	}
	defer resp.Body.Close()

	dec := json.NewDecoder(resp.Body)
	result := struct {
		Result string `json:"result"`
	}{}
	err = dec.Decode(&result)
	if err != nil {
		t.Fatal("proxy handler response unexpected error:", err)
	}
	if result.Result != "OK" {
		t.Fatalf("proxy handler response unexpected response: %+v", result)
	}

	msg1 := <-s1.send
	if string(msg1.Body) != "test message" {
		t.Errorf("proxy handler s1 not receive message: %s", string(msg1.Body))
	}
	if !msg1.LastWord {
		t.Error("s1 does not receive last word")
	}
	msg2 := <-s2.send
	if string(msg2.Body) != "test message" {
		t.Errorf("proxy handler s2 not receive message: %s", string(msg2.Body))
	}
	if !msg2.LastWord {
		t.Error("s2 does not receive last word")
	}
}

func TestProxySendHandlerFunc__StrictBroadcastFalse(t *testing.T) {
	var pool SessionPool
	s1 := &TestSession{
		key:  "hogehoge",
		send: make(chan Message, 4),
	}
	pool.Add(s1)

	tc := TestConfig // StrictBroadcast == false (default)
	p := NewProxy(tc, NewStats(), &pool)
	ts := httptest.NewServer(http.HandlerFunc(p.SendHandlerFunc))
	defer ts.Close()

	req, err := http.NewRequest("POST", ts.URL, bytes.NewBufferString("test message"))
	if err != nil {
		t.Fatal("proxy handler new request unexpected error:", err)
	}
	req.Header.Add(tc.SessionHeader, "hogehog") // missing "e" invalid session
	client := new(http.Client)
	resp, err := client.Do(req)
	if err != nil {
		t.Fatal("proxy handler request unexpected error:", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		// StrictBroadcast == false returns always OK
		t.Fatal("proxy handler response unexpected status:", resp.StatusCode)
	}
	dec := json.NewDecoder(resp.Body)
	result := struct {
		Result string        `json:"result"`
		Errors []interface{} `json:"errors,omitempty"`
	}{}
	err = dec.Decode(&result)
	if err != nil {
		t.Fatal("proxy handler response unexpected error:", err)
	}
	if result.Result != "OK" {
		t.Fatalf("proxy handler response unexpected response: %+v", result)
	}
	if len(result.Errors) != 1 {
		t.Fatalf("proxy handler response unexpected response: %+v", result)
	}
	/* fix me!!
	if s1.String() == "test message" {
		t.Fatalf("proxy handler s1 must not receive message: %s", s1.String())
	}
	*/
}

func TestProxySendHandlerFunc__StrictBroadcastTrue1(t *testing.T) {
	var pool SessionPool
	s1 := &TestSession{
		key:  "hogehoge",
		send: make(chan Message, 4),
	}
	pool.Add(s1)

	tc := TestConfig
	tc.StrictBroadcast = true
	p := NewProxy(tc, NewStats(), &pool)
	ts := httptest.NewServer(http.HandlerFunc(p.SendHandlerFunc))
	defer ts.Close()

	req, err := http.NewRequest("POST", ts.URL, bytes.NewBufferString("test message"))
	if err != nil {
		t.Fatal("proxy handler new request unexpected error:", err)
	}
	req.Header.Add(tc.SessionHeader, "hogehog") // missing "e" invalid session
	client := new(http.Client)
	resp, err := client.Do(req)
	if err != nil {
		t.Fatal("proxy handler request unexpected error:", err)
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusBadRequest {
		// StrictBroadcast == true returns Bad Request if requested sessions missing
		t.Fatal("proxy handler response unexpected status:", resp.StatusCode)
	}

	dec := json.NewDecoder(resp.Body)
	result := struct {
		Result string        `json:"result"`
		Errors []interface{} `json:"errors,omitempty"`
	}{}
	err = dec.Decode(&result)
	if err != nil {
		t.Fatal("proxy handler response unexpected error:", err)
	}
	if result.Result != "NG" {
		t.Fatalf("proxy handler response unexpected response: %+v", result)
	}
	if len(result.Errors) != 1 {
		t.Fatalf("proxy handler response unexpected response: %+v", result)
	}
	select {
	case msg := <-s1.send:
		t.Fatalf("proxy handler s1 must not receive message: %#v", msg)
	default:
	}
}

func TestProxySendHandlerFunc__StrictBroadcastTrue2(t *testing.T) {
	var pool SessionPool
	s1 := &TestSession{
		key:  "hogehoge",
		send: make(chan Message, 4),
	}
	s2 := &TestSession{
		key:  "fugafuga",
		send: make(chan Message, 4),
	}
	pool.Add(s1)
	pool.Add(s2)

	tc := TestConfig
	tc.StrictBroadcast = true
	p := NewProxy(tc, NewStats(), &pool)
	ts := httptest.NewServer(http.HandlerFunc(p.SendHandlerFunc))
	defer ts.Close()

	req, err := http.NewRequest("POST", ts.URL, bytes.NewBufferString("test message"))
	if err != nil {
		t.Fatal("proxy handler new request unexpected error:", err)
	}
	req.Header.Add(tc.SessionHeader, "hogehog") // missing "e" invalid session
	req.Header.Add(tc.SessionHeader, "fugafuga")
	client := new(http.Client)
	resp, err := client.Do(req)
	if err != nil {
		t.Fatal("proxy handler request unexpected error:", err)
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusBadRequest {
		// StrictBroadcast == true returns Bad Request if requested sessions missing
		t.Fatal("proxy handler response unexpected status:", resp.StatusCode)
	}

	dec := json.NewDecoder(resp.Body)
	result := struct {
		Result string        `json:"result"`
		Errors []interface{} `json:"errors,omitempty"`
	}{}
	err = dec.Decode(&result)
	if err != nil {
		t.Fatal("proxy handler response unexpected error:", err)
	}
	if result.Result != "NG" {
		t.Fatalf("proxy handler response unexpected response: %+v", result)
	}
	if len(result.Errors) != 1 {
		t.Fatalf("proxy handler response unexpected response: %+v", result)
	}
	select {
	case msg := <-s1.send:
		t.Fatalf("proxy handler s1 must not receive message: %#v", msg)
	default:
	}
	select {
	case msg := <-s2.send:
		t.Fatalf("proxy handler s2 must not receive message: %#v", msg)
	default:
	}
}

func TestProxyPingHandlerFunc(t *testing.T) {
	var pool SessionPool
	tc := TestConfig
	p := NewProxy(tc, NewStats(), &pool)
	ts := httptest.NewServer(http.HandlerFunc(p.PingHandlerFunc))
	defer ts.Close()

	req, err := http.NewRequest("GET", ts.URL, nil)
	if err != nil {
		t.Fatal("proxy handler new request unexpected error:", err)
	}
	client := new(http.Client)
	resp, err := client.Do(req)
	if err != nil {
		t.Fatal("proxy handler request unexpected error:", err)
	}
	defer resp.Body.Close()

	dec := json.NewDecoder(resp.Body)
	result := struct {
		Result string `json:"result"`
	}{}
	err = dec.Decode(&result)
	if err != nil {
		t.Fatal("proxy handler response unexpected error:", err)
	}
	if result.Result != "OK" {
		t.Fatalf("proxy handler response unexpected response: %+v", result)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"encoding/hex"
	"io/ioutil"
	"net"
	"testing"

	"gopkg.in/tomb.v1"
)

func NewTestProxy(name, upstream string) *Proxy {
	proxy := NewProxy()

	proxy.Name = name
	proxy.Listen = "localhost:20000"
	proxy.Upstream = upstream

	return proxy
}

func WithTCPServer(t *testing.T, f func(string, chan []byte)) {
	ln, err := net.Listen("tcp", "localhost:20002")
	if err != nil {
		t.Fatal("Failed to create TCP server", err)
	}

	defer ln.Close()

	response := make(chan []byte, 1)
	tomb := tomb.Tomb{}

	go func() {
		defer tomb.Done()
		src, err := ln.Accept()
		if err != nil {
			select {
			case <-tomb.Dying():
			default:
				t.Fatal("Failed to accept client")
			}
			return
		}

		ln.Close()

		val, err := ioutil.ReadAll(src)
		if err != nil {
			t.Fatal("Failed to read from client")
		}

		response <- val
	}()

	f(ln.Addr().String(), response)

	tomb.Killf("Function body finished")
	ln.Close()
	tomb.Wait()

	close(response)
}

func TestSimpleServer(t *testing.T) {
	WithTCPServer(t, func(addr string, response chan []byte) {
		conn, err := net.Dial("tcp", addr)
		if err != nil {
			t.Error("Unable to dial TCP server", err)
		}

		msg := []byte("hello world")

		_, err = conn.Write(msg)
		if err != nil {
			t.Error("Failed writing to TCP server", err)
		}

		err = conn.Close()
		if err != nil {
			t.Error("Failed to close TCP connection", err)
		}

		resp := <-response
		if !bytes.Equal(resp, msg) {
			t.Error("Server didn't read bytes from client")
		}
	})
}

func WithTCPProxy(t *testing.T, f func(proxy net.Conn, response chan []byte, proxyServer *Proxy)) {
	WithTCPServer(t, func(upstream string, response chan []byte) {
		proxy := NewTestProxy("test", upstream)
		proxy.Start()

		conn, err := net.Dial("tcp", "localhost:20000")
		if err != nil {
			t.Error("Unable to dial TCP server", err)
		}

		f(conn, response, proxy)

		proxy.Stop()
	})
}

func TestProxySimpleMessage(t *testing.T) {
	WithTCPProxy(t, func(conn net.Conn, response chan []byte, proxy *Proxy) {
		msg := []byte("hello world")

		_, err := conn.Write(msg)
		if err != nil {
			t.Error("Failed writing to TCP server", err)
		}

		err = conn.Close()
		if err != nil {
			t.Error("Failed to close TCP connection", err)
		}

		resp := <-response
		if !bytes.Equal(resp, msg) {
			t.Error("Server didn't read correct bytes from client", resp)
		}
	})
}

func TestProxyBigMessage(t *testing.T) {
	WithTCPProxy(t, func(conn net.Conn, response chan []byte, proxy *Proxy) {
		buf := make([]byte, 32*1024)
		msg := make([]byte, len(buf)*2)
		hex.Encode(msg, buf)

		_, err := conn.Write(msg)
		if err != nil {
			t.Error("Failed writing to TCP server", err)
		}

		err = conn.Close()
		if err != nil {
			t.Error("Failed to close TCP connection", err)
		}

		resp := <-response
		if !bytes.Equal(resp, msg) {
			t.Error("Server didn't read correct bytes from client", resp)
		}
	})
}

func TestProxyTwoPartMessage(t *testing.T) {
	WithTCPProxy(t, func(conn net.Conn, response chan []byte, proxy *Proxy) {
		msg1 := []byte("hello world")
		msg2 := []byte("hello world")

		_, err := conn.Write(msg1)
		if err != nil {
			t.Error("Failed writing to TCP server", err)
		}

		_, err = conn.Write(msg2)
		if err != nil {
			t.Error("Failed writing to TCP server", err)
		}

		err = conn.Close()
		if err != nil {
			t.Error("Failed to close TCP connection", err)
		}

		msg1 = append(msg1, msg2...)

		resp := <-response
		if !bytes.Equal(resp, msg1) {
			t.Error("Server didn't read correct bytes from client", resp)
		}
	})
}

func TestClosingProxyMultipleTimes(t *testing.T) {
	WithTCPProxy(t, func(conn net.Conn, response chan []byte, proxy *Proxy) {
		proxy.Stop()
		proxy.Stop()
		proxy.Stop()
	})
}

func TestStartTwoProxiesOnSameAddress(t *testing.T) {
	WithTCPProxy(t, func(conn net.Conn, response chan []byte, proxy *Proxy) {
		proxy2 := NewTestProxy("proxy_2", "localhost:3306")
		if err := proxy2.Start(); err == nil {
			t.Fatal("Expected an err back from start")
		}
	})
}
<commit_msg>Add test<commit_after>package main

import (
	"bytes"
	"encoding/hex"
	"io"
	"io/ioutil"
	"net"
	"testing"
	"time"

	"gopkg.in/tomb.v1"
)

func NewTestProxy(name, upstream string) *Proxy {
	proxy := NewProxy()

	proxy.Name = name
	proxy.Listen = "localhost:20000"
	proxy.Upstream = upstream

	return proxy
}

func WithTCPServer(t *testing.T, f func(string, chan []byte)) {
	ln, err := net.Listen("tcp", "localhost:20002")
	if err != nil {
		t.Fatal("Failed to create TCP server", err)
	}

	defer ln.Close()

	response := make(chan []byte, 1)
	tomb := tomb.Tomb{}

	go func() {
		defer tomb.Done()
		src, err := ln.Accept()
		if err != nil {
			select {
			case <-tomb.Dying():
			default:
				t.Fatal("Failed to accept client")
			}
			return
		}

		ln.Close()

		val, err := ioutil.ReadAll(src)
		if err != nil {
			t.Fatal("Failed to read from client")
		}

		response <- val
	}()

	f(ln.Addr().String(), response)

	tomb.Killf("Function body finished")
	ln.Close()
	tomb.Wait()

	close(response)
}

func TestSimpleServer(t *testing.T) {
	WithTCPServer(t, func(addr string, response chan []byte) {
		conn, err := net.Dial("tcp", addr)
		if err != nil {
			t.Error("Unable to dial TCP server", err)
		}

		msg := []byte("hello world")

		_, err = conn.Write(msg)
		if err != nil {
			t.Error("Failed writing to TCP server", err)
		}

		err = conn.Close()
		if err != nil {
			t.Error("Failed to close TCP connection", err)
		}

		resp := <-response
		if !bytes.Equal(resp, msg) {
			t.Error("Server didn't read bytes from client")
		}
	})
}

func WithTCPProxy(t *testing.T, f func(proxy net.Conn, response chan []byte, proxyServer *Proxy)) {
	WithTCPServer(t, func(upstream string, response chan []byte) {
		proxy := NewTestProxy("test", upstream)
		proxy.Start()

		conn, err := net.Dial("tcp", "localhost:20000")
		if err != nil {
			t.Error("Unable to dial TCP server", err)
		}

		f(conn, response, proxy)

		proxy.Stop()
	})
}

func TestProxySimpleMessage(t *testing.T) {
	WithTCPProxy(t, func(conn net.Conn, response chan []byte, proxy *Proxy) {
		msg := []byte("hello world")

		_, err := conn.Write(msg)
		if err != nil {
			t.Error("Failed writing to TCP server", err)
		}

		err = conn.Close()
		if err != nil {
			t.Error("Failed to close TCP connection", err)
		}

		resp := <-response
		if !bytes.Equal(resp, msg) {
			t.Error("Server didn't read correct bytes from client", resp)
		}
	})
}

func TestProxyToDownUpstream(t *testing.T) {
	proxy := NewTestProxy("test", "localhost:20009")
	proxy.Start()

	conn, err := net.Dial("tcp", "localhost:20000")
	if err != nil {
		t.Error("Unable to dial TCP server", err)
	}

	// Check to make sure the connection is closed
	conn.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
	_, err = conn.Read(make([]byte, 1))
	if err != io.EOF {
		t.Error("Proxy did not close connection when upstream down", err)
	}

	proxy.Stop()
}

func TestProxyBigMessage(t *testing.T) {
	WithTCPProxy(t, func(conn net.Conn, response chan []byte, proxy *Proxy) {
		buf := make([]byte, 32*1024)
		msg := make([]byte, len(buf)*2)
		hex.Encode(msg, buf)

		_, err := conn.Write(msg)
		if err != nil {
			t.Error("Failed writing to TCP server", err)
		}

		err = conn.Close()
		if err != nil {
			t.Error("Failed to close TCP connection", err)
		}

		resp := <-response
		if !bytes.Equal(resp, msg) {
			t.Error("Server didn't read correct bytes from client", resp)
		}
	})
}

func TestProxyTwoPartMessage(t *testing.T) {
	WithTCPProxy(t, func(conn net.Conn, response chan []byte, proxy *Proxy) {
		msg1 := []byte("hello world")
		msg2 := []byte("hello world")

		_, err := conn.Write(msg1)
		if err != nil {
			t.Error("Failed writing to TCP server", err)
		}

		_, err = conn.Write(msg2)
		if err != nil {
			t.Error("Failed writing to TCP server", err)
		}

		err = conn.Close()
		if err != nil {
			t.Error("Failed to close TCP connection", err)
		}

		msg1 = append(msg1, msg2...)

		resp := <-response
		if !bytes.Equal(resp, msg1) {
			t.Error("Server didn't read correct bytes from client", resp)
		}
	})
}

func TestClosingProxyMultipleTimes(t *testing.T) {
	WithTCPProxy(t, func(conn net.Conn, response chan []byte, proxy *Proxy) {
		proxy.Stop()
		proxy.Stop()
		proxy.Stop()
	})
}

func TestStartTwoProxiesOnSameAddress(t *testing.T) {
	WithTCPProxy(t, func(conn net.Conn, response chan []byte, proxy *Proxy) {
		proxy2 := NewTestProxy("proxy_2", "localhost:3306")
		if err := proxy2.Start(); err == nil {
			t.Fatal("Expected an err back from start")
		}
	})
}
<|endoftext|>


<commit_before>package tablestorageproxy

import (
	"bytes"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httputil"
	"strings"
	"time"
)

type GoHaveStorage interface {
	GetKey() []byte
	GetAccount() string
}

type TableStorageProxy struct {
	goHaveStorage GoHaveStorage
	baseUrl string
}

func New(goHaveStorage GoHaveStorage) *TableStorageProxy {
	var tableStorageProxy TableStorageProxy

	tableStorageProxy.goHaveStorage = goHaveStorage
	tableStorageProxy.baseUrl = "https://"+goHaveStorage.GetAccount()+".table.core.windows.net/"

	return &tableStorageProxy
}

func (tableStorageProxy *TableStorageProxy) QueryTables() {
	tableStorageProxy.get("Tables", "")
}

func (tableStorageProxy *TableStorageProxy) QueryEntity(tableName string, partitionKey string, rowKey string, selects string) {
	tableStorageProxy.get(tableName + "%28PartitionKey=%27" + partitionKey + "%27,RowKey=%27" + rowKey + "%27%29", "?$select="+selects)
}

func (tableStorageProxy *TableStorageProxy) QueryEntities(tableName string, selects string, filter string, top string) {
	tableStorageProxy.get(tableName, "?$filter="+filter + "&$select=" + selects+"&$top="+top)
}

func (tableStorageProxy *TableStorageProxy) DeleteEntity(tableName string, partitionKey string, rowKey string) {
	tableStorageProxy.executeEntityRequest("DELETE",tableName, partitionKey, rowKey, nil, true)
}

func (tableStorageProxy *TableStorageProxy) UpdateEntity(tableName string, partitionKey string, rowKey string, json []byte) {
	tableStorageProxy.executeEntityRequest("PUT",tableName, partitionKey, rowKey, json, true)
}

func (tableStorageProxy *TableStorageProxy) MergeEntity(tableName string, partitionKey string, rowKey string, json []byte) {
	tableStorageProxy.executeEntityRequest("MERGE",tableName, partitionKey, rowKey, json, true)
}

func (tableStorageProxy *TableStorageProxy) InsertOrMergeEntity(tableName string, partitionKey string, rowKey string, json []byte) {
	tableStorageProxy.executeEntityRequest("MERGE",tableName, partitionKey, rowKey, json, false)
}

func (tableStorageProxy *TableStorageProxy) InsertOrReplaceEntity(tableName string, partitionKey string, rowKey string, json []byte) {
	tableStorageProxy.executeEntityRequest("PUT",tableName, partitionKey, rowKey, json, false)
}

func (tableStorageProxy *TableStorageProxy) DeleteTable(tableName string) {
	target := "Tables%28%27" + tableName + "%27%29"

	client := &http.Client{}
	request, _ := http.NewRequest("DELETE", tableStorageProxy.baseUrl+target, nil)
	request.Header.Set("Content-Type", "application/atom+xml")

	tableStorageProxy.executeRequest(request, client, target)
}

type CreateTableArgs struct {
	TableName string
}

func (tableStorageProxy *TableStorageProxy) CreateTable(tableName string) {
	json, _ := json.Marshal(CreateTableArgs{TableName: tableName})
	tableStorageProxy.postJson("Tables", json)
}

func (tableStorageProxy *TableStorageProxy) InsertEntity(tableName string, json []byte) {
	tableStorageProxy.postJson(tableName, json)
}

func (tableStorageProxy *TableStorageProxy) get(target string, query string) {
	client := &http.Client{}
	request, _ := http.NewRequest("GET", tableStorageProxy.baseUrl+target + query, nil)
	request.Header.Set("Accept", "application/json;odata=nometadata")

	tableStorageProxy.executeRequest(request, client, target)
}

func (tableStorageProxy *TableStorageProxy) postJson(target string, json []byte) {
	client := &http.Client{}
	request, _ := http.NewRequest("POST", tableStorageProxy.baseUrl+target, bytes.NewBuffer(json))
	addPayloadHeaders(request, len(json))

	tableStorageProxy.executeRequest(request, client, target)
}

func addPayloadHeaders(request *http.Request, bodyLength int) {
	request.Header.Set("Content-Type", "application/json")
	request.Header.Set("Content-Length", string(bodyLength))
}

func (tableStorageProxy *TableStorageProxy) executeRequest(request *http.Request, client *http.Client, target string) {
	xmsdate, Authentication := tableStorageProxy.calculateDateAndAuthentication(target)

	request.Header.Set("x-ms-date", xmsdate)
	request.Header.Set("x-ms-version", "2013-08-15")
	request.Header.Set("Authorization", Authentication)

	requestDump, _ := httputil.DumpRequest(request, true)

	fmt.Printf("Request: %s\n", requestDump)

	response, _ := client.Do(request)

	responseDump, _ := httputil.DumpResponse(response, true)
	fmt.Printf("Response: %s\n", responseDump)
}

func (tableStorageProxy *TableStorageProxy)  executeEntityRequest(httpVerb string, tableName string, partitionKey string, rowKey string, json []byte, useIfMatch bool) {
	tableStorageProxy.executeCommonRequest(httpVerb, tableName + "%28PartitionKey=%27" + partitionKey + "%27,RowKey=%27" + rowKey + "%27%29", "", json, useIfMatch)
}

func (tableStorageProxy *TableStorageProxy)  executeCommonRequest(httpVerb string, target string, query string, json []byte, useIfMatch bool) {
	client := &http.Client{}
	request, _ := http.NewRequest(httpVerb, tableStorageProxy.baseUrl+target+query, bytes.NewBuffer(json))

	if json != nil {
		addPayloadHeaders(request, len(json))
	}

	if useIfMatch {
		request.Header.Set("If-Match", "*")
	}

	tableStorageProxy.executeRequest(request, client, target)
}

func (tableStorageProxy *TableStorageProxy) calculateDateAndAuthentication(target string) (string, string) {
	xmsdate := strings.Replace(time.Now().UTC().Add(-time.Minute).Format(time.RFC1123), "UTC", "GMT", -1)
	SignatureString := xmsdate + "\n/" + tableStorageProxy.goHaveStorage.GetAccount() + "/" + target
	Authentication := "SharedKeyLite " + tableStorageProxy.goHaveStorage.GetAccount() + ":" + computeHmac256(SignatureString, tableStorageProxy.goHaveStorage.GetKey())
	return xmsdate, Authentication
}

func computeHmac256(message string, key []byte) string {
	h := hmac.New(sha256.New, key)
	h.Write([]byte(message))
	return base64.StdEncoding.EncodeToString(h.Sum(nil))
}
<commit_msg>Omitting postJson method<commit_after>package tablestorageproxy

import (
	"bytes"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httputil"
	"strings"
	"time"
)

type GoHaveStorage interface {
	GetKey() []byte
	GetAccount() string
}

type TableStorageProxy struct {
	goHaveStorage GoHaveStorage
	baseUrl string
}

func New(goHaveStorage GoHaveStorage) *TableStorageProxy {
	var tableStorageProxy TableStorageProxy

	tableStorageProxy.goHaveStorage = goHaveStorage
	tableStorageProxy.baseUrl = "https://"+goHaveStorage.GetAccount()+".table.core.windows.net/"

	return &tableStorageProxy
}

func (tableStorageProxy *TableStorageProxy) QueryTables() {
	tableStorageProxy.get("Tables", "")
}

func (tableStorageProxy *TableStorageProxy) QueryEntity(tableName string, partitionKey string, rowKey string, selects string) {
	tableStorageProxy.get(tableName + "%28PartitionKey=%27" + partitionKey + "%27,RowKey=%27" + rowKey + "%27%29", "?$select="+selects)
}

func (tableStorageProxy *TableStorageProxy) QueryEntities(tableName string, selects string, filter string, top string) {
	tableStorageProxy.get(tableName, "?$filter="+filter + "&$select=" + selects+"&$top="+top)
}

func (tableStorageProxy *TableStorageProxy) DeleteEntity(tableName string, partitionKey string, rowKey string) {
	tableStorageProxy.executeEntityRequest("DELETE",tableName, partitionKey, rowKey, nil, true)
}

func (tableStorageProxy *TableStorageProxy) UpdateEntity(tableName string, partitionKey string, rowKey string, json []byte) {
	tableStorageProxy.executeEntityRequest("PUT",tableName, partitionKey, rowKey, json, true)
}

func (tableStorageProxy *TableStorageProxy) MergeEntity(tableName string, partitionKey string, rowKey string, json []byte) {
	tableStorageProxy.executeEntityRequest("MERGE",tableName, partitionKey, rowKey, json, true)
}

func (tableStorageProxy *TableStorageProxy) InsertOrMergeEntity(tableName string, partitionKey string, rowKey string, json []byte) {
	tableStorageProxy.executeEntityRequest("MERGE",tableName, partitionKey, rowKey, json, false)
}

func (tableStorageProxy *TableStorageProxy) InsertOrReplaceEntity(tableName string, partitionKey string, rowKey string, json []byte) {
	tableStorageProxy.executeEntityRequest("PUT",tableName, partitionKey, rowKey, json, false)
}

func (tableStorageProxy *TableStorageProxy) DeleteTable(tableName string) {
	target := "Tables%28%27" + tableName + "%27%29"

	client := &http.Client{}
	request, _ := http.NewRequest("DELETE", tableStorageProxy.baseUrl+target, nil)
	request.Header.Set("Content-Type", "application/atom+xml")

	tableStorageProxy.executeRequest(request, client, target)
}

type CreateTableArgs struct {
	TableName string
}

func (tableStorageProxy *TableStorageProxy) CreateTable(tableName string) {
	json, _ := json.Marshal(CreateTableArgs{TableName: tableName})
	tableStorageProxy.executeCommonRequest("POST", "Tables", "", json, false)
}

func (tableStorageProxy *TableStorageProxy) InsertEntity(tableName string, json []byte) {
	tableStorageProxy.executeCommonRequest("POST", tableName, "", json, false)
}

func (tableStorageProxy *TableStorageProxy) get(target string, query string) {
	client := &http.Client{}
	request, _ := http.NewRequest("GET", tableStorageProxy.baseUrl+target + query, nil)
	request.Header.Set("Accept", "application/json;odata=nometadata")

	tableStorageProxy.executeRequest(request, client, target)
}

func addPayloadHeaders(request *http.Request, bodyLength int) {
	request.Header.Set("Content-Type", "application/json")
	request.Header.Set("Content-Length", string(bodyLength))
}

func (tableStorageProxy *TableStorageProxy) executeRequest(request *http.Request, client *http.Client, target string) {
	xmsdate, Authentication := tableStorageProxy.calculateDateAndAuthentication(target)

	request.Header.Set("x-ms-date", xmsdate)
	request.Header.Set("x-ms-version", "2013-08-15")
	request.Header.Set("Authorization", Authentication)

	requestDump, _ := httputil.DumpRequest(request, true)

	fmt.Printf("Request: %s\n", requestDump)

	response, _ := client.Do(request)

	responseDump, _ := httputil.DumpResponse(response, true)
	fmt.Printf("Response: %s\n", responseDump)
}

func (tableStorageProxy *TableStorageProxy)  executeEntityRequest(httpVerb string, tableName string, partitionKey string, rowKey string, json []byte, useIfMatch bool) {
	tableStorageProxy.executeCommonRequest(httpVerb, tableName + "%28PartitionKey=%27" + partitionKey + "%27,RowKey=%27" + rowKey + "%27%29", "", json, useIfMatch)
}

func (tableStorageProxy *TableStorageProxy)  executeCommonRequest(httpVerb string, target string, query string, json []byte, useIfMatch bool) {
	client := &http.Client{}
	request, _ := http.NewRequest(httpVerb, tableStorageProxy.baseUrl+target+query, bytes.NewBuffer(json))

	if json != nil {
		addPayloadHeaders(request, len(json))
	}

	if useIfMatch {
		request.Header.Set("If-Match", "*")
	}

	tableStorageProxy.executeRequest(request, client, target)
}

func (tableStorageProxy *TableStorageProxy) calculateDateAndAuthentication(target string) (string, string) {
	xmsdate := strings.Replace(time.Now().UTC().Add(-time.Minute).Format(time.RFC1123), "UTC", "GMT", -1)
	SignatureString := xmsdate + "\n/" + tableStorageProxy.goHaveStorage.GetAccount() + "/" + target
	Authentication := "SharedKeyLite " + tableStorageProxy.goHaveStorage.GetAccount() + ":" + computeHmac256(SignatureString, tableStorageProxy.goHaveStorage.GetKey())
	return xmsdate, Authentication
}

func computeHmac256(message string, key []byte) string {
	h := hmac.New(sha256.New, key)
	h.Write([]byte(message))
	return base64.StdEncoding.EncodeToString(h.Sum(nil))
}
<|endoftext|>