<commit_before>package main

import (
	"flag"
	"log"
	"net/http"
	"net/url"
	"os"

	"github.com/bitrise-io/bitrise-webhooks/config"
	"github.com/bitrise-io/bitrise-webhooks/metrics"
)

func stringFlagOrEnv(flagValue *string, envKey string) string {
	if flagValue != nil && *flagValue != "" {
		return *flagValue
	}
	return os.Getenv(envKey)
}

func stringFlag(flagValue *string) string {
	if flagValue != nil && *flagValue != "" {
		return *flagValue
	}
	return ""
}

func main() {
	var (
		portFlag          = flag.String("port", "", `Use port [$PORT]`)
		sendRequestToFlag = flag.String("send-request-to", "", `Send requests to this URL. If set, every request will be sent to this URL and not to bitrise.io. You can use this to debug/test, e.g. with http://requestb.in [$SEND_REQUEST_TO]`)
		newRelicKeyFlag   = flag.String("newrelic", "", `NewRelic license key`)
	)
	flag.Parse()

	port := stringFlagOrEnv(portFlag, "PORT")
	if port == "" {
		log.Fatal("Port must be set")
	}
	config.SetupServerEnvMode()

	requestToStr := stringFlagOrEnv(sendRequestToFlag, "SEND_REQUEST_TO")
	if requestToStr != "" {
		url, err := url.Parse(requestToStr)
		if err != nil {
			log.Fatalf("Failed to parse send-request-to (%s) as a URL, error: %s", requestToStr, err)
		}
		config.SendRequestToURL = url
		log.Printf(" (!) Send-Request-To specified, every request will be sent to: %s", config.SendRequestToURL)
	}

	// Monitoring
	if config.GetServerEnvMode() == config.ServerEnvModeProd {
		newRelicKey := stringFlagOrEnv(newRelicKeyFlag, "NEW_RELIC_LICENSE_KEY")
		metrics.SetupNewRelic("BitriseWebhooksProcessor", newRelicKey)
	} else {
		log.Println(" (!) Skipping NewRelic setup - environment is not 'production'")
	}

	// Routing
	setupRoutes()

	log.Println("Starting - using port:", port)
	if err := http.ListenAndServe(":"+port, nil); err != nil {
		log.Fatalf("Failed to ListenAndServe: %s", err)
	}
}
<commit_msg>NEW_RELIC_LICENSE_KEY is now optional, even in production mode<commit_after>package main

import (
	"flag"
	"log"
	"net/http"
	"net/url"
	"os"

	"github.com/bitrise-io/bitrise-webhooks/config"
	"github.com/bitrise-io/bitrise-webhooks/metrics"
)

func stringFlagOrEnv(flagValue *string, envKey string) string {
	if flagValue != nil && *flagValue != "" {
		return *flagValue
	}
	return os.Getenv(envKey)
}

func stringFlag(flagValue *string) string {
	if flagValue != nil && *flagValue != "" {
		return *flagValue
	}
	return ""
}

func main() {
	var (
		portFlag          = flag.String("port", "", `Use port [$PORT]`)
		sendRequestToFlag = flag.String("send-request-to", "", `Send requests to this URL. If set, every request will be sent to this URL and not to bitrise.io. You can use this to debug/test, e.g. with http://requestb.in [$SEND_REQUEST_TO]`)
		newRelicKeyFlag   = flag.String("newrelic", "", `NewRelic license key`)
	)
	flag.Parse()

	port := stringFlagOrEnv(portFlag, "PORT")
	if port == "" {
		log.Fatal("Port must be set")
	}
	config.SetupServerEnvMode()

	requestToStr := stringFlagOrEnv(sendRequestToFlag, "SEND_REQUEST_TO")
	if requestToStr != "" {
		url, err := url.Parse(requestToStr)
		if err != nil {
			log.Fatalf("Failed to parse send-request-to (%s) as a URL, error: %s", requestToStr, err)
		}
		config.SendRequestToURL = url
		log.Printf(" (!) Send-Request-To specified, every request will be sent to: %s", config.SendRequestToURL)
	}

	// Monitoring
	if newRelicKey := stringFlagOrEnv(newRelicKeyFlag, "NEW_RELIC_LICENSE_KEY"); newRelicKey != "" && config.GetServerEnvMode() == config.ServerEnvModeProd {
		metrics.SetupNewRelic("BitriseWebhooksProcessor", newRelicKey)
	} else {
		log.Println(" (!) Skipping NewRelic setup - environment is not 'production'")
	}

	// Routing
	setupRoutes()

	log.Println("Starting - using port:", port)
	if err := http.ListenAndServe(":"+port, nil); err != nil {
		log.Fatalf("Failed to ListenAndServe: %s", err)
	}
}
<|endoftext|>


<commit_before>// Copyright 2012 tsuru 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 main

import (
	"fmt"
	"github.com/globocom/tsuru/cmd"
	"launchpad.net/gnuflag"
	"net/http"
	"os"
	"strings"
)

const version = "0.2"

var appname = gnuflag.String("app", "", "App name for running app related commands.")

func validateTsuruVersion(resp *http.Response, context *cmd.Context) {
	format := `You're using an unsupported version of tsuru client.

You must have at least version %s, your current version is %s.`
	var (
		bigger bool
		limit  int
	)
	supportedHeader := resp.Header.Get("Supported-Tsuru")
	partsSupported := strings.Split(supportedHeader, ".")
	partsCurrent := strings.Split(version, ".")
	if len(partsSupported) > len(partsCurrent) {
		limit = len(partsCurrent)
		bigger = true
	} else {
		limit = len(partsSupported)
	}
	for i := 0; i < limit; i++ {
		if partsCurrent[i] < partsSupported[i] {
			fmt.Fprintf(context.Stderr, format, supportedHeader, version)
			return
		}
	}
	if bigger {
		fmt.Fprintf(context.Stderr, format, supportedHeader, version)
	}
}

func buildManager(name string) *cmd.Manager {
	m := cmd.BuildBaseManager(name, version)
	m.Register(&AppRun{})
	m.Register(&AppInfo{})
	m.Register(&AppCreate{})
	m.Register(&AppRemove{})
	m.Register(&AppList{})
	m.Register(&AppLog{})
	m.Register(&AppGrant{})
	m.Register(&AppRevoke{})
	m.Register(&AppRestart{})
	m.Register(&EnvGet{})
	m.Register(&EnvSet{})
	m.Register(&EnvUnset{})
	m.Register(&KeyAdd{})
	m.Register(&KeyRemove{})
	m.Register(&ServiceList{})
	m.Register(&ServiceAdd{})
	m.Register(&ServiceRemove{})
	m.Register(&ServiceBind{})
	m.Register(&ServiceUnbind{})
	m.Register(&ServiceDoc{})
	m.Register(&ServiceInfo{})
	m.Register(&ServiceInstanceStatus{})
	return m
}

func main() {
	gnuflag.Parse(true)
	name := cmd.ExtractProgramName(os.Args[0])
	manager := buildManager(name)
	args := gnuflag.Args()
	manager.Run(args)
}
<commit_msg>cmd, cmd/tsuru: added generic version checking in the cmd package<commit_after>// Copyright 2012 tsuru 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 main

import (
	"fmt"
	"github.com/globocom/tsuru/cmd"
	"launchpad.net/gnuflag"
	"net/http"
	"os"
)

const version = "0.2"

var appname = gnuflag.String("app", "", "App name for running app related commands.")

func validateTsuruVersion(resp *http.Response, context *cmd.Context) {
	format := `You're using an unsupported version of tsuru client.

You must have at least version %s, your current version is %s.`
	supportedHeader := resp.Header.Get("Supported-Tsuru")
	if !cmd.ValidateVersion(supportedHeader, version) {
		fmt.Fprintf(context.Stderr, format, supportedHeader, version)
	}
}

func buildManager(name string) *cmd.Manager {
	m := cmd.BuildBaseManager(name, version)
	m.Register(&AppRun{})
	m.Register(&AppInfo{})
	m.Register(&AppCreate{})
	m.Register(&AppRemove{})
	m.Register(&AppList{})
	m.Register(&AppLog{})
	m.Register(&AppGrant{})
	m.Register(&AppRevoke{})
	m.Register(&AppRestart{})
	m.Register(&EnvGet{})
	m.Register(&EnvSet{})
	m.Register(&EnvUnset{})
	m.Register(&KeyAdd{})
	m.Register(&KeyRemove{})
	m.Register(&ServiceList{})
	m.Register(&ServiceAdd{})
	m.Register(&ServiceRemove{})
	m.Register(&ServiceBind{})
	m.Register(&ServiceUnbind{})
	m.Register(&ServiceDoc{})
	m.Register(&ServiceInfo{})
	m.Register(&ServiceInstanceStatus{})
	return m
}

func main() {
	gnuflag.Parse(true)
	name := cmd.ExtractProgramName(os.Args[0])
	manager := buildManager(name)
	args := gnuflag.Args()
	manager.Run(args)
}
<|endoftext|>


<commit_before>package main

import (
	"errors"
	"log"
	"os"
	"strconv"
	"time"

	"github.com/gizak/termui"
	"github.com/kolo/xmlrpc"
	"github.com/spf13/viper"
)

var selector int

// AccountReturn contains fields for informations about the Gandi account
type AccountReturn struct {
	AverageCreditCost     float64   `xmlrpc:"average_credit_cost"`
	Credits               int       `xmlrpc:"credits"`
	CycleDay              int       `xmlrpc:"cycle_day"`
	DateCreditsExpiration time.Time `xmlrpc:"date_credits_expiration"`
	FullName              string    `xmlrpc:"fullname"`
	Handle                string    `xmlrpc:"handle"`
	ID                    int       `xmlrpc:"id"`
}

// DiskReturn contains fields for informations about the Disks
type DiskReturn struct {
	CanSnapshot   bool      `xmlrpc:"can_snapshot"`
	DatacenterID  int       `xmlrpc:"datacenter_id"`
	DateCreated   time.Time `xmlrpc:"date_created"`
	DateUpdated   time.Time `xmlrpc:"date_updated"`
	ID            int       `xmlrpc:"id"`
	IsBootDisk    bool      `xmlrpc:"is_boot_disk"`
	KernelVersion string    `xmlrpc:"kernel_version"`
	Label         string    `xmlrpc:"label"`
	Name          string    `xmlrpc:"name"`
	Size          int       `xmlrpc:"size"`
	State         string    `xmlrpc:"state"`
	TotalSize     int       `xmlrpc:"total_size"`
	Type          string    `xmlrpc:"type"`
	Visibility    string    `xmlrpc:"visibility"`
}

// VMReturn contains fields for informations about the virtual machines
type VMReturn struct {
	AiActive     int          `xmlrpc:"ai_active"`
	Console      int          `xmlrpc:"console"`
	ConsoleURL   string       `xmlrpc:"console_url"`
	Cores        int          `xmlrpc:"cores"`
	DatacenterID int          `xmlrpc:"datacenter_id"`
	DateCreated  time.Time    `xmlrpc:"date_created"`
	DateUpdated  time.Time    `xmlrpc:"date_updated"`
	Description  string       `xmlrpc:"description"`
	Disks        []DiskReturn `xmlrpc:"disks"`
	Farm         string       `xmlrpc:"farm"`
	FlexShares   int          `xmlrpc:"flex_shares"`
	Hostname     string       `xmlrpc:"hostname"`
	HVMState     string       `xmlrpc:"hvm_state"`
	ID           int          `xmlrpc:"id"`
	Memory       int          `xmlrpc:"memory"`
	State        string       `xmlrpc:"state"`
	VMmaxMemory  int          `xmlrpc:"vm_max_memory"`
}

// LoadAPI returns the api and apiKey according to the settings defined in the
// configuration file, respectively.
func LoadAPI() (api *xmlrpc.Client, apiKey string, err error) {
	viper.SetConfigName("bapu")

	homePath := os.Getenv("HOME")
	viper.AddConfigPath(homePath)
	viper.AddConfigPath("/usr/local/etc")
	viper.AddConfigPath("/etc")

	err = viper.ReadInConfig()
	if err != nil {
		return api, apiKey, err
	}

	production := viper.GetBool("production.enabled")
	if production {
		apiKey = viper.GetString("production.apiKey")
		api, err = xmlrpc.NewClient("https://rpc.gandi.net/xmlrpc/", nil)
		if err != nil {
			return api, apiKey, err
		}
	}

	development := viper.GetBool("development.enabled")
	if development {
		log.Println("Development Config found")
		api, err = xmlrpc.NewClient("https://rpc.ote.gandi.net/xmlrpc/", nil)
		if err != nil {
			return api, apiKey, err
		}
		apiKey = viper.GetString("development.apiKey")
	}

	if api == nil {
		return api, apiKey, errors.New("neither production nor development environment enabled in config")
	}

	return api, apiKey, nil
}

func serverList(list []VMReturn) (servers [][]string) {

	servers = append(servers, []string{
		"Selected",
		"Hostname",
		"Datacenter",
		"Cores",
		"Memory",
		"State",
	})

	for i, val := range list {
		s := ""
		if selector == i {
			s = "*"
		}
		servers = append(servers, []string{
			s,
			val.Hostname,
			strconv.Itoa(val.DatacenterID),
			strconv.Itoa(val.Cores),
			strconv.Itoa(val.Memory) + "MB",
			val.State,
		})
	}

	return servers
}

