Exemplo n.º 1
0
Arquivo: hn.go Projeto: anykao/p
func main() {
	usr, err := user.Current()
	if err != nil {
		log.Fatal(err)
	}
	cache := filepath.Join(usr.HomeDir, ".ak", "news")

	flag.Parse()
	if flag.NArg() > 0 {
		idx, e := strconv.ParseInt(flag.Arg(0), 0, 0)
		if e != nil {
			// not int
		}
		item := getItem(cache, idx)
		if comment {
			open.Start(fmt.Sprintf("%s%s%d", HACKERWEB, "/#/item/", item.ID))
		} else {
			open.Start(item.URL)
		}

	} else {
		if next {
			var news []Item
			res, err := http.Get(NEWS2)
			if err != nil {
				log.Fatal(err)
			}
			bytes, err := ioutil.ReadAll(res.Body)
			if err != nil {
				log.Fatal(err)
			}
			res.Body.Close()
			populateCache(cache, bytes)
			contents := string(bytes)
			err = json.NewDecoder(strings.NewReader(contents)).Decode(&news)
			if err != nil {
				log.Fatal(err)
			}
			showNewsList(news)
		} else {
			var news []Item
			res, err := http.Get(NEWS)
			if err != nil {
				log.Fatal(err)
			}
			bytes, err := ioutil.ReadAll(res.Body)
			if err != nil {
				log.Fatal(err)
			}
			res.Body.Close()
			populateCache(cache, bytes)
			contents := string(bytes)
			err = json.NewDecoder(strings.NewReader(contents)).Decode(&news)
			showNewsList(news)
		}
	}
}
Exemplo n.º 2
0
// Our programs starts executing here
func main() {
	// We need exactly 2 parameters: the first one is the program name,
	// the second one should be the photo we want to operate on
	if len(os.Args) != 2 {
		fmt.Println("Please give a single file name as an argument!")
		os.Exit(1)
	}

	// Retrieve the photo file name from the arguments array
	fileName := os.Args[1]

	// Try to opern the given file, error out on failure
	file, err := os.Open(fileName)
	exitOnError(err, "Couldn't open file")

	// Try to extract the EXIF data, error out on failure
	exifData, err := exif.Decode(file)
	exitOnError(err, "Couldn't find EXIF data")

	// Try to find a GPS coordinates entry in the EXIF data structure.
	// Error out on failure
	lat, long, err := exifData.LatLong()
	exitOnError(err, "Couldn't read GPS coordinates")

	// Create the final URL by using the Google Maps URL template
	url := fmt.Sprintf(googleMapsURLTemplate, lat, long)

	// Try to start the default browser for the current OS.
	// Show the computer URL on error, so that the user can still
	// access it manually
	err = open.Start(url)
	exitOnError(err, fmt.Sprintf(
		"Couldn't start the default browser, please visit %v manually", url))
}
Exemplo n.º 3
0
func (g *Commands) QR(byId bool) error {

	kvChan := g.urler(byId, g.opts.Sources)

	address := DefaultQRShareServer
	if g.opts.Meta != nil {
		meta := *(g.opts.Meta)
		if retrAddress, ok := meta[AddressKey]; ok && len(retrAddress) >= 1 {
			address = retrAddress[0]
		}
	}

	address = strings.TrimRight(address, "/")
	if envKeySet.PublicKey == "" {
		envKeySet.PublicKey = "5160897b3586461e83e7279c10352ac4"
	}
	if envKeySet.PrivateKey == "" {
		envKeySet.PrivateKey = "5a3451dadab74f75b16f754c0a931949"
	}

	for kv := range kvChan {
		switch kv.value.(type) {
		case error:
			g.log.LogErrf("%s: %s\n", kv.key, kv.value)
			continue
		}

		fileURI, ok := kv.value.(string)
		if !ok {
			continue
		}

		curTime := time.Now()
		pl := meddler.Payload{
			URI:         fileURI,
			RequestTime: curTime.Unix(),
			Payload:     fmt.Sprintf("%v%v", rand.Float64(), curTime),
			PublicKey:   envKeySet.PublicKey,
			ExpiryTime:  curTime.Add(time.Hour).Unix(),
		}

		plainTextToSign := pl.RawTextForSigning()

		pl.Signature = fmt.Sprintf("%s", envKeySet.Sign([]byte(plainTextToSign)))

		uv := pl.ToUrlValues()
		encodedValues := uv.Encode()

		fullUrl := fmt.Sprintf("%s/qr?%s", address, encodedValues)
		if g.opts.Verbose {
			g.log.Logf("%q => %q\n", kv.key, fullUrl)
		}

		if err := open.Start(fullUrl); err != nil {
			g.log.Logf("qr: err %v %q\n", err, fullUrl)
		}
	}

	return nil
}
Exemplo n.º 4
0
func showQRImage(uuid string) (err error) {
	qrUrl := `https://login.weixin.qq.com/qrcode/` + uuid
	params := url.Values{}
	params.Set("t", "webwx")
	params.Set("_", strconv.FormatInt(time.Now().Unix(), 10))

	req, err := http.NewRequest("POST", qrUrl, strings.NewReader(params.Encode()))
	if err != nil {
		return
	}

	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("Cache-Control", "no-cache")
	resp, err := Client.Do(req)
	if err != nil {
		return
	}
	defer resp.Body.Close()

	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return
	}

	if err = createFile(QRImagePath, data, false); err != nil {
		return
	}

	return open.Start(QRImagePath)
}
Exemplo n.º 5
0
func (g *Commands) Open(ot OpenType) error {
	byId := (ot & IdOpen) != 0
	kvChan := g.urler(byId)

	for kv := range kvChan {
		switch kv.value.(type) {
		case error:
			g.log.LogErrf("%s: %s\n", kv.key, kv.value)
			continue
		}

		openArgs := []string{}
		canAddUrl := (ot & BrowserOpen) != 0

		if byId {
			canAddUrl = true
		} else if (ot & FileManagerOpen) != 0 {
			openArgs = append(openArgs, g.context.AbsPathOf(kv.key))
		}

		if canAddUrl {
			if castKey, ok := kv.value.(string); ok {
				openArgs = append(openArgs, castKey)
			}
		}

		for _, arg := range openArgs {
			open.Start(arg)
		}
	}

	return nil
}
Exemplo n.º 6
0
func run(dir, port, host string) {
	open.Start(host)
	fmt.Println("-> Listening on ", host)
	fmt.Println("-> Press ctrl-c to kill process")
	http.CloseIdleConnections()
	log.Fatal(http.ListenAndServe(port, http.FileServer(http.Dir(dir))))
}
Exemplo n.º 7
0
func setupSysTrayReal() {

	systray.SetIcon(icon.Data)
	mUrl := systray.AddMenuItem("Go to Arduino Create (staging)", "Arduino Create")
	mDebug := systray.AddMenuItem("Open debug console", "Debug console")
	menuVer := systray.AddMenuItem("Agent version "+version+"-"+git_revision, "")
	mPause := systray.AddMenuItem("Pause Plugin", "")
	//mQuit := systray.AddMenuItem("Quit Plugin", "")

	menuVer.Disable()

	go func() {
		<-mPause.ClickedCh
		ports, _ := serial.GetPortsList()
		for _, element := range ports {
			spClose(element)
		}
		systray.Quit()
		*hibernate = true
		log.Println("Restart becayse setup went wrong?")
		restart("")
	}()

	// go func() {
	// 	<-mQuit.ClickedCh
	// 	systray.Quit()
	// 	exit()
	// }()

	go func() {
		for {
			<-mDebug.ClickedCh
			logAction("log on")
			open.Start("http://localhost" + port)
		}
	}()

	// We can manipulate the systray in other goroutines
	go func() {
		for {
			<-mUrl.ClickedCh
			open.Start("http://create-staging.arduino.cc")
		}
	}()
}
Exemplo n.º 8
0
Arquivo: bopen.go Projeto: anykao/p
func main() {
	nc, _ := nats.Connect("nats://yourhost:4222")
	defer nc.Close()
	nc.QueueSubscribe(TOPIC, QUEUE, func(m *nats.Msg) {
		fmt.Println(string(m.Data))
		open.Start(string(m.Data))
	})
	select {}
}
Exemplo n.º 9
0
Arquivo: main.go Projeto: anykao/p
func main() {
	flag.Parse()

	url := template.URLQueryEscaper(flag.Args())

	url = fmt.Sprintf("http://52.68.184.19:8080/search/%s", url)

	fmt.Printf("open %s\n", url)

	open.Start(url)

}
Exemplo n.º 10
0
Arquivo: diffjar.go Projeto: anykao/p
func webui() {
	goji.Get("/", index)
	goji.Get("/result/diff.txt", generateResult)
	goji.Post("/diff", PostDiff)
	//Fully backwards compatible with net/http's Handlers
	//goji.Get("/result", http.RedirectHandler("/", 301))
	if os.Getenv("DEBUG") == "" {
		time.AfterFunc(500*time.Millisecond, func() {
			open.Start("http://localhost:8000")
		})
	}
	goji.Serve()
}
Exemplo n.º 11
0
func docPlugin(c *cli.Context) {
	if len(c.Args()) != 1 {
		fmt.Printf("Which documentation do you want to open? Try 'apiplexy plugin-doc <plugin-name>'.\n")
		os.Exit(1)
	}
	plugin, ok := apiplexy.AvailablePlugins()[c.Args()[0]]
	if !ok {
		fmt.Printf("Plugin '%s' not found. Try 'apiplexy plugins' to list available ones.\n", c.Args()[0])
		os.Exit(1)
	}
	fmt.Printf("Opening documentation for '%s' at: %s\n", plugin.Name, plugin.Link)
	open.Start(plugin.Link)
}
Exemplo n.º 12
0
func doOpen(flags *flag.FlagSet) {
	args := flags.Args()
	branch, err := getBranchFromArgs(args)
	checkError(err)
	remote, err := git.GetRemoteURL("origin")
	checkError(err)
	cr, err := circle.GetTree(remote.Path, remote.RepoName, branch)
	checkError(err)
	if len(*cr) == 0 {
		fmt.Printf("No results, are you sure there are tests for %s/%s?\n",
			remote.Path, remote.RepoName)
		return
	}
	latestBuild := (*cr)[0]
	open.Start(latestBuild.BuildURL)
}
Exemplo n.º 13
0
func main() {
	title := flag.String("title", "", "Optional Title")
	script := flag.String("script", "", "lua script to filter/enrich data")
	laddr := flag.String("addr", "", "Address on which to serve up the map")
	flag.Usage = func() {
		fmt.Fprintln(os.Stderr, usage)
		flag.PrintDefaults()
	}
	flag.Parse()

	if *script != "" {
		if _, err := os.Stat(*script); os.IsNotExist(err) {
			log.Fatal(err)
		}
	}

	http.HandleFunc("/gidata", handleGIData)
	http.Handle("/resources/", http.FileServer(rice.MustFindBox("public").HTTPBox()))
	http.HandleFunc("/", serveIndex(*title))

	/* Get the address from the command line or the environment */
	address := *laddr
	if "" == address {
		address = os.Getenv("GIM_ADDR")
	}
	/* Failing that, use an ephemeral port on loopback */
	if "" == address {
		address = "127.0.0.1:0"
	}
	/* If it's a single port, prepend a localhost */
	if _, err := strconv.Atoi(address); nil == err {
		address = "127.0.0.1:" + address
	}

	go readStdin(*script)

	l, err := net.Listen("tcp", address)
	if err != nil {
		log.Fatal(err)
	}
	go func() {
		addr := fmt.Sprintf("http://%s", l.Addr())
		log.Printf("Listening on %v\n", addr)
		open.Start(addr)
	}()
	log.Fatal(http.Serve(l, nil))
}
Exemplo n.º 14
0
Arquivo: main.go Projeto: hhatto/ftcat
func execCmd(c *cli.Context) {
	if len(c.Args()) < 1 {
		fmt.Println("Specify Markdown file")
		return
	}

	/* open webbrowser */
	open.Start("http://0.0.0.0:8089")

	ch := make(chan string)
	gChan = make(chan string)

	targetFileName = c.Args()[0]
	go fileWatcher(ch)

	/* for static files */
	staticFilePath := path.Join(os.Getenv("GOPATH"), "src/github.com/hhatto/ftcat/static")
	fs := http.FileServer(http.Dir(staticFilePath))
	http.Handle("/static/", http.StripPrefix("/static/", fs))

	/* index */
	http.HandleFunc("/", indexHandler)

	/* server sent events */
	es := eventsource.New(nil, nil)
	defer es.Close()
	http.Handle("/events", es)

	/* message broker */
	go func() {
		id := 1
		for {
			select {
			case n := <-ch:
				es.SendEventMessage(n, "cre", strconv.Itoa(id))
				id++
			case n := <-gChan:
				es.SendEventMessage(n, "cre", strconv.Itoa(id))
				id++
			}
		}
	}()

	log.Fatal(http.ListenAndServe(":8089", nil))
}
Exemplo n.º 15
0
func DoOpen(c *cli.Context) {
	useOptions(c)
	dest := c.Args().First()
	log.Debugf("Open destination: %s", dest)
	url := ""
	message := ""

	switch dest {

	default:
		fallthrough
	case "deployed":
		app, err := account.GetCurrentApp()
		if err != nil {
			message = "Sorry, could not find a deployed app to open."
		}
		url = "http://" + app.HostingSubdomain + ".appstax.io"
		break

	case "admin":
		url = "http://appstax.com/admin/#/dashboard"
		break

	case "local":
		url = "http://localhost:9000/"
		break
	}

	if url != "" {
		term.Printf("Opening %s in your browser.\n", url)
		err := open.Start(url)
		if err != nil {
			message = "Ooops! Something went wrong."
		}
	}

	if message != "" {
		term.Section()
		term.Println(message)
	}
}
Exemplo n.º 16
0
func openBrowser() {
	url := "http://" + host + "/tour.html"
	tries := 0

	for {
		if tries > 100 {
			fmt.Println("giving up after ", time.Duration(tries)*100*time.Microsecond)
			os.Exit(1)
		}

		<-time.After(10 * time.Microsecond)

		if _, err := http.Get(url); err == nil {
			println("Opening " + url)
			fmt.Println(open.Start(url))
			return
		}

		tries++
	}
}
Exemplo n.º 17
0
Arquivo: auth.go Projeto: nildev/tools
// Auth user against selected provider and return AccessToken
func Auth(provider string) AccessToken {
	port := "7777"
	go func() {
		log.Infof("Starting HTTP server on 0.0.0.0:%s...", port)
		http.HandleFunc("/oauth2", processOAuth)
		http.HandleFunc("/store", persistToken)

		if err := http.ListenAndServe(":"+port, nil); err != nil {
			log.WithField("error", err).Fatal("Unable to create listener")
		}
	}()

	if provider == "bitbucket.org" {
		log.Infof("Please authenticate yourself within [%s] provider in opened browser window ...", provider)
		wg.Add(1)
		open.Start("https://bitbucket.org/site/oauth2/authorize?client_id=FUGTa554rDNASAzdBg&response_type=token")
	}
	wg.Wait()

	return accessToken
}
Exemplo n.º 18
0
Arquivo: utils.go Projeto: foomo/shop
// OpenInBrowser stores the html under "<name><date>.html" in the current
// directory and opens it in the browser
func OpenInBrowser(name string, html string) error {
	pwd, err := os.Getwd()
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("PWD", pwd)

	//path := "file://" + pwd + "/" + "diff.html"
	path := pwd + "/" + "diff-" + name + "_" + GetFormattedTimeShort(time.Now()) + ".html"
	fmt.Println("PATH", path)
	tmpFile, err := os.Create(path)
	if err != nil {
		return err
	}
	tmpFile.WriteString(html)
	tmpFile.Close()
	err = open.Start(path)
	if err != nil {
		log.Println(err)
	}
	return err

}
Exemplo n.º 19
0
func main() {
	flag.StringVar(&presently.Dir, "d", "", "Directory of the repository")
	flag.StringVar(&presently.Port, "p", "8080", "Port to listen")
	flag.Parse()
	var args = flag.Args()

	if presently.Dir == "" {
		if len(args) == 0 {
			fmt.Println("You need to specify -dir")
			flag.PrintDefaults()
			os.Exit(0)
		} else {
			presently.Dir = args[0]
		}
	}

	go func() {
		url := "http://localhost:" + presently.Port
		time.Sleep(400 * time.Millisecond)
		open.Start(url)
	}()
	presently.Serve()
}
Exemplo n.º 20
0
func (b Bopen) Open(url string) {
	open.Start(url)
}
Exemplo n.º 21
0
// Config does the initial creation of the token
//
// It may run an internal webserver to receive the results
func Config(name string, config *oauth2.Config) error {
	overrideCredentials(name, config)
	// See if already have a token
	tokenString := fs.ConfigFile.MustValue(name, "token")
	if tokenString != "" {
		fmt.Printf("Already have a token - refresh?\n")
		if !fs.Confirm() {
			return nil
		}
	}

	// Detect whether we should use internal web server
	useWebServer := false
	switch config.RedirectURL {
	case RedirectURL, RedirectPublicURL, RedirectLocalhostURL:
		useWebServer = true
	case TitleBarRedirectURL:
		fmt.Printf("Use auto config?\n")
		fmt.Printf(" * Say Y if not sure\n")
		fmt.Printf(" * Say N if you are working on a remote or headless machine or Y didn't work\n")
		useWebServer = fs.Confirm()
		if useWebServer {
			// copy the config and set to use the internal webserver
			configCopy := *config
			config = &configCopy
			config.RedirectURL = RedirectURL
		}
	}

	// Make random state
	stateBytes := make([]byte, 16)
	_, err := rand.Read(stateBytes)
	if err != nil {
		return err
	}
	state := fmt.Sprintf("%x", stateBytes)
	authURL := config.AuthCodeURL(state)

	// Prepare webserver
	server := authServer{
		state:       state,
		bindAddress: bindAddress,
		authURL:     authURL,
	}
	if useWebServer {
		server.code = make(chan string, 1)
		go server.Start()
		defer server.Stop()
		authURL = "http://" + bindAddress + "/auth"
	}

	// Generate a URL for the user to visit for authorization.
	_ = open.Start(authURL)
	fmt.Printf("If your browser doesn't open automatically go to the following link: %s\n", authURL)
	fmt.Printf("Log in and authorize rclone for access\n")

	var authCode string
	if useWebServer {
		// Read the code, and exchange it for a token.
		fmt.Printf("Waiting for code...\n")
		authCode = <-server.code
		if authCode != "" {
			fmt.Printf("Got code\n")
		} else {
			return fmt.Errorf("Failed to get code")
		}
	} else {
		// Read the code, and exchange it for a token.
		fmt.Printf("Enter verification code> ")
		authCode = fs.ReadLine()
	}
	token, err := config.Exchange(oauth2.NoContext, authCode)
	if err != nil {
		return fmt.Errorf("Failed to get token: %v", err)
	}
	return putToken(name, token)
}
Exemplo n.º 22
0
func (u *fireflyUI) open(url string) {
	open.Start(url)
}
Exemplo n.º 23
0
func (u *fireflyUI) show() {
	open.Start(u.settingsUrl)
}
Exemplo n.º 24
0
// OpenUrl will open a file, directory, or URI using the OS's default application
// for that object type.
//
// See github.com/skratchdot/open-golang
func OpenUrl(url string) {
	open.Start(url)
}
Exemplo n.º 25
0
func main() {
	flag.Usage = func() {
		usage()
	}

	flag.Parse()
	util.InitLogs()
	defer util.FlushLogs()

	verflag.PrintAndExitIfRequested()

	// Initialize the client
	if clientConfig.Host == "" {
		clientConfig.Host = os.Getenv("KUBERNETES_MASTER")
	}

	// Load namespace information for requests
	// Check if the namespace was overriden by the -ns argument
	ctx := api.NewDefaultContext()
	if len(*ns) > 0 {
		ctx = api.WithNamespace(ctx, *ns)
	} else {
		nsInfo, err := kubecfg.LoadNamespaceInfo(*nsFile)
		if err != nil {
			glog.Fatalf("Error loading current namespace: %v", err)
		}
		ctx = api.WithNamespace(ctx, nsInfo.Namespace)
	}

	if clientConfig.Host == "" {
		// TODO: eventually apiserver should start on 443 and be secure by default
		// TODO: don't specify http or https in Host, and infer that from auth options.
		clientConfig.Host = "http://localhost:8080"
	}
	if client.IsConfigTransportTLS(*clientConfig) {
		auth, err := kubecfg.LoadClientAuthInfoOrPrompt(*authConfig, os.Stdin)
		if err != nil {
			glog.Fatalf("Error loading auth: %v", err)
		}
		clientConfig.Username = auth.User
		clientConfig.Password = auth.Password
		if auth.CAFile != "" {
			clientConfig.CAFile = auth.CAFile
		}
		if auth.CertFile != "" {
			clientConfig.CertFile = auth.CertFile
		}
		if auth.KeyFile != "" {
			clientConfig.KeyFile = auth.KeyFile
		}
		if auth.BearerToken != "" {
			clientConfig.BearerToken = auth.BearerToken
		}
		if auth.Insecure != nil {
			clientConfig.Insecure = *auth.Insecure
		}
	}
	kubeClient, err := client.New(clientConfig)
	if err != nil {
		glog.Fatalf("Can't configure client: %v", err)
	}

	if *serverVersion != verflag.VersionFalse {
		got, err := kubeClient.ServerVersion()
		if err != nil {
			fmt.Printf("Couldn't read version from server: %v\n", err)
			os.Exit(1)
		}
		if *serverVersion == verflag.VersionRaw {
			fmt.Printf("%#v\n", *got)
			os.Exit(0)
		} else {
			fmt.Printf("Server: Kubernetes %s\n", got)
			os.Exit(0)
		}
	}

	if *preventSkew {
		got, err := kubeClient.ServerVersion()
		if err != nil {
			fmt.Printf("Couldn't read version from server: %v\n", err)
			os.Exit(1)
		}
		if c, s := version.Get(), *got; !reflect.DeepEqual(c, s) {
			fmt.Printf("Server version (%#v) differs from client version (%#v)!\n", s, c)
			os.Exit(1)
		}
	}

	if *proxy {
		glog.Info("Starting to serve on localhost:8001")
		if *openBrowser {
			go func() {
				time.Sleep(2 * time.Second)
				open.Start("http://localhost:8001/static/")
			}()
		}
		server, err := kubecfg.NewProxyServer(*www, clientConfig)
		if err != nil {
			glog.Fatalf("Error creating proxy server: %v", err)
		}
		glog.Fatal(server.Serve())
	}

	if len(flag.Args()) < 1 {
		usage()
		os.Exit(1)
	}
	method := flag.Arg(0)

	matchFound := executeAPIRequest(ctx, method, kubeClient) || executeControllerRequest(ctx, method, kubeClient) || executeNamespaceRequest(method, kubeClient)
	if matchFound == false {
		glog.Fatalf("Unknown command %s", method)
	}
}
Exemplo n.º 26
0
// RunInspect is the handler for 'scw inspect'
func RunInspect(ctx CommandContext, args InspectArgs) error {
	nbInspected := 0
	ci := make(chan api.ScalewayResolvedIdentifier)
	cj := make(chan api.InspectIdentifierResult)
	go api.ResolveIdentifiers(ctx.API, args.Identifiers, ci)
	go api.InspectIdentifiers(ctx.API, ci, cj)

	if args.Browser {
		// --browser will open links in the browser
		for {
			data, isOpen := <-cj
			if !isOpen {
				break
			}

			switch data.Type {
			case api.IdentifierServer:
				err := open.Start(fmt.Sprintf("https://cloud.scaleway.com/#/servers/%s", data.Object.(*api.ScalewayServer).Identifier))
				if err != nil {
					return fmt.Errorf("cannot open browser: %v", err)
				}
				nbInspected++
			case api.IdentifierImage:
				err := open.Start(fmt.Sprintf("https://cloud.scaleway.com/#/images/%s", data.Object.(*api.ScalewayImage).Identifier))
				if err != nil {
					return fmt.Errorf("cannot open browser: %v", err)
				}
				nbInspected++
			case api.IdentifierVolume:
				err := open.Start(fmt.Sprintf("https://cloud.scaleway.com/#/volumes/%s", data.Object.(*api.ScalewayVolume).Identifier))
				if err != nil {
					return fmt.Errorf("cannot open browser: %v", err)
				}
				nbInspected++
			case api.IdentifierSnapshot:
				logrus.Errorf("Cannot use '--browser' option for snapshots")
			case api.IdentifierBootscript:
				logrus.Errorf("Cannot use '--browser' option for bootscripts")
			}
		}

	} else {
		// without --browser option, inspect will print object info to the terminal
		res := "["
		for {
			data, isOpen := <-cj
			if !isOpen {
				break
			}
			if args.Format == "" {
				dataB, err := json.MarshalIndent(data.Object, "", "  ")
				if err == nil {
					if nbInspected != 0 {
						res += ",\n"
					}
					res += string(dataB)
					nbInspected++
				}
			} else {
				tmpl, err := template.New("").Funcs(api.FuncMap).Parse(args.Format)
				if err != nil {
					return fmt.Errorf("format parsing error: %v", err)
				}

				err = tmpl.Execute(ctx.Stdout, data.Object)
				if err != nil {
					return fmt.Errorf("format execution error: %v", err)
				}
				fmt.Fprint(ctx.Stdout, "\n")
				nbInspected++
			}
		}
		res += "]"

		if args.Format == "" {
			if ctx.Getenv("SCW_SENSITIVE") != "1" {
				res = ctx.API.HideAPICredentials(res)
			}
			fmt.Fprintln(ctx.Stdout, res)
		}
	}

	if len(args.Identifiers) != nbInspected {
		return fmt.Errorf("at least 1 item failed to be inspected")
	}
	return nil
}
Exemplo n.º 27
0
	port int
)

