• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang browser.OpenURL函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/pkg/browser.OpenURL函数的典型用法代码示例。如果您正苦于以下问题:Golang OpenURL函数的具体用法?Golang OpenURL怎么用?Golang OpenURL使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了OpenURL函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: openService

func openService(ns string, serviceName string, c *k8sclient.Client, printURL bool, retry bool) {
	if retry {
		if err := RetryAfter(40, func() error { return CheckService(ns, serviceName, c) }, 10*time.Second); err != nil {
			util.Errorf("Could not find finalized endpoint being pointed to by %s: %v", serviceName, err)
			os.Exit(1)
		}
	}
	svcs, err := c.Services(ns).List(kubeApi.ListOptions{})
	if err != nil {
		util.Errorf("No services found %v\n", err)
	}
	found := false
	for _, service := range svcs.Items {
		if serviceName == service.Name {

			url := service.ObjectMeta.Annotations[exposeURLAnnotation]

			if printURL {
				util.Successf("%s\n", url)
			} else {
				util.Successf("\nOpening URL %s\n", url)
				browser.OpenURL(url)
			}
			found = true
			break
		}
	}
	if !found {
		util.Errorf("No service %s in namespace %s\n", serviceName, ns)
	}
}
开发者ID:fabric8io,项目名称:gofabric8,代码行数:31,代码来源:service.go


示例2: StackoverflowceptionCheck

func StackoverflowceptionCheck(err error) bool {
	if err != nil {
		url := "http://stackoverflow.com/search?q="
		url += err.Error()
		browser.OpenURL(url)
		return true
	}
	return false
}
开发者ID:pixeldesu,项目名称:stackoverflowception,代码行数:9,代码来源:golang.go


示例3: authorizeInBrowser

// Opens a browser tab/window with the login to pocket for authorization.
// Only returns when the user presses enter.
func authorizeInBrowser(requestToken string, redirectURI string) {
	template := "https://getpocket.com/auth/authorize?" +
		"request_token=%s&redirect_uri=%s"
	url := fmt.Sprintf(template, requestToken, redirectURI)
	browser.OpenURL(url)

	reader := bufio.NewReader(os.Stdin)
	fmt.Println("Press enter when authorized")
	_, err := reader.ReadString('\n')
	checkFatal(err)
}
开发者ID:simonlindblad,项目名称:go-pocket,代码行数:13,代码来源:auth.go


示例4: main

func main() {

	var err error

	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage of %s: command <args>...\n", os.Args[0])
		flag.PrintDefaults()
	}

	flag.Parse()
	if len(flag.Args()) < 1 {
		flag.Usage()
		return
	}

	ifaceAndPort := fmt.Sprintf("%v:0", *iface)
	listener, err := net.Listen("tcp4", ifaceAndPort)
	if err != nil {
		log.Fatal(err)
	}

	pr, pw, _ := os.Pipe()
	gcChan := make(chan *gctrace, 1)
	scvgChan := make(chan *scvgtrace, 1)

	parser := Parser{
		reader:   pr,
		gcChan:   gcChan,
		scvgChan: scvgChan,
	}

	gcvisGraph = NewGraph(strings.Join(flag.Args(), " "), GCVIS_TMPL)

	go startSubprocess(pw, flag.Args())
	go parser.Run()

	http.HandleFunc("/", indexHandler)

	go http.Serve(listener, nil)

	url := fmt.Sprintf("http://%s/", listener.Addr())
	log.Printf("opening browser window, if this fails, navigate to %s", url)
	browser.OpenURL(url)

	for {
		select {
		case gcTrace := <-gcChan:
			gcvisGraph.AddGCTraceGraphPoint(gcTrace)
		case scvgTrace := <-scvgChan:
			gcvisGraph.AddScavengerGraphPoint(scvgTrace)
		}
	}
}
开发者ID:jsouthworth,项目名称:gcvis,代码行数:53,代码来源:main.go


示例5: main