func main() {
	// Load API
	api, apiKey, err := LoadAPI()
	if err != nil {
		log.Fatal(err)
	}

	// initialize termui
	err = termui.Init()
	if err != nil {
		log.Fatal(err)
	}
	defer termui.Close()

	// Title
	uiTitle := termui.NewPar("Bapu -- Control your Gandi Machines")
	uiTitle.Border = false
	uiTitle.Height = 3
	uiTitle.TextFgColor = termui.ColorMagenta

	// Summary
	var hostingVMCount *int
	err = api.Call("hosting.vm.count", apiKey, &hostingVMCount)
	if err != nil {
		log.Fatal(err)
	}
	var hostingAccountInfo *AccountReturn
	err = api.Call("hosting.account.info", apiKey, &hostingAccountInfo)
	if err != nil {
		log.Fatal(err)
	}

	info := *hostingAccountInfo

	uiSummary := termui.NewPar("Owner: " + info.FullName + "    Virtual Machines: " + strconv.Itoa(*hostingVMCount) + "    Remaining Credit: " + strconv.Itoa(info.Credits))
	uiSummary.Height = 3
	uiSummary.Border = true
	uiSummary.BorderLabel = "Summary"
	uiSummary.TextFgColor = termui.ColorWhite

	// List instances
	var hostingVMList *[]VMReturn
	err = api.Call("hosting.vm.list", apiKey, &hostingVMList)
	if err != nil {
		log.Fatal(err)
	}

	list := *hostingVMList

	uiTable := termui.NewTable()
	uiTable.Rows = serverList(list)
	uiTable.FgColor = termui.ColorWhite
	uiTable.BgColor = termui.ColorDefault
	uiTable.TextAlign = termui.AlignCenter
	uiTable.Seperator = false
	uiTable.Analysis()
	uiTable.SetSize()
	uiTable.BgColors[0] = termui.ColorWhite
	uiTable.FgColors[0] = termui.ColorBlack
	uiTable.Y = 20
	uiTable.X = 0
	uiTable.Border = false
	for i := 0; i < len(list); i++ {
		switch list[i].State {
		case "paused":
			uiTable.BgColors[i+1] = termui.ColorBlack
			uiTable.FgColors[i+1] = termui.ColorWhite
		case "running":
			uiTable.BgColors[i+1] = termui.ColorBlue
			uiTable.FgColors[i+1] = termui.ColorWhite
		case "halted":
			uiTable.BgColors[i+1] = termui.ColorYellow
			uiTable.FgColors[i+1] = termui.ColorBlack
		case "locked":
			uiTable.BgColors[i+1] = termui.ColorMagenta
			uiTable.FgColors[i+1] = termui.ColorGreen
		case "being_created":
			uiTable.BgColors[i+1] = termui.ColorWhite
			uiTable.FgColors[i+1] = termui.ColorBlack
		case "deleted":
			uiTable.BgColors[i+1] = termui.ColorBlack
			uiTable.FgColors[i+1] = termui.ColorRed
		}
	}

	// Commands
	uiCommands := termui.NewPar("<[S]tart>    <St[o]p>    <[R]eboot>  Virtual Machine |   <[Q]uit>")
	uiCommands.Height = 3
	uiCommands.Border = false
	uiCommands.BorderLabel = "Summary"
	uiCommands.TextFgColor = termui.ColorBlack
	uiCommands.TextBgColor = termui.ColorWhite

	// Create termui Grid system
	termui.Body.AddRows(
		termui.NewRow(
			termui.NewCol(12, 0, uiTitle),
		),
		termui.NewRow(
			termui.NewCol(12, 0, uiSummary),
		),
		termui.NewRow(
			termui.NewCol(12, 0, uiTable),
		),
		termui.NewRow(
			termui.NewCol(12, 0, uiCommands),
		),
	)

	// calculate layout
	termui.Body.Align()
	termui.Render(termui.Body)

	// Quit with q
	termui.Handle("/sys/kbd/q", func(termui.Event) {
		termui.StopLoop()
	})

	termui.Handle("/sys/kbd/<up>", func(termui.Event) {
		if selector > 0 {
			selector--
		}
		uiTable.Rows = serverList(list)
		termui.Render(termui.Body)
	})

	termui.Handle("/sys/kbd/<down>", func(termui.Event) {
		if selector < len(list)-1 {
			selector++
		}
		uiTable.Rows = serverList(list)
		termui.Render(termui.Body)
	})

	termui.Handle("/sys/kbd/s", func(termui.Event) {
		err = api.Call("hosting.vm.start", []interface{}{apiKey, list[selector].ID}, nil)
		if err != nil {
			log.Fatal(err)
		}

		confirmation := termui.NewPar(list[selector].Hostname + " (ID " + strconv.Itoa(list[selector].ID) + ") is being started")
		confirmation.Height = 4
		confirmation.Width = 50
		confirmation.Y = 5
		confirmation.Border = true
		termui.Render(confirmation)
	})

	termui.Handle("/sys/kbd/o", func(termui.Event) {
		err = api.Call("hosting.vm.stop", []interface{}{apiKey, list[selector].ID}, nil)
		if err != nil {
			log.Fatal(err)
		}
		confirmation := termui.NewPar(list[selector].Hostname + " (ID " + strconv.Itoa(list[selector].ID) + ") is being stopped")
		confirmation.Height = 4
		confirmation.Width = 50
		confirmation.Y = 5
		confirmation.Border = true
		termui.Render(confirmation)
	})

	termui.Handle("/sys/kbd/r", func(termui.Event) {
		err = api.Call("hosting.vm.reboot", []interface{}{apiKey, list[selector].ID}, nil)
		if err != nil {
			log.Fatal(err)
		}
		confirmation := termui.NewPar(list[selector].Hostname + " (ID " + strconv.Itoa(list[selector].ID) + ") is being rebooted")
		confirmation.Height = 4
		confirmation.Width = 50
		confirmation.Y = 5
		confirmation.Border = true
		termui.Render(confirmation)
	})

	termui.Handle("/timer/1s", func(e termui.Event) {
		t := e.Data.(termui.EvtTimer)
		// t is a EvtTimer
		if t.Count%2 == 0 {
			termui.Body.Align()
			termui.Render(termui.Body)
		}
	})
	termui.Handle("/timer/1s", func(e termui.Event) {
		t := e.Data.(termui.EvtTimer)
		// t is a EvtTimer
		if t.Count%4 == 0 {
			err = api.Call("hosting.vm.list", apiKey, &hostingVMList)
			if err != nil {
				log.Fatal(err)
			}

			list = *hostingVMList
			uiTable.Rows = serverList(list)
			for i := 0; i < len(list); i++ {
				switch list[i].State {
				case "paused":
					uiTable.BgColors[i+1] = termui.ColorBlack
					uiTable.FgColors[i+1] = termui.ColorWhite
				case "running":
					uiTable.BgColors[i+1] = termui.ColorBlue
					uiTable.FgColors[i+1] = termui.ColorWhite
				case "halted":
					uiTable.BgColors[i+1] = termui.ColorYellow
					uiTable.FgColors[i+1] = termui.ColorBlack
				case "locked":
					uiTable.BgColors[i+1] = termui.ColorMagenta
					uiTable.FgColors[i+1] = termui.ColorGreen
				case "being_created":
					uiTable.BgColors[i+1] = termui.ColorWhite
					uiTable.FgColors[i+1] = termui.ColorBlack
				case "deleted":
					uiTable.BgColors[i+1] = termui.ColorBlack
					uiTable.FgColors[i+1] = termui.ColorRed
				}
			}
			termui.Render(termui.Body)
		}
	})

	termui.Loop()
}
<commit_msg>license stuff<commit_after>// Copyright 2017, Carlo Strub <cs@carlostrub.ch>
// BSD 3-Clause License, see LICENSE file for details.

package main

import (
	"errors"
	"log"
	"os"
	"strconv"
	"time"

	"github.com/gizak/termui"
	"github.com/kolo/xmlrpc"
	"github.com/spf13/viper"
)

var selector int

// AccountReturn contains fields for informations about the Gandi account
type AccountReturn struct {
	AverageCreditCost     float64   `xmlrpc:"average_credit_cost"`
	Credits               int       `xmlrpc:"credits"`
	CycleDay              int       `xmlrpc:"cycle_day"`
	DateCreditsExpiration time.Time `xmlrpc:"date_credits_expiration"`
	FullName              string    `xmlrpc:"fullname"`
	Handle                string    `xmlrpc:"handle"`
	ID                    int       `xmlrpc:"id"`
}

// DiskReturn contains fields for informations about the Disks
type DiskReturn struct {
	CanSnapshot   bool      `xmlrpc:"can_snapshot"`
	DatacenterID  int       `xmlrpc:"datacenter_id"`
	DateCreated   time.Time `xmlrpc:"date_created"`
	DateUpdated   time.Time `xmlrpc:"date_updated"`
	ID            int       `xmlrpc:"id"`
	IsBootDisk    bool      `xmlrpc:"is_boot_disk"`
	KernelVersion string    `xmlrpc:"kernel_version"`
	Label         string    `xmlrpc:"label"`
	Name          string    `xmlrpc:"name"`
	Size          int       `xmlrpc:"size"`
	State         string    `xmlrpc:"state"`
	TotalSize     int       `xmlrpc:"total_size"`
	Type          string    `xmlrpc:"type"`
	Visibility    string    `xmlrpc:"visibility"`
}

// VMReturn contains fields for informations about the virtual machines
type VMReturn struct {
	AiActive     int          `xmlrpc:"ai_active"`
	Console      int          `xmlrpc:"console"`
	ConsoleURL   string       `xmlrpc:"console_url"`
	Cores        int          `xmlrpc:"cores"`
	DatacenterID int          `xmlrpc:"datacenter_id"`
	DateCreated  time.Time    `xmlrpc:"date_created"`
	DateUpdated  time.Time    `xmlrpc:"date_updated"`
	Description  string       `xmlrpc:"description"`
	Disks        []DiskReturn `xmlrpc:"disks"`
	Farm         string       `xmlrpc:"farm"`
	FlexShares   int          `xmlrpc:"flex_shares"`
	Hostname     string       `xmlrpc:"hostname"`
	HVMState     string       `xmlrpc:"hvm_state"`
	ID           int          `xmlrpc:"id"`
	Memory       int          `xmlrpc:"memory"`
	State        string       `xmlrpc:"state"`
	VMmaxMemory  int          `xmlrpc:"vm_max_memory"`
}

// LoadAPI returns the api and apiKey according to the settings defined in the
// configuration file, respectively.
func LoadAPI() (api *xmlrpc.Client, apiKey string, err error) {
	viper.SetConfigName("bapu")

	homePath := os.Getenv("HOME")
	viper.AddConfigPath(homePath)
	viper.AddConfigPath("/usr/local/etc")
	viper.AddConfigPath("/etc")

	err = viper.ReadInConfig()
	if err != nil {
		return api, apiKey, err
	}

	production := viper.GetBool("production.enabled")
	if production {
		apiKey = viper.GetString("production.apiKey")
		api, err = xmlrpc.NewClient("https://rpc.gandi.net/xmlrpc/", nil)
		if err != nil {
			return api, apiKey, err
		}
	}

	development := viper.GetBool("development.enabled")
	if development {
		log.Println("Development Config found")
		api, err = xmlrpc.NewClient("https://rpc.ote.gandi.net/xmlrpc/", nil)
		if err != nil {
			return api, apiKey, err
		}
		apiKey = viper.GetString("development.apiKey")
	}

	if api == nil {
		return api, apiKey, errors.New("neither production nor development environment enabled in config")
	}

	return api, apiKey, nil
}

func serverList(list []VMReturn) (servers [][]string) {

	servers = append(servers, []string{
		"Selected",
		"Hostname",
		"Datacenter",
		"Cores",
		"Memory",
		"State",
	})

	for i, val := range list {
		s := ""
		if selector == i {
			s = "*"
		}
		servers = append(servers, []string{
			s,
			val.Hostname,
			strconv.Itoa(val.DatacenterID),
			strconv.Itoa(val.Cores),
			strconv.Itoa(val.Memory) + "MB",
			val.State,
		})
	}

	return servers
}