var serverCmd = &cobra.Command{
	Use:   "server",
	Short: "host the generated site locally",
	Long:  `host the generated site locally so that you could look and feel it before pushing`,
	Run: func(cmd *cobra.Command, args []string) {

		addr := fmt.Sprintf(":%d", port)
		url := fmt.Sprintf("http://localhost:%d/index.html", port)

		go func() {
			time.Sleep(1)
			log.Printf("Starting your default browser with %s\n", url)
			open.Start(url)
		}()

		processSignal(watchFiles())

		log.Printf("Serving static content on %s\n", addr)
		http.ListenAndServe(addr, http.FileServer(http.Dir("./build")))

	},
}

func init() {
	serverCmd.Flags().IntVarP(&port, "port", "p", DEFAULT_PORT, "port to listen")
}

func processSignal(watcher *fsnotify.Watcher) {
Exemplo n.º 28
0
func OpenBrowser(args []string) {
	err := open.Start(args[0])
	if err != nil {
		fatal("Can't open browser: '" + err.Error())
	}
}
Exemplo n.º 29
0
func main() {
	port := info.Port()
	log.Println("Listening on port " + port)
	open.Start("http://127.0.0.1:" + port)
	http.ListenAndServe(":"+port, router.Routes())
}
Exemplo n.º 30
0
// Config does the initial creation of the token
//
// It may run an internal webserver to receive the results
func Config(id, name string, config *oauth2.Config) error {
	changed := overrideCredentials(name, config)
	automatic := fs.ConfigFile.MustValue(name, fs.ConfigAutomatic) != ""

	// See if already have a token
	tokenString := fs.ConfigFile.MustValue(name, "token")
	if tokenString != "" {
		fmt.Printf("Already have a token - refresh?\n")
		if !fs.Confirm() {
			return nil
		}
	}

	// Detect whether we should use internal web server
	useWebServer := false
	switch config.RedirectURL {
	case RedirectURL, RedirectPublicURL, RedirectLocalhostURL:
		useWebServer = true
		if automatic {
			break
		}
		fmt.Printf("Use auto config?\n")
		fmt.Printf(" * Say Y if not sure\n")
		fmt.Printf(" * Say N if you are working on a remote or headless machine\n")
		auto := fs.Confirm()
		if !auto {
			fmt.Printf("For this to work, you will need rclone available on a machine that has a web browser available.\n")
			fmt.Printf("Execute the following on your machine:\n")
			if changed {
				fmt.Printf("\trclone authorize %q %q %q\n", id, config.ClientID, config.ClientSecret)
			} else {
				fmt.Printf("\trclone authorize %q\n", id)
			}
			fmt.Println("Then paste the result below:")
			code := ""
			for code == "" {
				fmt.Printf("result> ")
				code = strings.TrimSpace(fs.ReadLine())
			}
			token := &oauth2.Token{}
			err := json.Unmarshal([]byte(code), token)
			if err != nil {
				return err
			}
			return putToken(name, token)
		}
	case TitleBarRedirectURL:
		useWebServer = automatic
		if !automatic {
			fmt.Printf("Use auto config?\n")
			fmt.Printf(" * Say Y if not sure\n")
			fmt.Printf(" * Say N if you are working on a remote or headless machine or Y didn't work\n")
			useWebServer = fs.Confirm()
		}
		if useWebServer {
			// copy the config and set to use the internal webserver
			configCopy := *config
			config = &configCopy
			config.RedirectURL = RedirectURL
		}
	}

	// Make random state
	stateBytes := make([]byte, 16)
	_, err := rand.Read(stateBytes)
	if err != nil {
		return err
	}
	state := fmt.Sprintf("%x", stateBytes)
	authURL := config.AuthCodeURL(state)

	// Prepare webserver
	server := authServer{
		state:       state,
		bindAddress: bindAddress,
		authURL:     authURL,
	}
	if useWebServer {
		server.code = make(chan string, 1)
		go server.Start()
		defer server.Stop()
		authURL = "http://" + bindAddress + "/auth"
	}

	// Generate a URL for the user to visit for authorization.
	_ = open.Start(authURL)
	fmt.Printf("If your browser doesn't open automatically go to the following link: %s\n", authURL)
	fmt.Printf("Log in and authorize rclone for access\n")

	var authCode string
	if useWebServer {
		// Read the code, and exchange it for a token.
		fmt.Printf("Waiting for code...\n")
		authCode = <-server.code
		if authCode != "" {
			fmt.Printf("Got code\n")
		} else {
			return errors.New("failed to get code")
		}
	} else {
		// Read the code, and exchange it for a token.
		fmt.Printf("Enter verification code> ")
		authCode = fs.ReadLine()
	}
	token, err := config.Exchange(oauth2.NoContext, authCode)
	if err != nil {
		return errors.Wrap(err, "failed to get token")
	}

	// Print code if we do automatic retrieval
	if automatic {
		result, err := json.Marshal(token)
		if err != nil {
			return errors.Wrap(err, "failed to marshal token")
		}
		fmt.Printf("Paste the following into your remote machine --->\n%s\n<---End paste", result)
	}
	return putToken(name, token)
}