// main is the entry point for the application.
func main() {
	print("Starting - HTTP service on port 8676\n")
	print("Press 'ctrl + c' to quit\n")
	folderPath, err := osext.ExecutableFolder()
	if err != nil {
		print(err)
	}

	browser.OpenURL("http://localhost:8676/index.html")

	panic(http.ListenAndServe(":8676", http.FileServer(http.Dir(folderPath))))

}
开发者ID:ErlendSB,项目名称:WebServer_GO,代码行数:14,代码来源:serve.go


示例6: main

func main() {
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage of %s: command <args>...\n", os.Args[0])
		flag.PrintDefaults()
	}

	flag.Parse()
	if len(flag.Args()) < 1 {
		flag.Usage()
		return
	}

	subcommand := NewSubCommand(flag.Args())
	parser := NewParser(subcommand.PipeRead)
	gcvisGraph := NewGraph(strings.Join(flag.Args(), " "), GCVIS_TMPL)
	server := NewHttpServer(*iface, *port, &gcvisGraph)

	go subcommand.Run()
	go parser.Run()
	go server.Start()

	url := server.Url()
	log.Printf("opening browser window, if this fails, navigate to %s", url)
	browser.OpenURL(url)

	for {
		select {
		case gcTrace := <-parser.GcChan:
			gcvisGraph.AddGCTraceGraphPoint(gcTrace)
		case scvgTrace := <-parser.ScvgChan:
			gcvisGraph.AddScavengerGraphPoint(scvgTrace)
		case output := <-parser.NoMatchChan:
			fmt.Fprintln(os.Stderr, output)
		case <-parser.done:
			if parser.Err != nil {
				fmt.Fprintf(os.Stderr, parser.Err.Error())
				os.Exit(1)
			}

			if subcommand.Err() != nil {
				fmt.Fprintf(os.Stderr, subcommand.Err().Error())
				os.Exit(1)
			}

			os.Exit(0)
		}
	}
}
开发者ID:mikereedell,项目名称:gcvis,代码行数:48,代码来源:main.go


示例7: Open

// Open opens a product on the amazon website
func Open(c *cli.Context) {
	api := api.Create(c.GlobalString("locale"))

	conf := config.GetConfig()
	asin, exists := conf.ASINFromCache("Products", c.Args().First())
	if !exists {
		fmt.Fprintln(os.Stderr, "Cannot look up ASIN")
		os.Exit(1)
	}

	result, err := api.ItemLookup(asin, "Small")

	if err != nil {
		panic(err)
	}

	browser.OpenURL(result.Items.ItemList[0].DetailPageURL)
}
开发者ID:matthistuff,项目名称:amazon,代码行数:19,代码来源:open.go


示例8: serve

func serve(ctx context.Context) error {

	wgctx.Add(ctx, "serve")
	defer wgctx.Done(ctx, "serve")

	env := envctx.FromContext(ctx)
	cmd := cmdctx.FromContext(ctx)

	// Starting with port zero chooses a random open port
	listner, err := net.Listen("tcp", fmt.Sprintf(":%d", cmd.Port))
	if err != nil {
		return kerr.Wrap("QGLXHWPWQW", err)
	}
	defer listner.Close()

	// Here we get the address we're serving on
	address, ok := listner.Addr().(*net.TCPAddr)
	if !ok {
		return kerr.New("CBLPYVGGUR", "Can't find address (l.Addr() is not *net.TCPAddr)")
	}

	url := fmt.Sprintf("http://localhost:%d/%s/", address.Port, env.Path)

	cmd.Printf("Server now running on %s\n", url)

	// We open the default browser and navigate to the address we're serving
	// from. This will error if the system doesn't have a browser, so we can
	// ignore the error.
	browser.OpenURL(url)

	withCancel(ctx, func() {
		err = http.Serve(listner, nil)
	})
	if err != nil {
		return kerr.Wrap("TUCBTWMRNN", err)
	}

	if cmd.Debug {
		return kerr.New("ATUTBOICGJ", "Connection closed")
	}
	return nil

}
开发者ID:kego,项目名称:ke,代码行数:43,代码来源:server.go