func main() {
	// Load API
	api, apiKey, err := LoadAPI()
	if err != nil {
		log.Fatal(err)
	}

	// initialize termui
	err = termui.Init()
	if err != nil {
		log.Fatal(err)
	}
	defer termui.Close()

	// Title
	uiTitle := termui.NewPar("Bapu -- Control your Gandi Machines")
	uiTitle.Border = false
	uiTitle.Height = 3
	uiTitle.TextFgColor = termui.ColorMagenta

	// Summary
	var hostingVMCount *int
	err = api.Call("hosting.vm.count", apiKey, &hostingVMCount)
	if err != nil {
		log.Fatal(err)
	}
	var hostingAccountInfo *AccountReturn
	err = api.Call("hosting.account.info", apiKey, &hostingAccountInfo)
	if err != nil {
		log.Fatal(err)
	}

	info := *hostingAccountInfo

	uiSummary := termui.NewPar("Owner: " + info.FullName + "    Virtual Machines: " + strconv.Itoa(*hostingVMCount) + "    Remaining Credit: " + strconv.Itoa(info.Credits))
	uiSummary.Height = 3
	uiSummary.Border = true
	uiSummary.BorderLabel = "Summary"
	uiSummary.TextFgColor = termui.ColorWhite

	// List instances
	var hostingVMList *[]VMReturn
	err = api.Call("hosting.vm.list", apiKey, &hostingVMList)
	if err != nil {
		log.Fatal(err)
	}

	list := *hostingVMList

	uiTable := termui.NewTable()
	uiTable.Rows = serverList(list)
	uiTable.FgColor = termui.ColorWhite
	uiTable.BgColor = termui.ColorDefault
	uiTable.TextAlign = termui.AlignCenter
	uiTable.Seperator = false
	uiTable.Analysis()
	uiTable.SetSize()
	uiTable.BgColors[0] = termui.ColorWhite
	uiTable.FgColors[0] = termui.ColorBlack
	uiTable.Y = 20
	uiTable.X = 0
	uiTable.Border = false
	for i := 0; i < len(list); i++ {
		switch list[i].State {
		case "paused":
			uiTable.BgColors[i+1] = termui.ColorBlack
			uiTable.FgColors[i+1] = termui.ColorWhite
		case "running":
			uiTable.BgColors[i+1] = termui.ColorBlue
			uiTable.FgColors[i+1] = termui.ColorWhite
		case "halted":
			uiTable.BgColors[i+1] = termui.ColorYellow
			uiTable.FgColors[i+1] = termui.ColorBlack
		case "locked":
			uiTable.BgColors[i+1] = termui.ColorMagenta
			uiTable.FgColors[i+1] = termui.ColorGreen
		case "being_created":
			uiTable.BgColors[i+1] = termui.ColorWhite
			uiTable.FgColors[i+1] = termui.ColorBlack
		case "deleted":
			uiTable.BgColors[i+1] = termui.ColorBlack
			uiTable.FgColors[i+1] = termui.ColorRed
		}
	}

	// Commands
	uiCommands := termui.NewPar("<[S]tart>    <St[o]p>    <[R]eboot>  Virtual Machine |   <[Q]uit>")
	uiCommands.Height = 3
	uiCommands.Border = false
	uiCommands.BorderLabel = "Summary"
	uiCommands.TextFgColor = termui.ColorBlack
	uiCommands.TextBgColor = termui.ColorWhite

	// Create termui Grid system
	termui.Body.AddRows(
		termui.NewRow(
			termui.NewCol(12, 0, uiTitle),
		),
		termui.NewRow(
			termui.NewCol(12, 0, uiSummary),
		),
		termui.NewRow(
			termui.NewCol(12, 0, uiTable),
		),
		termui.NewRow(
			termui.NewCol(12, 0, uiCommands),
		),
	)

	// calculate layout
	termui.Body.Align()
	termui.Render(termui.Body)

	// Quit with q
	termui.Handle("/sys/kbd/q", func(termui.Event) {
		termui.StopLoop()
	})

	termui.Handle("/sys/kbd/<up>", func(termui.Event) {
		if selector > 0 {
			selector--
		}
		uiTable.Rows = serverList(list)
		termui.Render(termui.Body)
	})

	termui.Handle("/sys/kbd/<down>", func(termui.Event) {
		if selector < len(list)-1 {
			selector++
		}
		uiTable.Rows = serverList(list)
		termui.Render(termui.Body)
	})

	termui.Handle("/sys/kbd/s", func(termui.Event) {
		err = api.Call("hosting.vm.start", []interface{}{apiKey, list[selector].ID}, nil)
		if err != nil {
			log.Fatal(err)
		}

		confirmation := termui.NewPar(list[selector].Hostname + " (ID " + strconv.Itoa(list[selector].ID) + ") is being started")
		confirmation.Height = 4
		confirmation.Width = 50
		confirmation.Y = 5
		confirmation.Border = true
		termui.Render(confirmation)
	})

	termui.Handle("/sys/kbd/o", func(termui.Event) {
		err = api.Call("hosting.vm.stop", []interface{}{apiKey, list[selector].ID}, nil)
		if err != nil {
			log.Fatal(err)
		}
		confirmation := termui.NewPar(list[selector].Hostname + " (ID " + strconv.Itoa(list[selector].ID) + ") is being stopped")
		confirmation.Height = 4
		confirmation.Width = 50
		confirmation.Y = 5
		confirmation.Border = true
		termui.Render(confirmation)
	})

	termui.Handle("/sys/kbd/r", func(termui.Event) {
		err = api.Call("hosting.vm.reboot", []interface{}{apiKey, list[selector].ID}, nil)
		if err != nil {
			log.Fatal(err)
		}
		confirmation := termui.NewPar(list[selector].Hostname + " (ID " + strconv.Itoa(list[selector].ID) + ") is being rebooted")
		confirmation.Height = 4
		confirmation.Width = 50
		confirmation.Y = 5
		confirmation.Border = true
		termui.Render(confirmation)
	})

	termui.Handle("/timer/1s", func(e termui.Event) {
		t := e.Data.(termui.EvtTimer)
		// t is a EvtTimer
		if t.Count%2 == 0 {
			termui.Body.Align()
			termui.Render(termui.Body)
		}
	})
	termui.Handle("/timer/1s", func(e termui.Event) {
		t := e.Data.(termui.EvtTimer)
		// t is a EvtTimer
		if t.Count%4 == 0 {
			err = api.Call("hosting.vm.list", apiKey, &hostingVMList)
			if err != nil {
				log.Fatal(err)
			}

			list = *hostingVMList
			uiTable.Rows = serverList(list)
			for i := 0; i < len(list); i++ {
				switch list[i].State {
				case "paused":
					uiTable.BgColors[i+1] = termui.ColorBlack
					uiTable.FgColors[i+1] = termui.ColorWhite
				case "running":
					uiTable.BgColors[i+1] = termui.ColorBlue
					uiTable.FgColors[i+1] = termui.ColorWhite
				case "halted":
					uiTable.BgColors[i+1] = termui.ColorYellow
					uiTable.FgColors[i+1] = termui.ColorBlack
				case "locked":
					uiTable.BgColors[i+1] = termui.ColorMagenta
					uiTable.FgColors[i+1] = termui.ColorGreen
				case "being_created":
					uiTable.BgColors[i+1] = termui.ColorWhite
					uiTable.FgColors[i+1] = termui.ColorBlack
				case "deleted":
					uiTable.BgColors[i+1] = termui.ColorBlack
					uiTable.FgColors[i+1] = termui.ColorRed
				}
			}
			termui.Render(termui.Body)
		}
	})

	termui.Loop()
}
<|endoftext|>


<commit_before>package main

import (
	//"encoding/json"
	"github.com/julienschmidt/httprouter"
	"net/http"
	"log"
	"os"
	"fmt"
	//"database/sql"
	//"github.com/lib/pq"
)

func GetBlog(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	w.Write([]byte("blah"))
}

func GetSpinData(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	w.Write([]byte("blah"))
}

func GetServoData(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	w.Write([]byte("blah"))
}

func PostBlog(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	w.Write([]byte("blah"))
}

func PostSpinData(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	w.Write([]byte("blah"))
}

func PostServoData(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	w.Write([]byte("blah"))
}

func main() {
	router := httprouter.New()
	router.GET("/blog", GetBlog)
	router.GET("/spin", GetSpinData)
	router.GET("/servo", GetServoData)
	router.POST("/blog", PostBlog)
	router.POST("/spin", PostSpinData)
	router.POST("/servo", PostServoData)
	port := os.Getenv("PORT")
	if port == "" {
		port = "3000"
	}
	fmt.Printf("Starting server at localhost:%s...", port)
	log.Fatal(http.ListenAndServe(":"+port, router))
}<commit_msg>json..<commit_after>package main

import (
	"encoding/json"
	"github.com/julienschmidt/httprouter"
	"net/http"
	"log"
	"os"
	"fmt"
	//"database/sql"
	//"github.com/lib/pq"
)

func GetBlog(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	data,err := json.Marshal("blah")
	w.Write(data)
}

func GetSpinData(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	data,err := json.Marshal("blah")
	w.Write(data)
}

func GetServoData(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	data,err := json.Marshal("blah")
	w.Write(data)
}

func PostBlog(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	data,err := json.Marshal("blah")
	w.Write(data)
}

func PostSpinData(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	data,err := json.Marshal("blah")
	w.Write(data)
}

func PostServoData(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	data,err := json.Marshal("blah")
	w.Write(data)
}

func main() {
	router := httprouter.New()
	router.GET("/blog", GetBlog)
	router.GET("/spin", GetSpinData)
	router.GET("/servo", GetServoData)
	router.POST("/blog", PostBlog)
	router.POST("/spin", PostSpinData)
	router.POST("/servo", PostServoData)
	port := os.Getenv("PORT")
	if port == "" {
		port = "3000"
	}
	fmt.Printf("Starting server at localhost:%s...", port)
	log.Fatal(http.ListenAndServe(":"+port, router))
}<|endoftext|>


<commit_before>package main

import (
	"./srt"
	"fmt"
	"os"
	"sort"
	"time"
)

func main() {
	if len(os.Args) != 2 {
		fmt.Println("Usage:", os.Args[0], "[srt file]")
		return
	}
	b := srt.ReadSrtFile(os.Args[1])

	screen := NewSdlContext(640, 480)
	defer screen.Release()

	screen.Clear()

	tickDuration, _ := time.ParseDuration("10ms")
	tkr := time.NewTicker(tickDuration)
	defer tkr.Stop()

	var nextScript *srt.Script = &b[0]
	startTime := time.Now()
	/* var viasMs int */
	for {
		<-tkr.C
		currMs := time.Since(startTime)

		if currMs < 0 {
			nextScript = &b[0]
			continue
		}

		if nextScript == nil {
			fmt.Println("searching next script...")
			i := sort.Search(len(b), func(i int) bool {
				return b[i].Start >= currMs
			})

			if i >= len(b) {
				lastScript := b[len(b)-1]
				if lastScript.End < currMs {
					fmt.Println("book ended")
					break
				}
			}
			nextScript = &b[i]
		}

		if nextScript != nil && nextScript.Start <= currMs {
			screen.DisplayScript(nextScript)
			nextScript = nil
		}
	}
}
<commit_msg>Add varaible for vias<commit_after>package main

import (
	"./srt"
	"fmt"
	"os"
	"sort"
	"time"
)

func main() {
	if len(os.Args) != 2 {
		fmt.Println("Usage:", os.Args[0], "[srt file]")
		return
	}
	b := srt.ReadSrtFile(os.Args[1])

	screen := NewSdlContext(640, 480)
	defer screen.Release()

	screen.Clear()

	tickDuration, _ := time.ParseDuration("10ms")
	tkr := time.NewTicker(tickDuration)
	defer tkr.Stop()

	var vias time.Duration
	var nextScript *srt.Script
	startTime := time.Now()
	for {
		<-tkr.C
		currMs := time.Since(startTime)
		currMs += vias

		if currMs < 0 {
			nextScript = &b[0]
			continue
		}

		if nextScript == nil {
			i := sort.Search(len(b), func(i int) bool {
				return b[i].Start >= currMs
			})

			if i >= len(b) {
				lastScript := b[len(b)-1]
				if lastScript.End < currMs {
					fmt.Println("book ended")
					break
				}
			}
			nextScript = &b[i]
		}

		if nextScript != nil && nextScript.Start <= currMs {
			screen.DisplayScript(nextScript)
			nextScript = nil
		}
	}
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"time"

	flag "github.com/spf13/pflag"

	marathon "github.com/gambol99/go-marathon"
	"github.com/rcrowley/go-metrics"
)

var appChecker AppChecker
var alertManager AlertManager
var notifyManager NotifyManager

// Check settings
var minHealthyWarningThreshold float32
var minHealthyCriticalThreshold float32
var minInstancesWarningThreshold float32
var minInstancesCriticalThreshold float32

// Required flags
var marathonURI string
var checkInterval time.Duration
var alertSuppressDuration time.Duration
var debugMode bool

// Slack flags
var slackWebhooks string
var slackChannel string
var slackOwners string
var pidFile string

var DebugMetricsRegistry metrics.Registry

func main() {
	os.Args[0] = "marathon-alerts"
	defineFlags()
	flag.Parse()
	pid := []byte(fmt.Sprintf("%d\n", os.Getpid()))
	err := ioutil.WriteFile(pidFile, pid, 0644)
	if err != nil {
		fmt.Println("Unable to write pid file. ")
		log.Fatalf("Error - %v\n", err)
	}

	client, err := marathonClient(marathonURI)
	if err != nil {
		fmt.Printf("%v\n", err)
		os.Exit(1)
	}
	DebugMetricsRegistry = metrics.NewPrefixedRegistry("debug")

	minHealthyTasks := &MinHealthyTasks{
		DefaultCriticalThreshold: minHealthyCriticalThreshold,
		DefaultWarningThreshold:  minHealthyWarningThreshold,
	}
	minInstances := &MinInstances{
		DefaultCriticalThreshold: minHealthyCriticalThreshold,
		DefaultWarningThreshold:  minHealthyWarningThreshold,
	}
	checks := []Checker{minHealthyTasks, minInstances}

	appChecker = AppChecker{
		Client:        client,
		CheckInterval: checkInterval,
		Checks:        checks,
	}
	appChecker.Start()

	alertManager = AlertManager{
		CheckerChan:      appChecker.AlertsChannel,
		SuppressDuration: alertSuppressDuration,
	}
	alertManager.Start()

	var notifiers []Notifier
	slack := Slack{
		Webhook: slackWebhooks,
		Channel: slackChannel,
		Owners:  slackOwners,
	}
	notifiers = append(notifiers, &slack)
	notifyManager = NotifyManager{
		AlertChan: alertManager.NotifierChan,
		Notifiers: notifiers,
	}
	notifyManager.Start()

	go metrics.Log(metrics.DefaultRegistry, 60*time.Second, log.New(os.Stderr, "metrics: ", log.Lmicroseconds))
	if debugMode {
		go metrics.Log(DebugMetricsRegistry, 300*time.Second, log.New(os.Stderr, "debug-metrics: ", log.Lmicroseconds))
	}
	appChecker.RunWaitGroup.Wait()
	// Handle signals and cleanup all routines
}

func marathonClient(uri string) (marathon.Marathon, error) {
	config := marathon.NewDefaultConfig()
	config.URL = uri
	config.HTTPClient = &http.Client{
		Timeout: (30 * time.Second),
	}

	return marathon.NewClient(config)
}

func defineFlags() {
	flag.StringVar(&marathonURI, "uri", "", "Marathon URI to connect")
	flag.StringVar(&pidFile, "pid", "PID", "File to write PID file")
	flag.BoolVar(&debugMode, "debug", false, "Enable debug mode. More counters for now.")
	flag.DurationVar(&checkInterval, "check-interval", 30*time.Second, "Check runs periodically on this interval")
	flag.DurationVar(&alertSuppressDuration, "alerts-suppress-duration", 30*time.Minute, "Suppress alerts for this duration once notified")

	// Check flags
	flag.Float32Var(&minHealthyWarningThreshold, "check-min-healthy-warn-threshold", 0.75, "Min Healthy instances check warning threshold")
	flag.Float32Var(&minHealthyCriticalThreshold, "check-min-healthy-critical-threshold", 0.5, "Min Healthy instances check fail threshold")
	flag.Float32Var(&minInstancesWarningThreshold, "check-min-instances-warn-threshold", 0.75, "Min Instances check warning threshold")
	flag.Float32Var(&minInstancesCriticalThreshold, "check-min-instances-critical-threshold", 0.5, "Min Instances check fail threshold")

	// Slack flags
	flag.StringVar(&slackWebhooks, "slack-webhook", "", "Comma list of Slack webhooks to post the alert")
	flag.StringVar(&slackChannel, "slack-channel", "", "#Channel / @User to post the alert (defaults to webhook configuration)")
	flag.StringVar(&slackOwners, "slack-owner", "", "Comma list of owners who should be alerted on the post")
}
<commit_msg>minor edit on main.go<commit_after>package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"time"

	flag "github.com/spf13/pflag"

	marathon "github.com/gambol99/go-marathon"
	"github.com/rcrowley/go-metrics"
)

