func test(cmd *cli.Cmd) {

	cmd.Spec = "COMMAND [ARG...] [--application-path=<appPath>]"

	var (
		command       = cmd.StringArg("COMMAND", "", "Command to run for test")
		args          = cmd.StringsArg("ARG", nil, "Arguments")
		bootstrapPath = cmd.StringOpt("application-path", "./", "Directory of your application")
	)

	cmd.Action = func() {

		var apiKey string
		authFilePath := os.Getenv("HOME") + "/.apisonator"
		f, err := os.Open(authFilePath)
		if err != nil {
			fmt.Println("Error. Login first")
			os.Exit(1)
		}
		fmt.Fscan(f, &apiKey)

		yamlFile, err := ioutil.ReadFile(*bootstrapPath + "/config.yml")
		var config configYaml
		err = yaml.Unmarshal(yamlFile, &config)
		if err != nil {
			panic(err)

		}

		data := url.Values{}
		data.Add("endpoint", config.Endpoint)
		data.Add("api_key", apiKey)

		resp, _ := http.PostForm(APIEndpoint+"/api/proxies.json", data)

		defer resp.Body.Close()
		body, _ := ioutil.ReadAll(resp.Body)

		if resp.StatusCode == http.StatusCreated {
			var response createEndpoint
			if err := json.Unmarshal(body, &response); err != nil {
				panic(err)
			}
			Success := emoji.Sprintf("\n Testing with endpoint: %shttp://%s.apisonator.io%s -> %s\n", chalk.Green, response.Subdomain, chalk.Reset, response.Endpoint)
			fmt.Println(Success)

			arguments := strings.Join(*args, " ")
			testCommand := "export ENDPOINT=http://" + config.Subdomain + ".apisonator.io ; " + *command + " " + arguments
			//out, err := exec.Command("bash", "-c", testCommand).Output()
			cmd := exec.Command("bash", "-c", testCommand)
			cmd.Stdout = os.Stdout
			cmd.Stdin = os.Stdin
			cmd.Stderr = os.Stderr
			cmd.Run()
			if err != nil {
				fmt.Println("Command failed..")
			}
		} else {
			fmt.Println("Something went wrong :()")
		}
	}
}
Beispiel #2
1
func main() {
	configPath := flag.String("c", "", "path to config file")
	flag.Parse()

	if *configPath == "" {
		flag.Usage()
		return
	}

	// read and decode configuration
	var config Config
	cfg, err := ioutil.ReadFile(*configPath)
	if err != nil {
		log.Panic(err)
	}
	if _, err := toml.Decode(string(cfg), &config); err != nil {
		log.Panic(err)
	}

	// initialize yahoo finance
	var f *yahoo.YahooFinanceService
	f, err = yahoo.New(config.Yahoo)
	if err != nil {
		log.Panic(err)
	}

	// initialize telegram framework
	app, err := telegram.New(config.Telegram)
	if err != nil {
		log.Panic("could not init app : ", err)
	}

	// helper handlers
	app.Use(
		&slugger.Slugger{},
		&canceler.Canceler{config.Canceler.Duration},

		telegram.HandlerFunc(func(ctrl *telegram.Control, bot *tgbotapi.BotAPI, update tgbotapi.Update) {
			ctrl.Log().Println(fmt.Sprintf(
				"incoming message: text:%q; query:%q",
				update.Message.Text, update.InlineQuery.Query,
			))

			ctrl.NextWithValue("start", time.Now())
			ctrl.Next()
		}),
	)

	// logic
	app.UseOn("/help", helpHandler.New())

	fh := financeHandler.New(f)
	app.Use(condition.Condition{
		matcher.RegExp{
			Source:  matcher.SourceText,
			Pattern: regexp.MustCompile(`^\/([a-z]{3}$|rate.*$)`),
		},
		fh,
	})
	app.Use(condition.Condition{
		matcher.RegExp{
			Source:  matcher.SourceQuery,
			Pattern: regexp.MustCompile(`^([a-z]{3}|[a-z]{3} [a-z]{3})`),
		},
		fh,
	})

	// error handler
	app.UseErrFunc(func(ctrl *telegram.Control, bot *tgbotapi.BotAPI, update tgbotapi.Update, err error) {
		if update.Message.Text != "" {
			bot.Send(tgbotapi.NewMessage(update.Message.Chat.ID, emoji.Sprintf(":space_invader:error: %s", err)))
		}
		ctrl.Log().Println("got error", err)
		ctrl.Stop()
	})

	app.Use(telegram.HandlerFunc(func(ctrl *telegram.Control, bot *tgbotapi.BotAPI, update tgbotapi.Update) {
		var dur float64
		if start, ok := ctrl.Context().Value("start").(time.Time); ok {
			dur = time.Since(start).Seconds() * 1000
		} else {
			dur = -1
		}
		ctrl.Log().Println(fmt.Sprintf(
			"message processing complete in %.2fmsec", dur,
		))
		ctrl.Next()
	}))

	http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("KURSOBOT_OK"))
	})

	log.Println("about to start app...")
	app.Bot().Send(tgbotapi.NewMessage(config.NoticeChatID, emoji.Sprintf("Hey man, I have been restarted! :fireworks::sunglasses:")))

	// start listen
	log.Fatal(app.Listen())
}
func create(cmd *cli.Cmd) {

	cmd.Spec = "SUBDOMAIN ENDPOINT [--no-bootstrap | --bootstrap-destination=<dir>]"

	var (
		name          = cmd.StringArg("SUBDOMAIN", "", "Name for your apisonator proxy $subdomain.apisonator.io")
		endpoint      = cmd.StringArg("ENDPOINT", "", "Your API endpoint")
		noBootstrap   = cmd.BoolOpt("no-bootstrap", false, "Don't create the basic app bootstrap")
		bootstrapPath = cmd.StringOpt("bootstrap-destination", "./", "Path to create the bootstrap files for your project")
	)

	cmd.Action = func() {
		var apiKey string
		authFilePath := os.Getenv("HOME") + "/.apisonator"
		f, err := os.Open(authFilePath)
		if err != nil {
			fmt.Println("Error. Login first")
			os.Exit(1)
		}
		fmt.Fscan(f, &apiKey)

		data := url.Values{}
		data.Set("subdomain", *name)
		data.Add("endpoint", *endpoint)
		data.Add("api_key", apiKey)

		resp, _ := http.PostForm(APIEndpoint+"/api/proxies.json", data)
		body, _ := ioutil.ReadAll(resp.Body)
		if resp.StatusCode == http.StatusCreated {
			var response createEndpoint
			if err := json.Unmarshal(body, &response); err != nil {
				panic(err)
			}
			Success := emoji.Sprintf("\n:white_check_mark: Your apisonator endpoint: %shttp://%s.apisonator.io%s -> %s\n", chalk.Green, response.Subdomain, chalk.Reset, response.Endpoint)
			fmt.Print(Success)

			if *noBootstrap {
				fmt.Println("\nBootstrap not created\n")
			} else {
				// Ugly eh. Extract
				resp, _ := http.Get("https://github.com/apisonator/bootstrap/archive/master.zip")
				defer resp.Body.Close()
				body, _ := ioutil.ReadAll(resp.Body)
				mode := int(0777)
				os.Remove("/tmp/bootstrap.zip")
				ioutil.WriteFile("/tmp/bootstrap.zip", body, os.FileMode(mode))
				Unzip("/tmp/bootstrap.zip", *bootstrapPath)
				os.Rename(*bootstrapPath+"bootstrap-master", *bootstrapPath+"apisonator-"+*name)
				fmt.Printf("\t\nBootstrap directory created at: %s\n\n", *bootstrapPath+"apisonator-"+*name)

				// Modify yaml file and set correct subdomain
				yamlFile, err := ioutil.ReadFile(*bootstrapPath + "apisonator-" + *name + "/config.yml")
				var config configYaml
				err = yaml.Unmarshal(yamlFile, &config)
				if err != nil {
					panic(err)

				}
				config.Subdomain = *name
				config.Endpoint = *endpoint
				mary, err := yaml.Marshal(config)
				if err != nil {
					panic(err)
				}
				err = ioutil.WriteFile(*bootstrapPath+"apisonator-"+*name+"/config.yml", mary, os.FileMode(mode))
				if err != nil {
					panic(err)

				}
			}

		} else {
			// move this emoji and success / fail to another
			Failed := emoji.Sprintf("\n:red_circle: Subdomain %s does exists\n", *name)
			fmt.Println(Failed)
		}
	}
}