示例9: Checkout

// Checkout initiates the checkout for a cart
func Checkout(c *cli.Context) {
	api := api.Create(c.GlobalString("locale"))

	conf := config.GetConfig()
	defer conf.Flush()

	cartName := conf.CartNameFromCache(c.Args().First())

	if cart, exists := conf.Carts[cartName]; exists {
		if getResponse, getErr := api.CartGet(cart.CartID, cart.HMAC); getErr == nil {
			delete(conf.Carts, cartName)
			browser.OpenURL(getResponse.Cart.PurchaseURL)
		} else {
			panic(getErr)
		}
	} else {
		fmt.Fprintf(os.Stderr, "Cart %s is unknown\n", cartName)
		os.Exit(1)
	}
}
开发者ID:matthistuff,项目名称:amazon,代码行数:21,代码来源:checkout.go


示例10: main

func main() {
	if len(os.Args) < 2 {
		log.Fatalf("usage: %s command <args>...", os.Args[0])
	}
	pr, pw, _ := os.Pipe()
	gc := make(chan *gctrace, 1)
	scvg := make(chan *scvgtrace, 1)

	go startSubprocess(pw)
	go startParser(pr, gc, scvg)

	l, err := net.Listen("tcp4", "127.0.0.1:0")
	if err != nil {
		log.Fatal(err)
	}
	http.HandleFunc("/", index)
	go http.Serve(l, nil)

	url := fmt.Sprintf("http://%s/", l.Addr())
	log.Printf("opening browser window, if this fails, navigate to %s", url)
	browser.OpenURL(url)

	for {
		select {
		case gc := <-gc:
			mu.Lock()
			ts := int(time.Now().UnixNano() / 1e6)
			heapuse = append(heapuse, graphPoints{ts, gc.Heap1})
			mu.Unlock()
		case scvg := <-scvg:
			mu.Lock()
			ts := int(time.Now().UnixNano() / 1e6)
			scvginuse = append(scvginuse, graphPoints{ts, scvg.inuse})
			scvgidle = append(scvgidle, graphPoints{ts, scvg.idle})
			scvgsys = append(scvgsys, graphPoints{ts, scvg.sys})
			scvgreleased = append(scvgreleased, graphPoints{ts, scvg.released})
			scvgconsumed = append(scvgconsumed, graphPoints{ts, scvg.consumed})
			mu.Unlock()
		}
	}
}
开发者ID:Gwill,项目名称:gcvis,代码行数:41,代码来源:main.go


示例11: openURL

func openURL(data string, isHTML bool) error {
	if isHTML {
		tmpfile, err := ioutil.TempFile("", "pmbopenurl")
		if err != nil {
			return err
		}

		_, err = tmpfile.Write([]byte(data))
		if err != nil {
			return err
		}

		err = tmpfile.Close()
		if err != nil {
			return err
		}

		nameWithSuffix := fmt.Sprintf("%s.html", tmpfile.Name())
		err = os.Rename(tmpfile.Name(), nameWithSuffix)
		if err != nil {
			return err
		}

		go func() {
			time.Sleep(15 * time.Second)
			logrus.Infof("cleaning up temporary file: %s", nameWithSuffix)
			os.Remove(nameWithSuffix)
		}()

		logrus.Infof("opening file: %s", nameWithSuffix)
		return browser.OpenFile(nameWithSuffix)
	}

	logrus.Infof("opening url: %s", data)
	return browser.OpenURL(data)
}
开发者ID:justone,项目名称:pmb,代码行数:36,代码来源:util.go


示例12: doServe