var appChecker AppChecker
var alertManager AlertManager
var notifyManager NotifyManager

// Check settings
var minHealthyWarningThreshold float32
var minHealthyCriticalThreshold float32
var minInstancesWarningThreshold float32
var minInstancesCriticalThreshold float32

// Required flags
var marathonURI string
var checkInterval time.Duration
var alertSuppressDuration time.Duration
var debugMode bool
var pidFile string

// Slack flags
var slackWebhooks string
var slackChannel string
var slackOwners string

var DebugMetricsRegistry metrics.Registry

func main() {
	os.Args[0] = "marathon-alerts"
	defineFlags()
	flag.Parse()
	pid := []byte(fmt.Sprintf("%d\n", os.Getpid()))
	err := ioutil.WriteFile(pidFile, pid, 0644)
	if err != nil {
		fmt.Println("Unable to write pid file. ")
		log.Fatalf("Error - %v\n", err)
	}

	client, err := marathonClient(marathonURI)
	if err != nil {
		fmt.Printf("%v\n", err)
		os.Exit(1)
	}
	DebugMetricsRegistry = metrics.NewPrefixedRegistry("debug")

	minHealthyTasks := &MinHealthyTasks{
		DefaultCriticalThreshold: minHealthyCriticalThreshold,
		DefaultWarningThreshold:  minHealthyWarningThreshold,
	}
	minInstances := &MinInstances{
		DefaultCriticalThreshold: minHealthyCriticalThreshold,
		DefaultWarningThreshold:  minHealthyWarningThreshold,
	}
	checks := []Checker{minHealthyTasks, minInstances}

	appChecker = AppChecker{
		Client:        client,
		CheckInterval: checkInterval,
		Checks:        checks,
	}
	appChecker.Start()

	alertManager = AlertManager{
		CheckerChan:      appChecker.AlertsChannel,
		SuppressDuration: alertSuppressDuration,
	}
	alertManager.Start()

	var notifiers []Notifier
	slack := Slack{
		Webhook: slackWebhooks,
		Channel: slackChannel,
		Owners:  slackOwners,
	}
	notifiers = append(notifiers, &slack)
	notifyManager = NotifyManager{
		AlertChan: alertManager.NotifierChan,
		Notifiers: notifiers,
	}
	notifyManager.Start()

	go metrics.Log(metrics.DefaultRegistry, 60*time.Second, log.New(os.Stderr, "metrics: ", log.Lmicroseconds))
	if debugMode {
		go metrics.Log(DebugMetricsRegistry, 300*time.Second, log.New(os.Stderr, "debug-metrics: ", log.Lmicroseconds))
	}
	appChecker.RunWaitGroup.Wait()
	// Handle signals and cleanup all routines
}

func marathonClient(uri string) (marathon.Marathon, error) {
	config := marathon.NewDefaultConfig()
	config.URL = uri
	config.HTTPClient = &http.Client{
		Timeout: (30 * time.Second),
	}

	return marathon.NewClient(config)
}

func defineFlags() {
	flag.StringVar(&marathonURI, "uri", "", "Marathon URI to connect")
	flag.StringVar(&pidFile, "pid", "PID", "File to write PID file")
	flag.BoolVar(&debugMode, "debug", false, "Enable debug mode. More counters for now.")
	flag.DurationVar(&checkInterval, "check-interval", 30*time.Second, "Check runs periodically on this interval")
	flag.DurationVar(&alertSuppressDuration, "alerts-suppress-duration", 30*time.Minute, "Suppress alerts for this duration once notified")

	// Check flags
	flag.Float32Var(&minHealthyWarningThreshold, "check-min-healthy-warn-threshold", 0.75, "Min Healthy instances check warning threshold")
	flag.Float32Var(&minHealthyCriticalThreshold, "check-min-healthy-critical-threshold", 0.5, "Min Healthy instances check fail threshold")
	flag.Float32Var(&minInstancesWarningThreshold, "check-min-instances-warn-threshold", 0.75, "Min Instances check warning threshold")
	flag.Float32Var(&minInstancesCriticalThreshold, "check-min-instances-critical-threshold", 0.5, "Min Instances check fail threshold")

	// Slack flags
	flag.StringVar(&slackWebhooks, "slack-webhook", "", "Comma list of Slack webhooks to post the alert")
	flag.StringVar(&slackChannel, "slack-channel", "", "#Channel / @User to post the alert (defaults to webhook configuration)")
	flag.StringVar(&slackOwners, "slack-owner", "", "Comma list of owners who should be alerted on the post")
}
<|endoftext|>


<commit_before>package main

import (
	"encoding/json"
	"flag"
	"github.com/belogik/goes"
	"log"
	"net/http"
	"net/url"
	"runtime"
	"strconv"
	"strings"
)

type Item struct {
	Title string  `json:"title"`
	Price float64 `json:"price"`
}

type Results struct {
	TotalItems uint64                 `json:"total_items"`
	Page       uint64                 `json:"page"`
	PerPage    uint64                 `json:"per_page"`
	Embedded   map[string]interface{} `json:"_embedded"`
}

func buildResults(data *goes.Response, meta map[string]uint64) *Results {
	var items []*Item

	dataItems := data.Hits.Hits
	for _, it := range dataItems {
		source := it.Source
		title := source["title"].(string)
		price := source["price"].(float64)

		item := &Item{
			Title: title,
			Price: price,
		}

		items = append(items, item)
	}

	embedded := map[string]interface{}{
		"items": items,
	}

	results := &Results{
		TotalItems: data.Hits.Total,
		Page:       meta["page"],
		PerPage:    meta["per_page"],
		Embedded:   embedded,
	}

	return results
}

func pageValue(rawValue string, defValue uint64) (val uint64) {
	if rawValue != "" {
		pval, err := strconv.ParseUint(rawValue, 10, 64)
		if err == nil {
			val = pval
		} else {
			val = defValue
		}
	} else {
		val = defValue
	}

	return val
}

func main() {

	maxProcs := runtime.NumCPU()
	runtime.GOMAXPROCS(maxProcs)

	var (
		es_host string
	)

	flag.StringVar(&es_host, "eshost", "localhost:9200", "HTTP host:port for ElasticSearch server")
	flag.Parse()

	es_host_and_port := strings.Split(es_host, ":")

	engine := goes.NewConnection(es_host_and_port[0], es_host_and_port[1])

	http.HandleFunc("/search", func(w http.ResponseWriter, r *http.Request) {

		q := r.URL.Query().Get("q")

		page := pageValue(r.URL.Query().Get("page"), 1)
		perPage := pageValue(r.URL.Query().Get("per_page"), 30)

		size := perPage
		from := perPage * (page - 1)

		query := map[string]interface{}{
			"query": map[string]interface{}{
				"filtered": map[string]interface{}{
					"query": map[string]interface{}{
						"query_string": map[string]interface{}{
							"query":            q,
							"default_operator": "AND",
						},
					},
					"filter": map[string]interface{}{
						"and": []interface{}{
							map[string]interface{}{
								"term": map[string]interface{}{
									"status": []string{"visible"},
								},
							},
						},
					},
				},
			},
			"size": size,
			"from": from,
		}

		extraArgs := make(url.Values, 1)
		searchResults, err := engine.Search(query, []string{"products"}, []string{"product"}, extraArgs)

		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		responseData := buildResults(searchResults, map[string]uint64{"page": page, "per_page": perPage})

		json_data, err := json.Marshal(responseData)

		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/json")
		w.Write(json_data)
	})

	log.Fatal(http.ListenAndServe(":3000", nil))
}
<commit_msg>Allow empty items array.<commit_after>package main

import (
	"encoding/json"
	"flag"
	"github.com/belogik/goes"
	"log"
	"net/http"
	"net/url"
	"runtime"
	"strconv"
	"strings"
)

type Item struct {
	Title string  `json:"title"`
	Price float64 `json:"price"`
}

type Results struct {
	TotalItems uint64                 `json:"total_items"`
	Page       uint64                 `json:"page"`
	PerPage    uint64                 `json:"per_page"`
	Embedded   map[string]interface{} `json:"_embedded"`
}

func buildResults(data *goes.Response, meta map[string]uint64) *Results {
	var items []*Item

	dataItems := data.Hits.Hits
	for _, it := range dataItems {
		source := it.Source
		title := source["title"].(string)
		price := source["price"].(float64)

		item := &Item{
			Title: title,
			Price: price,
		}

		items = append(items, item)
	}

	var embeddedItems interface{}

	if len(items) == 0 {
		embeddedItems = []string{}
	} else {
		embeddedItems = items
	}

	embedded := map[string]interface{}{
		"items": embeddedItems,
	}

	results := &Results{
		TotalItems: data.Hits.Total,
		Page:       meta["page"],
		PerPage:    meta["per_page"],
		Embedded:   embedded,
	}

	return results
}

func pageValue(rawValue string, defValue uint64) (val uint64) {
	if rawValue != "" {
		pval, err := strconv.ParseUint(rawValue, 10, 64)
		if err == nil {
			val = pval
		} else {
			val = defValue
		}
	} else {
		val = defValue
	}

	return val
}

func main() {

	maxProcs := runtime.NumCPU()
	runtime.GOMAXPROCS(maxProcs)

	var (
		es_host string
	)

	flag.StringVar(&es_host, "eshost", "localhost:9200", "HTTP host:port for ElasticSearch server")
	flag.Parse()

	es_host_and_port := strings.Split(es_host, ":")

	engine := goes.NewConnection(es_host_and_port[0], es_host_and_port[1])

	http.HandleFunc("/search", func(w http.ResponseWriter, r *http.Request) {

		q := r.URL.Query().Get("q")

		page := pageValue(r.URL.Query().Get("page"), 1)
		perPage := pageValue(r.URL.Query().Get("per_page"), 30)

		if perPage > 50 {
			perPage = 50
		}

		size := perPage
		from := perPage * (page - 1)

		query := map[string]interface{}{
			"query": map[string]interface{}{
				"filtered": map[string]interface{}{
					"query": map[string]interface{}{
						"query_string": map[string]interface{}{
							"query":            q,
							"default_operator": "AND",
						},
					},
					"filter": map[string]interface{}{
						"and": []interface{}{
							map[string]interface{}{
								"term": map[string]interface{}{
									"status": []string{"visible"},
								},
							},
						},
					},
				},
			},
			"size": size,
			"from": from,
		}

		extraArgs := make(url.Values, 1)
		searchResults, err := engine.Search(query, []string{"products"}, []string{"product"}, extraArgs)

		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		responseData := buildResults(searchResults, map[string]uint64{"page": page, "per_page": perPage})

		json_data, err := json.Marshal(responseData)

		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/json")
		w.Write(json_data)
	})

	log.Fatal(http.ListenAndServe(":3000", nil))
}
<|endoftext|>


<commit_before>package main

import (
	"encoding/json"
	"flag"
	"os"
	"time"

	WardenClient "github.com/cloudfoundry-incubator/garden/client"
	WardenConnection "github.com/cloudfoundry-incubator/garden/client/connection"
	"github.com/pivotal-golang/lager"
	"github.com/tedsuo/ifrit"
	"github.com/tedsuo/ifrit/grouper"
	"github.com/tedsuo/ifrit/http_server"
	"github.com/tedsuo/ifrit/sigmon"
	"github.com/tedsuo/rata"

	"github.com/concourse/turbine/api"
	"github.com/concourse/turbine/builder"
	"github.com/concourse/turbine/config"
	"github.com/concourse/turbine/resource"
	"github.com/concourse/turbine/routes"
	"github.com/concourse/turbine/scheduler"
	"github.com/concourse/turbine/snapshotter"
)

var listenAddr = flag.String(
	"listenAddr",
	"0.0.0.0:4637",
	"listening address",
)

var peerAddr = flag.String(
	"peerAddr",
	"127.0.0.1:4637",
	"external address of the api server, used for callbacks",
)

var wardenNetwork = flag.String(
	"wardenNetwork",
	"unix",
	"warden API connection network (unix or tcp)",
)

var wardenAddr = flag.String(
	"wardenAddr",
	"/tmp/warden.sock",
	"warden API connection address",
)

var resourceTypes = flag.String(
	"resourceTypes",
	`{
		"git": "docker:///concourse/git-resource",
		"raw": "docker:///concourse/raw-resource",
		"docker-image": "docker:///concourse/docker-image-resource",
		"time": "docker:///concourse/time-resource"
	}`,
	"map of resource type to its docker image",
)

var snapshotPath = flag.String(
	"snapshotPath",
	"/tmp/builds-snapshot.json",
	"path to file to store/load snapshots from",
)

func main() {
	flag.Parse()

	wardenClient := WardenClient.New(WardenConnection.New(
		*wardenNetwork,
		*wardenAddr,
	))

	logger := lager.NewLogger("turbine")
	logger.RegisterSink(lager.NewWriterSink(os.Stdout, lager.DEBUG))

	resourceTypesMap := map[string]string{}
	err := json.Unmarshal([]byte(*resourceTypes), &resourceTypesMap)
	if err != nil {
		logger.Fatal("failed-to-parse-resource-types", err)
	}

	var resourceTypesConfig config.ResourceTypes
	for typ, image := range resourceTypesMap {
		resourceTypesConfig = append(resourceTypesConfig, config.ResourceType{
			Name:  typ,
			Image: image,
		})
	}

	resourceTracker := resource.NewTracker(resourceTypesConfig, wardenClient)

	builder := builder.NewBuilder(resourceTracker, wardenClient)

	scheduler := scheduler.NewScheduler(logger.Session("scheduler"), builder)

	generator := rata.NewRequestGenerator("http://"+*peerAddr, routes.Routes)

	drain := make(chan struct{})

	handler, err := api.New(logger.Session("api"), scheduler, resourceTracker, generator, drain)
	if err != nil {
		logger.Fatal("failed-to-initialize-handler", err)
	}

	var pingErr error
	for i := 0; i < 10; i++ {
		pingErr = wardenClient.Ping()
		if pingErr == nil {
			break
		}

		time.Sleep(time.Second)
	}

	if pingErr != nil {
		logger.Fatal("failed-to-ping-warden", err)
	}

	group := grouper.EnvokeGroup(grouper.RunGroup{
		"api":         http_server.New(*listenAddr, handler),
		"snapshotter": snapshotter.NewSnapshotter(logger.Session("snapshotter"), *snapshotPath, scheduler),
		"drainer": ifrit.RunFunc(func(signals <-chan os.Signal, ready chan<- struct{}) error {
			close(ready)
			<-signals
			close(drain)
			return nil
		}),
	})

	running := ifrit.Envoke(sigmon.New(group))

	logger.Info("listening", lager.Data{
		"api": *listenAddr,
	})

	err = <-running.Wait()
	if err == nil {
		logger.Info("exited")
	} else {
		logger.Error("failed", err)
		os.Exit(1)
	}
}
<commit_msg>add tracker resource to supported list<commit_after>package main

import (
	"encoding/json"
	"flag"
	"os"
	"time"

	WardenClient "github.com/cloudfoundry-incubator/garden/client"
	WardenConnection "github.com/cloudfoundry-incubator/garden/client/connection"
	"github.com/pivotal-golang/lager"
	"github.com/tedsuo/ifrit"
	"github.com/tedsuo/ifrit/grouper"
	"github.com/tedsuo/ifrit/http_server"
	"github.com/tedsuo/ifrit/sigmon"
	"github.com/tedsuo/rata"

	"github.com/concourse/turbine/api"
	"github.com/concourse/turbine/builder"
	"github.com/concourse/turbine/config"
	"github.com/concourse/turbine/resource"
	"github.com/concourse/turbine/routes"
	"github.com/concourse/turbine/scheduler"
	"github.com/concourse/turbine/snapshotter"
)

var listenAddr = flag.String(
	"listenAddr",
	"0.0.0.0:4637",
	"listening address",
)

var peerAddr = flag.String(
	"peerAddr",
	"127.0.0.1:4637",
	"external address of the api server, used for callbacks",
)

var wardenNetwork = flag.String(
	"wardenNetwork",
	"unix",
	"warden API connection network (unix or tcp)",
)

var wardenAddr = flag.String(
	"wardenAddr",
	"/tmp/warden.sock",
	"warden API connection address",
)

var resourceTypes = flag.String(
	"resourceTypes",
	`{
		"git": "docker:///concourse/git-resource",
		"raw": "docker:///concourse/raw-resource",
		"docker-image": "docker:///concourse/docker-image-resource",
		"time": "docker:///concourse/time-resource",
		"tracker": "docker:///concourse/tracker-resource"
	}`,
	"map of resource type to its docker image",
)

var snapshotPath = flag.String(
	"snapshotPath",
	"/tmp/builds-snapshot.json",
	"path to file to store/load snapshots from",
)

func main() {
	flag.Parse()

	wardenClient := WardenClient.New(WardenConnection.New(
		*wardenNetwork,
		*wardenAddr,
	))

	logger := lager.NewLogger("turbine")
	logger.RegisterSink(lager.NewWriterSink(os.Stdout, lager.DEBUG))

	resourceTypesMap := map[string]string{}
	err := json.Unmarshal([]byte(*resourceTypes), &resourceTypesMap)
	if err != nil {
		logger.Fatal("failed-to-parse-resource-types", err)
	}

	var resourceTypesConfig config.ResourceTypes
	for typ, image := range resourceTypesMap {
		resourceTypesConfig = append(resourceTypesConfig, config.ResourceType{
			Name:  typ,
			Image: image,
		})
	}

	resourceTracker := resource.NewTracker(resourceTypesConfig, wardenClient)

	builder := builder.NewBuilder(resourceTracker, wardenClient)

	scheduler := scheduler.NewScheduler(logger.Session("scheduler"), builder)

	generator := rata.NewRequestGenerator("http://"+*peerAddr, routes.Routes)

	drain := make(chan struct{})

	handler, err := api.New(logger.Session("api"), scheduler, resourceTracker, generator, drain)
	if err != nil {
		logger.Fatal("failed-to-initialize-handler", err)
	}

	var pingErr error
	for i := 0; i < 10; i++ {
		pingErr = wardenClient.Ping()
		if pingErr == nil {
			break
		}

		time.Sleep(time.Second)
	}

	if pingErr != nil {
		logger.Fatal("failed-to-ping-warden", err)
	}

	group := grouper.EnvokeGroup(grouper.RunGroup{
		"api":         http_server.New(*listenAddr, handler),
		"snapshotter": snapshotter.NewSnapshotter(logger.Session("snapshotter"), *snapshotPath, scheduler),
		"drainer": ifrit.RunFunc(func(signals <-chan os.Signal, ready chan<- struct{}) error {
			close(ready)
			<-signals
			close(drain)
			return nil
		}),
	})

	running := ifrit.Envoke(sigmon.New(group))

	logger.Info("listening", lager.Data{
		"api": *listenAddr,
	})

	err = <-running.Wait()
	if err == nil {
		logger.Info("exited")
	} else {
		logger.Error("failed", err)
		os.Exit(1)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"fmt"
	"io/ioutil"

	yaml "gopkg.in/yaml.v2"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/cloudwatchevents"
)

func main() {
	var apply bool
	var dryrun bool
	var file string
	var awsRegion string

	flag.BoolVar(&apply, "apply", false, "apply to CloudWatch Events")
	flag.BoolVar(&dryrun, "dry-run", false, "dry-run")
	flag.StringVar(&file, "file", "config.yml", "file path to setting yaml")
	flag.StringVar(&file, "f", "config.yml", "file path to setting yaml (shorthand)")
	flag.StringVar(&awsRegion, "region", "", "aws region")
	flag.Parse()

	sess, errS := session.NewSession(
		&aws.Config{
			Region: aws.String(awsRegion),
		},
	)
	if errS != nil {
		fmt.Errorf("Session error %v", errS)
	}

	rules := Rules{}
	err := loadYaml(file, &rules)
	if err != nil {
		return err
	}
}

func loadYaml(file string, r *Rules) error {

	buf, err := ioutil.ReadFile(file)
	if err != nil {
		return err
	}

	err = yaml.Unmarshal(buf, &r)
	if err != nil {
		return err
	}

	return nil
}
<commit_msg>Put together var declarations<commit_after>package main

import (
	"flag"
	"fmt"
	"io/ioutil"

	yaml "gopkg.in/yaml.v2"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/cloudwatchevents"
)

func main() {
	var (
		apply, dryrun   bool
		file, awsRegion string
	)

	flag.BoolVar(&apply, "apply", false, "apply to CloudWatch Events")
	flag.BoolVar(&dryrun, "dry-run", false, "dry-run")
	flag.StringVar(&file, "file", "config.yml", "file path to setting yaml")
	flag.StringVar(&file, "f", "config.yml", "file path to setting yaml (shorthand)")
	flag.StringVar(&awsRegion, "region", "", "aws region")
	flag.Parse()

	sess, errS := session.NewSession(
		&aws.Config{
			Region: aws.String(awsRegion),
		},
	)
	if errS != nil {
		fmt.Errorf("Session error %v", errS)
	}

	rules := Rules{}
	err := loadYaml(file, &rules)
	if err != nil {
		return err
	}
}

func loadYaml(file string, r *Rules) error {

	buf, err := ioutil.ReadFile(file)
	if err != nil {
		return err
	}

	err = yaml.Unmarshal(buf, &r)
	if err != nil {
		return err
	}

	return nil
}
<|endoftext|>


<commit_before>package gorequest

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
)

type Options struct {
	Url    string
	Method string
	Body   string
	Json   string
	Header string
}

type Response *http.Response

type SuperAgent struct {
	Url       string
	Method    string
	Header    map[string]string
	Type      string
	Data      map[string]interface{}
	FormData  url.Values
	QueryData url.Values
}

func New() *SuperAgent {
	s := SuperAgent{
		Type:   "json",
		Data:   make(map[string]interface{}),
		Header: make(map[string]string)}
	return &s
}

func Get(targetUrl string) *SuperAgent {
	newReq := &SuperAgent{
		Url:       targetUrl,
		Method:    "GET",
		Header:    make(map[string]string),
		Data:      make(map[string]interface{}),
		FormData:  url.Values{},
		QueryData: url.Values{}}
	return newReq
}

func Post(targetUrl string) *SuperAgent {
	newReq := &SuperAgent{
		Url:       targetUrl,
		Method:    "POST",
		Type:      "json",
		Header:    make(map[string]string),
		Data:      make(map[string]interface{}),
		FormData:  url.Values{},
		QueryData: url.Values{}}
	return newReq
}

func (s *SuperAgent) Set(param string, value string) *SuperAgent {
	s.Header[param] = value
	return s
}

// TODO: check error
func (s *SuperAgent) Query(content string) *SuperAgent {
	var val map[string]string
	if err := json.Unmarshal([]byte(content), &val); err == nil {
		for k, v := range val {
			s.QueryData.Add(k, v)
		}
	} else {
		queryVal, _ := url.ParseQuery(content)
		for k, _ := range queryVal {
			s.QueryData.Add(k, queryVal.Get(k))
		}
		// TODO: need to check correct format of 'field=val&field=val&...'
	}
	return s
}

func (s *SuperAgent) Send(content string) *SuperAgent {
	var val map[string]interface{}
	// check if it is json format
	if err := json.Unmarshal([]byte(content), &val); err == nil {
		s.Type = "json"
		for k, v := range val {
			s.Data[k] = v
		}
	} else {
		// not json format (just normal string)
		s.Type = "form"
		formVal, _ := url.ParseQuery(content)
		for k, _ := range formVal {
			s.FormData.Add(k, formVal.Get(k))
		}
	}

	return s
}

func (s *SuperAgent) End(callback ...func(response *http.Response)) (*http.Response, error) {
	var (
		req  *http.Request
		err  error
		resp *http.Response
	)
	client := &http.Client{}
	if s.Method == "POST" {
		if s.Type == "json" {
			contentJson, _ := json.Marshal(s.Data)
			contentReader := bytes.NewReader(contentJson)
			req, err = http.NewRequest(s.Method, s.Url, contentReader)
			req.Header.Set("Content-Type", "application/json")
		} else if s.Type == "form" {
			req, err = http.NewRequest(s.Method, s.Url, strings.NewReader(s.FormData.Encode()))
			req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
		}
	} else if s.Method == "GET" {
		req, err = http.NewRequest(s.Method, s.Url, nil)
	}
	for k, v := range s.Header {
		req.Header.Set(k, v)
	}
	// Add all querystring from Query func
	q := req.URL.Query()
	for k, v := range s.QueryData {
		for _, vv := range v {
			q.Add(k, vv)
		}
	}
	req.URL.RawQuery = q.Encode()
	// Send request
	resp, err = client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	// deep copy response to give it to both return and callback func

	respCallback := *resp
	if len(callback) != 0 {
		callback[0](&respCallback)
	}
	return resp, nil
}

func main() {
	/*err, response, body:= Get("http://localhost:1337")
	  if err==nil && response.StatusCode == 200 {
	    fmt.Println(body)
	  }
	  fmt.Println(err, response, body)*/

	//s.post("/api/pet").send(`{"name":"tg"}`).end()
	Post("http://requestb.in/1f7ur5s1").
		Send(`nickname=a`).
		Set("Accept", "application/json").
		End(func(response *http.Response) {
		fmt.Println(response)
	})
	/*client:= &http.Client{}
	  req,_ := http.NewRequest("GET", "http://localhost:1337", nil)
	  req.Header.Add("Content-Type","application/json")
	  fmt.Println("main",req)
	  res, _ :=  client.Do(req)
	  fmt.Println(res.Body)
	  /*const jsonStream =`{"sn":"sn1"}`
	  reader:=strings.NewReader(jsonStream)
	  resp,_ := http.Post("http://localhost:1337", "application/json", reader)
	  defer resp.Body.Close()
	  body,_ :=ioutil.ReadAll(resp.Body)
	  fmt.Println(resp)
	  fmt.Println(string(body))*/
}
<commit_msg>If set to s.Type==form already, everything should be include in formData<commit_after>package gorequest

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
)

type Options struct {
	Url    string
	Method string
	Body   string
	Json   string
	Header string
}

type Response *http.Response

type SuperAgent struct {
	Url       string
	Method    string
	Header    map[string]string
	Type      string
	Data      map[string]interface{}
	FormData  url.Values
	QueryData url.Values
}

func New() *SuperAgent {
	s := SuperAgent{
		Type:   "json",
		Data:   make(map[string]interface{}),
		Header: make(map[string]string)}
	return &s
}

func Get(targetUrl string) *SuperAgent {
	newReq := &SuperAgent{
		Url:       targetUrl,
		Method:    "GET",
		Header:    make(map[string]string),
		Data:      make(map[string]interface{}),
		FormData:  url.Values{},
		QueryData: url.Values{}}
	return newReq
}

func Post(targetUrl string) *SuperAgent {
	newReq := &SuperAgent{
		Url:       targetUrl,
		Method:    "POST",
		Type:      "json",
		Header:    make(map[string]string),
		Data:      make(map[string]interface{}),
		FormData:  url.Values{},
		QueryData: url.Values{}}
	return newReq
}