func doServe(c *cli.Context) {
	master := c.Bool("master")
	theme := c.String("theme")

	// Get the presentation path from the command line, or grab the current directory.
	presentationPath, _ := os.Getwd()
	if len(c.Args()) > 0 {
		presentationPath = c.Args()[0]
	}

	// Check if the path is relative.
	if !strings.HasPrefix(presentationPath, "/") {
		presentationPath, _ = filepath.Abs(presentationPath)
	}

	// Check if there is a presentation file present.
	if _, err := os.Stat(path.Join(presentationPath, "slides.md")); err != nil {
		fmt.Printf("slides.md does not exist at %s\n", presentationPath)
		os.Exit(1)
	}

	if theme != "" {
		fmt.Println("Using one of the packaged themes ...")
		http.Handle("/css/", http.FileServer(&assetfs.AssetFS{Asset, AssetDir, "themes/" + theme}))
		http.Handle("/fonts/", http.FileServer(&assetfs.AssetFS{Asset, AssetDir, "themes/" + theme}))
	} else {
		if _, err := os.Stat(path.Join(presentationPath, "css", "theme.css")); err == nil {
			fmt.Println("Found a theme, using it ...")
			http.Handle("/css/", http.FileServer(http.Dir(presentationPath)))
			http.Handle("/fonts/", http.FileServer(http.Dir(presentationPath)))
		} else {
			fmt.Println("No theme found ...")
		}
	}

	// Handle the slides.
	http.HandleFunc("/slides.md", func(w http.ResponseWriter, r *http.Request) {
		t, _ := template.ParseFiles(path.Join(presentationPath, "slides.md"))
		t.Execute(w, "")
	})

	// Handle images.
	http.HandleFunc("/img/", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, path.Join(presentationPath, r.URL.Path))
	})

	// Handle reveal.js files.
	http.Handle("/reveal.js/css/", http.FileServer(&assetfs.AssetFS{Asset, AssetDir, ""}))
	http.Handle("/reveal.js/js/", http.FileServer(&assetfs.AssetFS{Asset, AssetDir, ""}))
	http.Handle("/reveal.js/lib/", http.FileServer(&assetfs.AssetFS{Asset, AssetDir, ""}))
	http.Handle("/reveal.js/plugin/", http.FileServer(&assetfs.AssetFS{Asset, AssetDir, ""}))

	// Handle the website.
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		opt := &Option{Markdown: "slides.md", Master: master}
		indexHTML, _ := Asset("assets/index.html")
		indexTemplate := template.Must(template.New("index").Parse(string(indexHTML)))
		indexTemplate.Execute(w, opt)
	})

	fmt.Println("Opening browser and redirecting to the presentation ...")
	browser.OpenURL("http://localhost:8989")

	err := http.ListenAndServe(":8989", nil)
	panic("Error while serving slides: " + err.Error())
}
开发者ID:superseb,项目名称:presenter,代码行数:66,代码来源:commands.go


示例13: init

		defer api.Close()

		url, err := cluster.GetServiceURL(api, namespace, service, serviceURLTemplate)
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			if _, ok := err.(cluster.MissingNodePortError); !ok {
				fmt.Fprintln(os.Stderr, "Check that minishift is running and that you have specified the correct namespace (-n flag).")
			}
			os.Exit(1)
		}

		if https {
			url = strings.Replace(url, "http", "https", 1)
		}
		if serviceURLMode {
			fmt.Fprintln(os.Stdout, url)
		} else {
			fmt.Fprintln(os.Stdout, "Opening kubernetes service "+namespace+"/"+service+" in default browser...")
			browser.OpenURL(url)
		}
	},
}

func init() {
	serviceCmd.Flags().StringVarP(&namespace, "namespace", "n", "default", "The service namespace")
	serviceCmd.Flags().BoolVar(&serviceURLMode, "url", false, "Display the kubernetes service URL in the CLI instead of opening it in the default browser")
	serviceCmd.PersistentFlags().StringVar(&serviceURLFormat, "format", "http://{{.IP}}:{{.Port}}", "Format to output service URL in")
	serviceCmd.Flags().BoolVar(&https, "https", false, "Open the service URL with https instead of http")
	RootCmd.AddCommand(serviceCmd)
}
开发者ID:rawlingsj,项目名称:gofabric8,代码行数:30,代码来源:service.go