func (s *SuperAgent) Set(param string, value string) *SuperAgent {
	s.Header[param] = value
	return s
}

// TODO: check error
func (s *SuperAgent) Query(content string) *SuperAgent {
	var val map[string]string
	if err := json.Unmarshal([]byte(content), &val); err == nil {
		for k, v := range val {
			s.QueryData.Add(k, v)
		}
	} else {
		queryVal, _ := url.ParseQuery(content)
		for k, _ := range queryVal {
			s.QueryData.Add(k, queryVal.Get(k))
		}
		// TODO: need to check correct format of 'field=val&field=val&...'
	}
	return s
}

func (s *SuperAgent) Send(content string) *SuperAgent {
	var val map[string]interface{}
	// check if it is json format
	if err := json.Unmarshal([]byte(content), &val); err == nil {
		if s.Type == "form" {
			for k, v := range val {
				// TODO: check if cannot convert to string, return error
				// Also, check that this is the right way to do. (Check superagent)
				s.FormData.Add(k, v.(string))
			}
		} else {
			s.Type = "json"
			for k, v := range val {
				s.Data[k] = v
			}
		}
	} else {
		// not json format (just normal string)
		s.Type = "form"
		formVal, _ := url.ParseQuery(content)
		for k, _ := range formVal {
			s.FormData.Add(k, formVal.Get(k))
		}
	}

	return s
}

func (s *SuperAgent) End(callback ...func(response *http.Response)) (*http.Response, error) {
	var (
		req  *http.Request
		err  error
		resp *http.Response
	)
	client := &http.Client{}
	if s.Method == "POST" {
		if s.Type == "json" {
			contentJson, _ := json.Marshal(s.Data)
			contentReader := bytes.NewReader(contentJson)
			req, err = http.NewRequest(s.Method, s.Url, contentReader)
			req.Header.Set("Content-Type", "application/json")
		} else if s.Type == "form" {
			req, err = http.NewRequest(s.Method, s.Url, strings.NewReader(s.FormData.Encode()))
			req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
		}
	} else if s.Method == "GET" {
		req, err = http.NewRequest(s.Method, s.Url, nil)
	}
	for k, v := range s.Header {
		req.Header.Set(k, v)
	}
	// Add all querystring from Query func
	q := req.URL.Query()
	for k, v := range s.QueryData {
		for _, vv := range v {
			q.Add(k, vv)
		}
	}
	req.URL.RawQuery = q.Encode()
	// Send request
	resp, err = client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	// deep copy response to give it to both return and callback func

	respCallback := *resp
	if len(callback) != 0 {
		callback[0](&respCallback)
	}
	return resp, nil
}

func main() {
	/*err, response, body:= Get("http://localhost:1337")
	  if err==nil && response.StatusCode == 200 {
	    fmt.Println(body)
	  }
	  fmt.Println(err, response, body)*/

	//s.post("/api/pet").send(`{"name":"tg"}`).end(
	Post("http://requestb.in/1f7ur5s1").
		Send(`nickname=a`).
		Set("Accept", "application/json").
		End(func(response *http.Response) {
		fmt.Println(response)
	})
	/*client:= &http.Client{}
	  req,_ := http.NewRequest("GET", "http://localhost:1337", nil)
	  req.Header.Add("Content-Type","application/json")
	  fmt.Println("main",req)
	  res, _ :=  client.Do(req)
	  fmt.Println(res.Body)
	  /*const jsonStream =`{"sn":"sn1"}`
	  reader:=strings.NewReader(jsonStream)
	  resp,_ := http.Post("http://localhost:1337", "application/json", reader)
	  defer resp.Body.Close()
	  body,_ :=ioutil.ReadAll(resp.Body)
	  fmt.Println(resp)
	  fmt.Println(string(body))*/
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"github.com/jolshevski/chester/api"
)

func main() {
	app := api.New()

	// Define configuration flags
	modulepath := flag.String("modulepath", "", "Directory containing module release tarballs to serve. Required.")
	binding := flag.String("binding", ":8080", "Golang ListenAndServe binding")
	fileurl := flag.String("fileurl", "/v3/files", "URL to the base of the URL which the module tarballs are being served from")
	flag.Parse()

	// Configure the API
	app.Config["modulepath"] = *modulepath
	app.Config["binding"] = *binding
	app.Config["fileurl"] = *fileurl

	// Start the API server
	app.Listen()
}
<commit_msg>Make fileurl flag required<commit_after>package main

import (
	"flag"
	"github.com/jolshevski/chester/api"
)

func main() {
	app := api.New()

	// Define configuration flags
	modulepath := flag.String("modulepath", "", "Directory containing module release tarballs to serve. Required.")
	binding := flag.String("binding", ":8080", "Golang ListenAndServe binding")
	fileurl := flag.String("fileurl", "", "URL to the base of the URL which the module tarballs are being served from")
	flag.Parse()

	// Configure the API
	app.Config["modulepath"] = *modulepath
	app.Config["binding"] = *binding
	app.Config["fileurl"] = *fileurl

	// Start the API server
	app.Listen()
}
<|endoftext|>


<commit_before>package main

import (
	"errors"
	"encoding/json"
	"encoding/base64"
	"fmt"
	"flag"
	"gopkg.in/gomail.v1"
	"github.com/mpdroog/beanstalkd" //"github.com/maxid/beanstalkd"
	"smtpw/config"
	"time"
	"strings"
)

const ERR_WAIT_SEC = 5
var verbose bool
var readonly bool

func proc(m config.Email) error {
	conf, ok := config.C.From[m.From]
	if !ok {
		return errors.New("From does not exist: " + m.From)
	}

	msg := gomail.NewMessage()
	msg.SetHeader("From", conf.Display + " <" + conf.From + ">")
	msg.SetHeader("To", m.To...)
	msg.SetHeader("Bcc", conf.Bcc...)
	msg.SetHeader("Subject", m.Subject)
	msg.SetBody("text/plain", m.Text)
	msg.SetBody("text/html", m.Html)

	for name, embed := range m.HtmlEmbed {
		raw, e := base64.StdEncoding.DecodeString(embed)
		if e != nil {
			return errors.New("HtmlEmbed: " + name + " is not base64!")
		}
		if !strings.Contains(m.Html, fmt.Sprintf("cid:" + name)) {
			return errors.New("HtmlEmbed: " + name + " is not used in the HTML!")
		}
		msg.Embed(gomail.CreateFile(name, raw))
	}

	if readonly {
		fmt.Println("From: " + conf.Display + " <" + conf.From + ">")
		fmt.Println(fmt.Sprintf("To: %v", m.To))
		fmt.Println(fmt.Sprintf("Bcc: %v", conf.Bcc))
		fmt.Println("Subject: " + m.Subject)
		fmt.Println("\ntext/plain")
		fmt.Println(m.Text)
		fmt.Println("\ntext/html")
		fmt.Println(m.Html)
		fmt.Println("\n")
		return nil
	}

	mailer := gomail.NewMailer(conf.Host, conf.User, conf.Pass, conf.Port)
	return mailer.Send(msg)
}

func main() {
	var (
		configPath string
		skipOne bool
	)
	flag.BoolVar(&verbose, "v", false, "Verbose-mode")
	flag.BoolVar(&skipOne, "s", false, "Delete e-mail on deverr")
	flag.BoolVar(&readonly, "r", false, "Don't email but flush to stdout")
	flag.StringVar(&configPath, "c", "./config.json", "Path to config.json")
	flag.Parse()

	if e := config.Init(configPath); e != nil {
		panic(e)
	}
	// TODO: Test config before starting?

	queue, e := beanstalkd.Dial(config.C.Beanstalk)
	if e != nil {
		panic(e)
	}
	// Only listen to email queue.
	queue.Use("email")
	if _, e := queue.Watch("email"); e != nil {
		panic(e)
	}
	queue.Ignore("default")

	if verbose {
		fmt.Println("SMTPw listening on email tube (ignoring default)")
	}
	if readonly {
		fmt.Println("!! ReadOnly mode !!")
	}
	for {
		job, e := queue.Reserve(0)
		if e != nil {
			fmt.Println("Beanstalkd err: " + e.Error())
			time.Sleep(time.Second * ERR_WAIT_SEC)
			continue
		}
		if verbose {
			fmt.Println(fmt.Sprintf("Parse job %d", job.Id))
			fmt.Println("JSON:\r\n" + string(job.Data))
		}
		// Parse
		var m config.Email
		if e := json.Unmarshal(job.Data, &m); e != nil {
			// Broken JSON
			if skipOne {
				fmt.Println("WARN: Skip job as JSON is invalid")
				queue.Delete(job.Id)
				skipOne = false
				continue
			}

			// Ignore decode trouble
			fmt.Println("CRIT: Invalid JSON received (msg=" + e.Error() + ")")
			continue
		}

		if e := proc(m); e != nil {
			// TODO: Isolate deverr from senderr
			// Processing trouble?
			fmt.Println("WARN: Failed sending, retry in 20sec (msg=" + e.Error() + ")")
			continue
		}
		queue.Delete(job.Id)
		if verbose {
			fmt.Println(fmt.Sprintf("Finished job %d", job.Id))
		}
	}
	queue.Quit()
}
<commit_msg>Bugfix. Text wasn't shown in old clients<commit_after>package main

import (
	"errors"
	"encoding/json"
	"encoding/base64"
	"fmt"
	"flag"
	"gopkg.in/gomail.v1"
	"github.com/mpdroog/beanstalkd" //"github.com/maxid/beanstalkd"
	"smtpw/config"
	"time"
	"strings"
)

const ERR_WAIT_SEC = 5
var verbose bool
var readonly bool

func proc(m config.Email) error {
	conf, ok := config.C.From[m.From]
	if !ok {
		return errors.New("From does not exist: " + m.From)
	}

	msg := gomail.NewMessage()
	msg.SetHeader("From", conf.Display + " <" + conf.From + ">")
	msg.SetHeader("To", m.To...)
	msg.SetHeader("Bcc", conf.Bcc...)
	msg.SetHeader("Subject", m.Subject)
	msg.SetBody("text/plain", m.Text)
	msg.AddAlternative("text/html", m.Html)

	for name, embed := range m.HtmlEmbed {
		raw, e := base64.StdEncoding.DecodeString(embed)
		if e != nil {
			return errors.New("HtmlEmbed: " + name + " is not base64!")
		}
		if !strings.Contains(m.Html, fmt.Sprintf("cid:" + name)) {
			return errors.New("HtmlEmbed: " + name + " is not used in the HTML!")
		}
		msg.Embed(gomail.CreateFile(name, raw))
	}

	if readonly {
		fmt.Println("From: " + conf.Display + " <" + conf.From + ">")
		fmt.Println(fmt.Sprintf("To: %v", m.To))
		fmt.Println(fmt.Sprintf("Bcc: %v", conf.Bcc))
		fmt.Println("Subject: " + m.Subject)
		fmt.Println("\ntext/plain")
		fmt.Println(m.Text)
		fmt.Println("\ntext/html")
		fmt.Println(m.Html)
		fmt.Println("\n")
		return nil
	}

	mailer := gomail.NewMailer(conf.Host, conf.User, conf.Pass, conf.Port)
	return mailer.Send(msg)
}

func main() {
	var (
		configPath string
		skipOne bool
	)
	flag.BoolVar(&verbose, "v", false, "Verbose-mode")
	flag.BoolVar(&skipOne, "s", false, "Delete e-mail on deverr")
	flag.BoolVar(&readonly, "r", false, "Don't email but flush to stdout")
	flag.StringVar(&configPath, "c", "./config.json", "Path to config.json")
	flag.Parse()

	if e := config.Init(configPath); e != nil {
		panic(e)
	}
	// TODO: Test config before starting?

	queue, e := beanstalkd.Dial(config.C.Beanstalk)
	if e != nil {
		panic(e)
	}
	// Only listen to email queue.
	queue.Use("email")
	if _, e := queue.Watch("email"); e != nil {
		panic(e)
	}
	queue.Ignore("default")

	if verbose {
		fmt.Println("SMTPw listening on email tube (ignoring default)")
	}
	if readonly {
		fmt.Println("!! ReadOnly mode !!")
	}
	for {
		job, e := queue.Reserve(0)
		if e != nil {
			fmt.Println("Beanstalkd err: " + e.Error())
			time.Sleep(time.Second * ERR_WAIT_SEC)
			continue
		}
		if verbose {
			fmt.Println(fmt.Sprintf("Parse job %d", job.Id))
			fmt.Println("JSON:\r\n" + string(job.Data))
		}
		// Parse
		var m config.Email
		if e := json.Unmarshal(job.Data, &m); e != nil {
			// Broken JSON
			if skipOne {
				fmt.Println("WARN: Skip job as JSON is invalid")
				queue.Delete(job.Id)
				skipOne = false
				continue
			}

			// Ignore decode trouble
			fmt.Println("CRIT: Invalid JSON received (msg=" + e.Error() + ")")
			continue
		}

		if e := proc(m); e != nil {
			// TODO: Isolate deverr from senderr
			// Processing trouble?
			fmt.Println("WARN: Failed sending, retry in 20sec (msg=" + e.Error() + ")")
			continue
		}
		queue.Delete(job.Id)
		if verbose {
			fmt.Println(fmt.Sprintf("Finished job %d", job.Id))
		}
	}
	queue.Quit()
}
<|endoftext|>


<commit_before>package main

import (
	"os"
	"fmt"
	flag "github.com/ogier/pflag"
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/ec2"
	"github.com/mitchellh/go-homedir"
	"strings"
	"reflect"
)

var defaultAttributes = [...]string{
	"InstanceId",
	"Name",
	"InstanceType",
	"AvailabilityZone",
	"State",
	"PrivateIpAddress",
	"PublicIpAddress",
}

func name(i *ec2.Instance) string {
	tags := i.Tags
	for _, tag := range tags {
		if "Name" == *tag.Key {
			return *tag.Value
		}
	}
	return ""
}

func state(i *ec2.Instance) string {
	return *i.State.Name
}

func availabilityZone(i *ec2.Instance) string {
	return *i.Placement.AvailabilityZone
}

var getter = map[string](func(*ec2.Instance)string){
	"Name":  name,
	"State":  state,
	"AvailabilityZone":  availabilityZone,
}

func main() {
	config := aws.Config{}
	profileName := flag.StringP("profile", "p", "", "AWS profile")
	flag.Parse()

	if len(*profileName) > 0 {
		profileFilepath, err := homedir.Expand("~/.aws/credentials")
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
		fmt.Println("Using profile:", *profileName)
		creds := credentials.NewSharedCredentials(profileFilepath, *profileName)
		config.Credentials = creds
	}

	// Create an EC2 service object in the "us-west-2" region
	// Note that you can also configure your region globally by
	// exporting the AWS_REGION environment variable
	svc := ec2.New(session.New(), &config)

	// Call the DescribeInstances Operation
	resp, err := svc.DescribeInstances(nil)
	if err != nil {
		panic(err)
	}

	// resp has all of the response data, pull out instance IDs:
	for idx := range resp.Reservations {
		for _, inst := range resp.Reservations[idx].Instances {
			attrs := make([]string, 0, 10)
			for _, attr := range defaultAttributes {
				v := ""
				f, ok := getter[attr]
				if ok {
					v = f(inst)
				} else {
					field := reflect.ValueOf(*inst).FieldByName(attr)
					if !field.IsNil() {
						v = fmt.Sprintf("%v", field.Elem().Interface())
					}
				}
				attrs = append(attrs, v)
			}
			fmt.Println(strings.Join(attrs, "\t"))
		}
	}
}

<commit_msg>Implemented sts assume role<commit_after>package main

import (
	"fmt"
	"strings"
	"reflect"
	flag "github.com/ogier/pflag"
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/ec2"
	"github.com/aws/aws-sdk-go/service/sts"
	"github.com/mitchellh/go-homedir"
	"github.com/vaughan0/go-ini"
)

var defaultAttributes = [...]string{
	"InstanceId",
	"Name",
	"InstanceType",
	"AvailabilityZone",
	"State",
	"PrivateIpAddress",
	"PublicIpAddress",
}

func name(i *ec2.Instance) string {
	tags := i.Tags
	for _, tag := range tags {
		if "Name" == *tag.Key {
			return *tag.Value
		}
	}
	return ""
}

func state(i *ec2.Instance) string {
	return *i.State.Name
}

func availabilityZone(i *ec2.Instance) string {
	return *i.Placement.AvailabilityZone
}

var getter = map[string](func(*ec2.Instance)string){
	"Name":  name,
	"State":  state,
	"AvailabilityZone":  availabilityZone,
}

func createCredentials(profileName *string) *credentials.Credentials {
	fmt.Println("Using profile:", *profileName)
	profileFilepath, err := homedir.Expand("~/.aws/credentials")
	if err != nil {
		panic(err)
	}

	file, err := ini.LoadFile(profileFilepath)
	if err != nil {
		panic(err)
	}

	sourceProfile, ok := file.Get(*profileName, "source_profile")
	if ok {
		// Using AssumeRole
		roleArn, _ := file.Get(*profileName, "role_arn")
		roleSessionName := "ec2ls"
		creds := credentials.NewSharedCredentials(profileFilepath, sourceProfile)
		svc := sts.New(session.New(), &aws.Config{Credentials: creds})
		result, err := svc.AssumeRole(&sts.AssumeRoleInput{
			RoleArn: &roleArn,
			RoleSessionName: &roleSessionName,
		})
		if err != nil {
			panic(err)
		}

		tmpCreds := result.Credentials
		return credentials.NewStaticCredentials(
			*tmpCreds.AccessKeyId,
			*tmpCreds.SecretAccessKey,
			*tmpCreds.SessionToken)
	}
	return credentials.NewSharedCredentials(profileFilepath, *profileName)
}

func main() {
	config := aws.Config{}
	profileName := flag.StringP("profile", "p", "", "AWS profile")
	flag.Parse()

	if len(*profileName) > 0 {
		config.Credentials = createCredentials(profileName)
	}

	// Create an EC2 service object in the "us-west-2" region
	// Note that you can also configure your region globally by
	// exporting the AWS_REGION environment variable
	svc := ec2.New(session.New(), &config)

	// Call the DescribeInstances Operation
	resp, err := svc.DescribeInstances(nil)
	if err != nil {
		panic(err)
	}

	// resp has all of the response data, pull out instance IDs:
	for idx := range resp.Reservations {
		for _, inst := range resp.Reservations[idx].Instances {
			attrs := make([]string, 0, 10)
			for _, attr := range defaultAttributes {
				v := ""
				f, ok := getter[attr]
				if ok {
					v = f(inst)
				} else {
					field := reflect.ValueOf(*inst).FieldByName(attr)
					if !field.IsNil() {
						v = fmt.Sprintf("%v", field.Elem().Interface())
					}
				}
				attrs = append(attrs, v)
			}
			fmt.Println(strings.Join(attrs, "\t"))
		}
	}
}

<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"log"
	"net/http"
	"strings"
	"time"

	"github.com/MyHomeworkSpace/api-server/schools"

	"github.com/MyHomeworkSpace/api-server/schools/dalton"

	"github.com/MyHomeworkSpace/api-server/api"
	"github.com/MyHomeworkSpace/api-server/auth"
	"github.com/MyHomeworkSpace/api-server/calendar"
	"github.com/MyHomeworkSpace/api-server/config"
	"github.com/MyHomeworkSpace/api-server/data"
	"github.com/MyHomeworkSpace/api-server/email"

	"github.com/labstack/echo"
	"github.com/labstack/echo/middleware"
)

type ErrorResponse struct {
	Status string `json:"status"`
	Error  string `json:"error"`
}

type CSRFResponse struct {
	Status string `json:"status"`
	Token  string `json:"token"`
}

type HelloResponse struct {
	Server string `json:"server"`
	Commit string `json:"builtFrom"`
}

func main() {
	log.Println("MyHomeworkSpace API Server")

	config.Init()

	InitDatabase()
	InitRedis()

	email.Init()

	calendar.InitCalendar()

	api.DB = DB
	api.RedisClient = RedisClient

	auth.DB = DB
	auth.RedisClient = RedisClient

	data.DB = DB

	schools.MainRegistry.Register(dalton.CreateSchool())

	e := echo.New()
	e.Pre(middleware.RemoveTrailingSlash())
	e.Pre(func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) error {
			if c.Request().Method == "OPTIONS" {
				c.Response().Header().Set("Access-Control-Allow-Credentials", "false")
				c.Response().Header().Set("Access-Control-Allow-Origin", "*")
				c.Response().Header().Set("Access-Control-Allow-Headers", "authorization")
				c.Response().Writer.WriteHeader(http.StatusOK)
				return nil
			}

			if config.GetCurrent().CORS.Enabled && len(config.GetCurrent().CORS.Origins) > 0 {
				foundOrigin := ""
				for _, origin := range config.GetCurrent().CORS.Origins {
					if origin == c.Request().Header.Get("Origin") {
						foundOrigin = origin
					}
				}

				if foundOrigin == "" {
					foundOrigin = config.GetCurrent().CORS.Origins[0]
				}

				c.Response().Header().Set("Access-Control-Allow-Origin", foundOrigin)
				c.Response().Header().Set("Access-Control-Allow-Credentials", "true")
			}
			if strings.HasPrefix(c.Request().URL.Path, "/api_tester") {
				return next(c)
			}
			if strings.HasPrefix(c.Request().URL.Path, "/application/requestAuth") {
				return next(c)
			}
			_, err := c.Cookie("session")
			if err != nil {
				// user has no cookie, generate one
				cookie := new(http.Cookie)
				cookie.Name = "session"
				cookie.Path = "/"
				uid, err := auth.GenerateUID()
				if err != nil {
					return err
				}
				cookie.Value = uid
				cookie.Expires = time.Now().Add(7 * 24 * time.Hour)
				c.SetCookie(cookie)
			}

			// check if they have an authorization header
			if c.Request().Header.Get("Authorization") != "" {
				// get the token
				headerParts := strings.Split(c.Request().Header.Get("Authorization"), " ")
				if len(headerParts) == 2 {
					authToken := headerParts[1]

					// look up token
					rows, err := DB.Query("SELECT applications.cors FROM application_authorizations INNER JOIN applications ON application_authorizations.applicationId = applications.id WHERE application_authorizations.token = ?", authToken)
					if err == nil {
						// IMPORTANT: if there's an error with the token, we just continue with the request
						// this is for backwards compatibility with old versions, where the token would always bypass csrf and only be checked when authentication was needed
						// this is ok because if someone is able to add a new header, it should not be in a scenario where csrf would be a useful defense
						// TODO: it would be much cleaner to just fail here if the token is bad. do any applications actually rely on this behavior?

						defer rows.Close()
						if rows.Next() {
							cors := ""
							err = rows.Scan(&cors)

							if err == nil && cors != "" {
								c.Response().Header().Set("Access-Control-Allow-Origin", cors)
								c.Response().Header().Set("Access-Control-Allow-Headers", "authorization")
							}
						}
					}
				}

				// also bypass csrf
				return next(c)
			}

			// bypass csrf for special internal api (this requires the ip to be localhost so it's still secure)
			if strings.HasPrefix(c.Request().URL.Path, "/schedule/internal") {
				return next(c)
			}

			csrfCookie, err := c.Cookie("csrfToken")
			csrfToken := ""
			hasNoToken := false
			if err != nil {
				// user has no cookie, generate one
				cookie := new(http.Cookie)
				cookie.Name = "csrfToken"
				cookie.Path = "/"
				uid, err := auth.GenerateRandomString(40)
				if err != nil {
					return err
				}
				cookie.Value = uid
				cookie.Expires = time.Now().Add(12 * 4 * 7 * 24 * time.Hour)
				c.SetCookie(cookie)

				hasNoToken = true
				csrfToken = cookie.Value

				// let the next if block handle this
			} else {
				csrfToken = csrfCookie.Value
			}

			// bypass csrf token for /auth/csrf
			if strings.HasPrefix(c.Request().URL.Path, "/auth/csrf") {
				// did we just make up a token?
				if hasNoToken {
					// if so, return it
					// auth.go won't know the new token yet
					return c.JSON(http.StatusOK, CSRFResponse{"ok", csrfToken})
				} else {
					return next(c)
				}
			}

			if csrfToken != c.QueryParam("csrfToken") || hasNoToken {
				return c.JSON(http.StatusBadRequest, ErrorResponse{"error", "csrfToken_invalid"})
			}

			return next(c)
		}
	})
	e.Static("/api_tester", "api_tester")
	e.GET("/", func(c echo.Context) error {
		return c.String(http.StatusOK, "MyHomeworkSpace API Server")
	})

	api.Init(e) // API init delayed because router must be started first

	log.Printf("Listening on port %d", config.GetCurrent().Server.Port)
	e.Start(fmt.Sprintf(":%d", config.GetCurrent().Server.Port))
}
<commit_msg>report errors with starting web server<commit_after>package main

import (
	"fmt"
	"log"
	"net/http"
	"strings"
	"time"

	"github.com/MyHomeworkSpace/api-server/schools"

	"github.com/MyHomeworkSpace/api-server/schools/dalton"

	"github.com/MyHomeworkSpace/api-server/api"
	"github.com/MyHomeworkSpace/api-server/auth"
	"github.com/MyHomeworkSpace/api-server/calendar"
	"github.com/MyHomeworkSpace/api-server/config"
	"github.com/MyHomeworkSpace/api-server/data"
	"github.com/MyHomeworkSpace/api-server/email"

	"github.com/labstack/echo"
	"github.com/labstack/echo/middleware"
)

type ErrorResponse struct {
	Status string `json:"status"`
	Error  string `json:"error"`
}

type CSRFResponse struct {
	Status string `json:"status"`
	Token  string `json:"token"`
}

type HelloResponse struct {
	Server string `json:"server"`
	Commit string `json:"builtFrom"`
}