示例14: main

func main() {
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage of %s: command <args>...\n", os.Args[0])
		flag.PrintDefaults()
	}

	var pipeRead io.ReadCloser
	var subcommand *SubCommand

	flag.Parse()
	if len(flag.Args()) < 1 {
		if terminal.IsTerminal(int(os.Stdin.Fd())) {
			flag.Usage()
			return
		} else {
			pipeRead = os.Stdin
		}
	} else {
		subcommand = NewSubCommand(flag.Args())
		pipeRead = subcommand.PipeRead
		go subcommand.Run()
	}

	parser := NewParser(pipeRead)
	gcvisGraph := NewGraph(strings.Join(flag.Args(), " "), GCVIS_TMPL)
	server := NewHttpServer(*iface, *port, &gcvisGraph)

	go parser.Run()
	go server.Start()

	url := server.Url()

	if *openBrowser {
		log.Printf("opening browser window, if this fails, navigate to %s", url)
		browser.OpenURL(url)
	} else {
		log.Printf("server started on %s", url)
	}

	for {
		select {
		case gcTrace := <-parser.GcChan:
			gcvisGraph.AddGCTraceGraphPoint(gcTrace)
		case scvgTrace := <-parser.ScvgChan:
			gcvisGraph.AddScavengerGraphPoint(scvgTrace)
		case output := <-parser.NoMatchChan:
			fmt.Fprintln(os.Stderr, output)
		case <-parser.done:
			if parser.Err != nil {
				fmt.Fprintf(os.Stderr, parser.Err.Error())
				os.Exit(1)
			}

			break
		}
	}

	if subcommand != nil && subcommand.Err() != nil {
		fmt.Fprintf(os.Stderr, subcommand.Err().Error())
		os.Exit(1)
	}

	os.Exit(0)
}
开发者ID:botvs,项目名称:gcvis,代码行数:64,代码来源:main.go


示例15: handleEvents