func main() {
	log.Println("MyHomeworkSpace API Server")

	config.Init()

	InitDatabase()
	InitRedis()

	email.Init()

	calendar.InitCalendar()

	api.DB = DB
	api.RedisClient = RedisClient

	auth.DB = DB
	auth.RedisClient = RedisClient

	data.DB = DB

	schools.MainRegistry.Register(dalton.CreateSchool())

	e := echo.New()
	e.Pre(middleware.RemoveTrailingSlash())
	e.Pre(func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) error {
			if c.Request().Method == "OPTIONS" {
				c.Response().Header().Set("Access-Control-Allow-Credentials", "false")
				c.Response().Header().Set("Access-Control-Allow-Origin", "*")
				c.Response().Header().Set("Access-Control-Allow-Headers", "authorization")
				c.Response().Writer.WriteHeader(http.StatusOK)
				return nil
			}

			if config.GetCurrent().CORS.Enabled && len(config.GetCurrent().CORS.Origins) > 0 {
				foundOrigin := ""
				for _, origin := range config.GetCurrent().CORS.Origins {
					if origin == c.Request().Header.Get("Origin") {
						foundOrigin = origin
					}
				}

				if foundOrigin == "" {
					foundOrigin = config.GetCurrent().CORS.Origins[0]
				}

				c.Response().Header().Set("Access-Control-Allow-Origin", foundOrigin)
				c.Response().Header().Set("Access-Control-Allow-Credentials", "true")
			}
			if strings.HasPrefix(c.Request().URL.Path, "/api_tester") {
				return next(c)
			}
			if strings.HasPrefix(c.Request().URL.Path, "/application/requestAuth") {
				return next(c)
			}
			_, err := c.Cookie("session")
			if err != nil {
				// user has no cookie, generate one
				cookie := new(http.Cookie)
				cookie.Name = "session"
				cookie.Path = "/"
				uid, err := auth.GenerateUID()
				if err != nil {
					return err
				}
				cookie.Value = uid
				cookie.Expires = time.Now().Add(7 * 24 * time.Hour)
				c.SetCookie(cookie)
			}

			// check if they have an authorization header
			if c.Request().Header.Get("Authorization") != "" {
				// get the token
				headerParts := strings.Split(c.Request().Header.Get("Authorization"), " ")
				if len(headerParts) == 2 {
					authToken := headerParts[1]

					// look up token
					rows, err := DB.Query("SELECT applications.cors FROM application_authorizations INNER JOIN applications ON application_authorizations.applicationId = applications.id WHERE application_authorizations.token = ?", authToken)
					if err == nil {
						// IMPORTANT: if there's an error with the token, we just continue with the request
						// this is for backwards compatibility with old versions, where the token would always bypass csrf and only be checked when authentication was needed
						// this is ok because if someone is able to add a new header, it should not be in a scenario where csrf would be a useful defense
						// TODO: it would be much cleaner to just fail here if the token is bad. do any applications actually rely on this behavior?

						defer rows.Close()
						if rows.Next() {
							cors := ""
							err = rows.Scan(&cors)

							if err == nil && cors != "" {
								c.Response().Header().Set("Access-Control-Allow-Origin", cors)
								c.Response().Header().Set("Access-Control-Allow-Headers", "authorization")
							}
						}
					}
				}

				// also bypass csrf
				return next(c)
			}

			// bypass csrf for special internal api (this requires the ip to be localhost so it's still secure)
			if strings.HasPrefix(c.Request().URL.Path, "/schedule/internal") {
				return next(c)
			}

			csrfCookie, err := c.Cookie("csrfToken")
			csrfToken := ""
			hasNoToken := false
			if err != nil {
				// user has no cookie, generate one
				cookie := new(http.Cookie)
				cookie.Name = "csrfToken"
				cookie.Path = "/"
				uid, err := auth.GenerateRandomString(40)
				if err != nil {
					return err
				}
				cookie.Value = uid
				cookie.Expires = time.Now().Add(12 * 4 * 7 * 24 * time.Hour)
				c.SetCookie(cookie)

				hasNoToken = true
				csrfToken = cookie.Value

				// let the next if block handle this
			} else {
				csrfToken = csrfCookie.Value
			}

			// bypass csrf token for /auth/csrf
			if strings.HasPrefix(c.Request().URL.Path, "/auth/csrf") {
				// did we just make up a token?
				if hasNoToken {
					// if so, return it
					// auth.go won't know the new token yet
					return c.JSON(http.StatusOK, CSRFResponse{"ok", csrfToken})
				} else {
					return next(c)
				}
			}

			if csrfToken != c.QueryParam("csrfToken") || hasNoToken {
				return c.JSON(http.StatusBadRequest, ErrorResponse{"error", "csrfToken_invalid"})
			}

			return next(c)
		}
	})
	e.Static("/api_tester", "api_tester")
	e.GET("/", func(c echo.Context) error {
		return c.String(http.StatusOK, "MyHomeworkSpace API Server")
	})

	api.Init(e) // API init delayed because router must be started first

	log.Printf("Listening on port %d", config.GetCurrent().Server.Port)
	err := e.Start(fmt.Sprintf(":%d", config.GetCurrent().Server.Port))
	if err != nil {
		log.Fatalln(err)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"fmt"
	"net/http"
	"os"
	"regexp"
	"text/tabwriter"
)

func GetUrl(url_no string) (replace_string string) {
	url := fmt.Sprintf("http://hichannel.hinet.net/radio/mobile/index.do?id=%s", url_no)
	//resp, _ := http.Get("http://hichannel.hinet.net/radio/mobile/index.do?id=232")
	//resp, _ := http.Get("http://hichannel.hinet.net/radio/mobile/index.do?id=207")
	resp, _ := http.Get(url)
	defer resp.Body.Close()
	html := new(bytes.Buffer)
	html.ReadFrom(resp.Body)
	//fmt.Println(html.String())
	reg := regexp.MustCompile(`var url = '([\S]+)'`)
	url_string := reg.FindAllStringSubmatch(html.String(), -1)
	//fmt.Println(url_string[0][1])

	replace := regexp.MustCompile(`\\\/`)
	replace_string = replace.ReplaceAllString(url_string[0][1], `/`)
	//fmt.Println(replace_string)
	return
}

func GetList() {
	resp, _ := http.Get("http://hichannel.hinet.net/radio/mobile/index.do?id=207")
	defer resp.Body.Close()
	html := new(bytes.Buffer)
	html.ReadFrom(resp.Body)
	reg := regexp.MustCompile(`<div class="stationName">(.+)</div>[\s]+<div class="list"><a href="#" onclick="getInfo\('list','([\d]+)'\);return false;"></a></div>`)
	url_string := reg.FindAllStringSubmatch(html.String(), -1)
	url_string = append(url_string, []string{"", "中廣新聞網", "207"})
	//fmt.Println(url_string)
	w := new(tabwriter.Writer)
	w.Init(os.Stdout, 0, 8, 0, '\t', 0)
	var output string
	for no, data := range url_string {
		if (no+1)%3 == 0 {
			output += fmt.Sprintf("%d. [%s] %s\t", no+1, data[2], data[1])
			fmt.Fprintln(w, output)
			output = ""
		} else {
			output += fmt.Sprintf("%d. [%s] %s\t", no+1, data[2], data[1])
		}
	}
	w.Flush()
}

func PrintChannel() {
	fmt.Println("[207] 中廣新聞網")
	fmt.Println("[205] 中廣流行網 i like")
	fmt.Println("[206] 中廣音樂網i radio")
	fmt.Println("[232] 飛碟電台")
	fmt.Println("[222] HitFm聯播網 Taipei 北部")
	fmt.Println("[156] KISS RADIO 大眾廣播電台")
	fmt.Println("[308] KISS RADIO 網路音樂台")
	fmt.Println("[187] NEWS98新聞網")
	fmt.Println("[370] POP Radio 台北流行廣播電台")
}

func main() {
	//fmt.Println("----- test open -----\r\n")
	//exec.Command("open", "-a", "firefox").Run()

	//fmt.Println(GetUrl("207"))

	//PrintChannel()

	//in := bufio.NewReader(os.Stdin)
	//std_string, _ := in.ReadString('\n')
	//fmt.Println(GetUrl(strings.Split(std_string, "\n")[0]))

	GetList()
}
<commit_msg>Add stdin.<commit_after>package main

import (
	"bufio"
	"bytes"
	"fmt"
	"net/http"
	"os"
	"regexp"
	"strings"
	"text/tabwriter"
)

func GetUrl(url_no string) (replace_string string) {
	url := fmt.Sprintf("http://hichannel.hinet.net/radio/mobile/index.do?id=%s", url_no)
	//resp, _ := http.Get("http://hichannel.hinet.net/radio/mobile/index.do?id=232")
	//resp, _ := http.Get("http://hichannel.hinet.net/radio/mobile/index.do?id=207")
	resp, _ := http.Get(url)
	defer resp.Body.Close()
	html := new(bytes.Buffer)
	html.ReadFrom(resp.Body)
	//fmt.Println(html.String())
	reg := regexp.MustCompile(`var url = '([\S]+)'`)
	url_string := reg.FindAllStringSubmatch(html.String(), -1)
	//fmt.Println(url_string[0][1])

	replace := regexp.MustCompile(`\\\/`)
	replace_string = replace.ReplaceAllString(url_string[0][1], `/`)
	//fmt.Println(replace_string)
	return
}

func GetList() {
	resp, _ := http.Get("http://hichannel.hinet.net/radio/mobile/index.do?id=207")
	defer resp.Body.Close()
	html := new(bytes.Buffer)
	html.ReadFrom(resp.Body)
	reg := regexp.MustCompile(`<div class="stationName">(.+)</div>[\s]+<div class="list"><a href="#" onclick="getInfo\('list','([\d]+)'\);return false;"></a></div>`)
	url_string := reg.FindAllStringSubmatch(html.String(), -1)
	url_string = append(url_string, []string{"", "中廣新聞網", "207"})
	//fmt.Println(url_string)
	w := new(tabwriter.Writer)
	w.Init(os.Stdout, 0, 8, 0, '\t', 0)
	var output string
	for no, data := range url_string {
		if (no+1)%3 == 0 {
			output += fmt.Sprintf("%d. [%s] %s\t", no+1, data[2], data[1])
			fmt.Fprintln(w, output)
			output = ""
		} else {
			output += fmt.Sprintf("%d. [%s] %s\t", no+1, data[2], data[1])
		}
	}
	fmt.Fprintln(w, output)
	w.Flush()
}

func PrintChannel() {
	fmt.Println("[207] 中廣新聞網")
	fmt.Println("[205] 中廣流行網 i like")
	fmt.Println("[206] 中廣音樂網i radio")
	fmt.Println("[232] 飛碟電台")
	fmt.Println("[222] HitFm聯播網 Taipei 北部")
	fmt.Println("[156] KISS RADIO 大眾廣播電台")
	fmt.Println("[308] KISS RADIO 網路音樂台")
	fmt.Println("[187] NEWS98新聞網")
	fmt.Println("[370] POP Radio 台北流行廣播電台")
}

func main() {
	//fmt.Println("----- test open -----\r\n")
	//exec.Command("open", "-a", "firefox").Run()

	//fmt.Println(GetUrl("207"))

	//PrintChannel()
	GetList()

	in := bufio.NewReader(os.Stdin)
	std_string, _ := in.ReadString('\n')
	fmt.Println(GetUrl(strings.Split(std_string, "\n")[0]))
}
<|endoftext|>


<commit_before>package main

import (
	"os"

	log "github.com/Sirupsen/logrus"
	"github.com/codegangsta/cli"
	"github.com/gobins/goaws/apihandlers"
)

func main() {
	app := cli.NewApp()
	app.Name = "goaws"
	app.Usage = "Aws cli using Golang SDK"

	//Defining sub-commands
	var environment string
	var tagname string
	var tagvalue string
	app.Commands = []cli.Command{
		{
			Name:  "get-subnets",
			Usage: "List all subnets",

			Action: func(c *cli.Context) {
				log.Debug("Calling apihandlers.GetSubnetsFormatted")
				apihandlers.GetSubnetsFormatted()
			},
		},
		{
			Name:  "get-instances",
			Usage: "List all subnets",
			Flags: []cli.Flag{
				cli.StringFlag{
					Name:        "environment",
					Usage:       "Environment Name",
					Destination: &environment,
				},
			},
			Action: func(c *cli.Context) {
				log.Debug("Calling apihandlers.GetInstancesFormatted")
				apihandlers.GetInstancesFormatted(environment)
			},
		},
		{
			Name:  "update-tag",
			Usage: "Updates tag for all objects in subnet",
			Flags: []cli.Flag{
				cli.StringFlag{
					Name:        "environment",
					Usage:       "Environment Name",
					Destination: &environment,
				},
				cli.StringFlag{
					Name:        "tagname",
					Usage:       "Key of the tag",
					Destination: &tagname,
				},
				cli.StringFlag{
					Name:        "tagvalue",
					Usage:       "Value of the tag",
					Destination: &tagvalue,
				},
			},
			Action: func(c *cli.Context) {
				log.Debug("Calling apihandlers.UpdateEnvTags")
				apihandlers.UpdateEnvTags(tagname, tagvalue, environment)
			},
		},
	}
	app.Run(os.Args)

}
<commit_msg>Adding checks for required flags<commit_after>package main

import (
	"fmt"
	"os"

	log "github.com/Sirupsen/logrus"
	"github.com/codegangsta/cli"
	"github.com/gobins/goaws/apihandlers"
)

func main() {
	app := cli.NewApp()
	app.Name = "goaws"
	app.Usage = "Aws cli using Golang SDK"

	//Defining sub-commands
	var environment string
	var tagname string
	var tagvalue string
	app.Commands = []cli.Command{
		{
			Name:  "get-subnets",
			Usage: "List all subnets",

			Action: func(c *cli.Context) {
				log.Debug("Calling apihandlers.GetSubnetsFormatted")
				apihandlers.GetSubnetsFormatted()
			},
		},
		{
			Name:  "get-instances",
			Usage: "List all subnets",
			Flags: []cli.Flag{
				cli.StringFlag{
					Name:        "environment",
					Usage:       "Environment Name",
					Destination: &environment,
				},
			},
			Action: func(c *cli.Context) {
				log.Debug("Calling apihandlers.GetInstancesFormatted")
				var errorFlag bool
				if environment == "" {
					fmt.Println("environment is required for update-tag subcommand")
					errorFlag = true
				}
				if errorFlag == true {
					os.Exit(1)
				}
				apihandlers.GetInstancesFormatted(environment)
			},
		},
		{
			Name:  "update-tag",
			Usage: "Updates tag for all objects in subnet",
			Flags: []cli.Flag{
				cli.StringFlag{
					Name:        "environment",
					Usage:       "Environment Name",
					Destination: &environment,
				},
				cli.StringFlag{
					Name:        "tagname",
					Usage:       "Key of the tag",
					Destination: &tagname,
				},
				cli.StringFlag{
					Name:        "tagvalue",
					Usage:       "Value of the tag",
					Destination: &tagvalue,
				},
			},
			Action: func(c *cli.Context) {
				log.Debug("Calling apihandlers.UpdateEnvTags")
				var errorFlag bool
				if tagname == "" {
					fmt.Println("tagname is required for update-tag subcommand")
					errorFlag = true
				}
				if tagvalue == "" {
					fmt.Println("tagvalue is required for update-tag subcommand")
					errorFlag = true
				}
				if environment == "" {
					fmt.Println("environment is required for update-tag subcommand")
					errorFlag = true
				}
				if errorFlag == true {
					os.Exit(1)
				}
				apihandlers.UpdateEnvTags(tagname, tagvalue, environment)
			},
		},
	}
	app.Run(os.Args)

}
<|endoftext|>