func handleEvents(eventChan chan termbox.Event) {
	for ev := range eventChan {
		switch ev.Type {
		case termbox.EventKey:
			switch ev.Key {
			case termbox.KeyArrowUp:

			case termbox.KeyArrowDown:

			case termbox.KeySpace:
				// page down
				lock.Lock()
				totalN := len(events)
				lock.Unlock()
				if selectedRow >= totalN-1 {
					// the last event
					continue
				}

				if !detailView {
					if selectedRow/pageSize == totalN/pageSize {
						// already the last page, do nothing
						continue
					}

					selectedRow += pageSize
					if selectedRow > totalN-1 {
						// can't be beyond the range
						selectedRow = totalN - 1
					}
					page++

					redrawAll()
				}
				continue

			case termbox.KeyEnter:
				if detailView {
					browser.OpenURL(currentWebHook.Commits[len(currentWebHook.Commits)-selectedCommit-1].Url)
				}
				continue

			case termbox.KeyCtrlD:
				// dashboard page
				if dashboardView {
					redrawAll()
				} else {
					drawDashboardByHour()
				}
				dashboardView = !dashboardView

			case termbox.KeyCtrlP:
				if projectSummaryView {
					redrawAll()
				} else {
					drawDashboardByProject()
				}
				projectSummaryView = !projectSummaryView

			case termbox.KeyCtrlU:
				if userSummaryView {
					redrawAll()
				} else {
					drawDashboardByUser()
				}
				userSummaryView = !userSummaryView

			case termbox.KeyEsc:
				if detailView {
					detailView = false
					redrawAll()
				} else {
					termbox.Close()
					os.Exit(0)
				}
			}

			switch ev.Ch {
			case 'j':
				if detailView {
					if selectedCommit < len(currentWebHook.Commits)-1 {
						selectedCommit++
					} else {
						selectedCommit = 0 // rewind
					}
					drawDetail()
				} else {
					lock.Lock()
					totalN := len(events)
					lock.Unlock()

					if selectedRow < totalN-1 {
						selectedRow++
						if selectedRow%pageSize == 0 {
							page++
						}
						redrawAll()
					}
				}

//.........这里部分代码省略.........
开发者ID:funkygao,项目名称:gafka,代码行数:101,代码来源:ui.go


示例16: main

func main() {
	//Create channels
	symbols := make(chan string)
	output := make(chan string)

	//Stage some workers
	for w := 1; w <= 10; w++ {
		wg.Add(1)
		go worker(symbols, output)
	}

	//Get symbol list from file
	f, _ := os.Open("C:\\temp\\test\\symbols.txt")
	defer f.Close()

	//Read file lines into slice
	scanner := bufio.NewScanner(f)
	scanner.Split(bufio.ScanLines)

	var symlist []string

	for scanner.Scan() {
		symlist = append(symlist, scanner.Text())
	}

	//Process each symbol
	go func() {
		for _, v := range symlist {
			symbols <- v
		}
		close(symbols)
	}()

	//Wait for workers to complete
	go func() {
		wg.Wait()
		close(output)
	}()

	//Spit out status as files complete
	for i := range output {
		fmt.Println(i)
	}

	fmt.Println("Done...")

	//...and now the for the web stuff...

	fns := template.FuncMap{
		"start": func(x int) bool {
			if (x+1)%3 == 1 {
				return true
			}
			return false
		},
		"finish": func(x, y int) bool {
			if (y+1) == x || (y+1)%3 == 0 {
				return true
			}
			return false
		},
	}

	//Parse template
	tmpl := template.Must(template.New("main").Funcs(fns).ParseGlob("*.gohtml"))

	//Function
	http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir("c:\\temp\\test\\"))))
	http.HandleFunc("/", func(res http.ResponseWriter, req *http.Request) {
		// execute template
		tmpl.ExecuteTemplate(res, "tmpl.gohtml", symlist)
	})

	//Call it...
	go browser.OpenURL("http://localhost:9002")

	// create server
	http.ListenAndServe(":9002", nil)
}
开发者ID:AceHeYump,项目名称:UdemyTraining,代码行数:79,代码来源:pullgif3.go


示例17: startInternalHTTPServer

func startInternalHTTPServer(authKey string) error {

	lg.V(15).Infoln("starting internal api server")
	mux, err := createServeMux()
	if err != nil {
		lg.Error("failed to create router")
		return err
	}

	auth := Auth{Key: authKey, wrapped: mux}
	conf := clientconfig.Get()
	listener, err := net.Listen("tcp", conf.Settings.Local.ClientBindAddr)
	if err != nil {
		lg.Warning(err)
		listener, err = net.Listen("tcp", "127.0.0.1:")
	}
	if err != nil {
		lg.Warning(err)
		ui.Notify("Could not bind any local port (bootstrap)")
		lg.Errorln("Could not bind any local port (bootstrap)")
		return err
	}

	go func(listenaddr string) {
		// baseURL := fmt.Sprintf()
		baseURL := fmt.Sprintf("http://%s?suk=", listenaddr)
		for {
			select {
			case <-ui.Actions.CopyBrowserCodeToClipboard:
				bc := browsercode.BrowserCode{Key: authKey}
				err := bc.SetHostport(listener.Addr().String())
				if err != nil {
					lg.Errorln(err)
					continue
				}
				err = bc.CopyToClipboard()
				if err != nil {
					lg.Errorln(err)
				}

			case <-ui.Actions.OpenInBrowser:
				browser.OpenURL(baseURL + singleUseKeys.New() + "#/")

			case <-ui.Actions.Help:
				browser.OpenURL(baseURL + singleUseKeys.New() + "#/docs/__/index")
			}
			singleUseKeys.Cleanup()
		}
	}(listener.Addr().String())

	doneC := make(chan bool, 1)
	go func() {
		defer listener.Close()
		err = http.Serve(listener, auth)
		if err != nil {
			doneC <- false
		}
	}()
	select {
	case ok := <-doneC:
		if !ok {
			return errors.New("Could not start internal http server")
		}
	case <-time.After(time.Millisecond * 200):
		return nil
	}
	return nil
}
开发者ID:thomasf,项目名称:alkasir,代码行数:68,代码来源:http.go


示例18: Serve

// Serve the presentation.
func Serve(c *cli.Context) {
	master := c.Bool("master")
	theme := c.String("theme")

	// Get the presentation path from the command line, or grab the current directory.
	presentationPath, _ := os.Getwd()
	if len(c.Args()) > 0 {
		presentationPath = c.Args()[0]
	}

	// Check if the path is relative.
	if !pathIsAbsolute(presentationPath) {
		presentationPath, _ = filepath.Abs(presentationPath)
	}

	// Check if there is a presentation file present.
	if fileExists(path.Join(presentationPath, "slides.md")) {
		log.Printf("slides.md does not exist at %s\n", presentationPath)
		os.Exit(1)
	}

	// Check if a theme was passed.
	if themeExists(theme) {
		log.Printf("Using build-in theme [%s]\n", theme)
		http.Handle("/css/", http.FileServer(&assetfs.AssetFS{bindata.Asset, bindata.AssetDir, bindata.AssetInfo, "themes/" + theme}))
		http.Handle("/fonts/", http.FileServer(&assetfs.AssetFS{bindata.Asset, bindata.AssetDir, bindata.AssetInfo, "themes/" + theme}))
	} else {
		if !fileExists(path.Join(presentationPath, "css", "theme.css")) {
			log.Println("Found a theme in the css directory, using it...")
			http.Handle("/css/", http.FileServer(http.Dir(presentationPath)))
			http.Handle("/fonts/", http.FileServer(http.Dir(presentationPath)))
		} else {
			log.Println("No theme found ...")
		}
	}

	// Handle the slides.
	http.HandleFunc("/slides.md", func(w http.ResponseWriter, r *http.Request) {
		t, _ := template.ParseFiles(path.Join(presentationPath, "slides.md"))
		t.Execute(w, "")
	})

	// Handle images.
	http.HandleFunc("/img/", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, path.Join(presentationPath, r.URL.Path))
	})

	// Handle reveal.js files.
	http.Handle("/reveal.js/css/", http.FileServer(&assetfs.AssetFS{bindata.Asset, bindata.AssetDir, bindata.AssetInfo, ""}))
	http.Handle("/reveal.js/js/", http.FileServer(&assetfs.AssetFS{bindata.Asset, bindata.AssetDir, bindata.AssetInfo, ""}))
	http.Handle("/reveal.js/lib/", http.FileServer(&assetfs.AssetFS{bindata.Asset, bindata.AssetDir, bindata.AssetInfo, ""}))
	http.Handle("/reveal.js/plugin/", http.FileServer(&assetfs.AssetFS{bindata.Asset, bindata.AssetDir, bindata.AssetInfo, ""}))

	// Handle the website.
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		opt := &Option{Markdown: "slides.md", Master: master}
		indexHTML, _ := bindata.Asset("assets/index.html")
		indexTemplate := template.Must(template.New("index").Parse(string(indexHTML)))
		indexTemplate.Execute(w, opt)
	})

	log.Println("Serving presentation on http://localhost:8989")
	log.Println("Opening browser and redirecting to the presentation, press Ctrl-C to stop ...")
	browser.OpenURL("http://localhost:8989")

	err := http.ListenAndServe(":8989", nil)
	log.Fatalf("Error while serving slides: %s\n", err.Error())
}
开发者ID:nautsio,项目名称:presenter,代码行数:69,代码来源:serve.go


示例19: AuthorizePocket

func AuthorizePocket(code string, callbackUrl string) {
	browser.OpenURL("https://getpocket.com/auth/authorize?request_token=" + code + "&redirect_uri=" + callbackUrl)
}
开发者ID:hougasian,项目名称:PoGo,代码行数:3,代码来源:pocket.go


示例20: Monitor

// Monitor monitors log aggregates results into RunStats
func Monitor(bf int) RunStats {
	log.Println("MONITORING")
	defer fmt.Println("DONE MONITORING")
retry_dial:
	ws, err := websocket.Dial("ws://localhost:8080/log", "", "http://localhost/")
	if err != nil {
		time.Sleep(1 * time.Second)
		goto retry_dial
	}
retry:
	// Get HTML of webpage for data (NHosts, Depth, ...)
	doc, err := goquery.NewDocument("http://localhost:8080/")
	if err != nil {
		log.Println("unable to get log data: retrying:", err)
		time.Sleep(10 * time.Second)
		goto retry
	}
	if view {
		browser.OpenURL("http://localhost:8080/")
	}
	nhosts := doc.Find("#numhosts").First().Text()
	log.Println("hosts:", nhosts)
	depth := doc.Find("#depth").First().Text()
	log.Println("depth:", depth)
	nh, err := strconv.Atoi(nhosts)
	if err != nil {
		log.Fatal("unable to convert hosts to be a number:", nhosts)
	}
	d, err := strconv.Atoi(depth)
	if err != nil {
		log.Fatal("unable to convert depth to be a number:", depth)
	}
	clientDone := false
	rootDone := false
	var rs RunStats
	rs.NHosts = nh
	rs.Depth = d
	rs.BF = bf

	var M, S float64
	k := float64(1)
	first := true
	for {
		var data []byte
		err := websocket.Message.Receive(ws, &data)
		if err != nil {
			// if it is an eof error than stop reading
			if err == io.EOF {
				log.Println("websocket terminated before emitting EOF or terminating string")
				break
			}
			continue
		}
		if bytes.Contains(data, []byte("EOF")) || bytes.Contains(data, []byte("terminating")) {
			log.Printf(
				"EOF/terminating Detected: need forkexec to report and clients: rootDone(%t) clientDone(%t)",
				rootDone, clientDone)
		}
		if bytes.Contains(data, []byte("root_round")) {
			if clientDone || rootDone {
				// ignore after we have received our first EOF
				continue
			}
			var entry StatsEntry
			err := json.Unmarshal(data, &entry)
			if err != nil {
				log.Fatal("json unmarshalled improperly:", err)
			}
			log.Println("root_round:", entry)
			if first {
				first = false
				rs.MinTime = entry.Time
				rs.MaxTime = entry.Time
			}
			if entry.Time < rs.MinTime {
				rs.MinTime = entry.Time
			} else if entry.Time > rs.MaxTime {
				rs.MaxTime = entry.Time
			}

			rs.AvgTime = ((rs.AvgTime * (k - 1)) + entry.Time) / k

			var tM = M
			M += (entry.Time - tM) / k
			S += (entry.Time - tM) * (entry.Time - M)
			k++
			rs.StdDev = math.Sqrt(S / (k - 1))
		} else if bytes.Contains(data, []byte("forkexec")) {
			if rootDone {
				continue
			}
			var ss SysStats
			err := json.Unmarshal(data, &ss)
			if err != nil {
				log.Fatal("unable to unmarshal forkexec:", ss)
			}
			rs.SysTime = ss.SysTime
			rs.UserTime = ss.UserTime
			log.Println("FORKEXEC:", ss)
//.........这里部分代码省略.........
开发者ID:ineiti,项目名称:prifi,代码行数:101,代码来源:monitor.go



注:本文中的github.com/pkg/browser.OpenURL函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang errors.Cause函数代码示例发布时间:2022-05-28
下一篇:
Golang rdtest.Assert函数代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap