示例#1
0
func (f *FileManager) Download(request *messaging.FileRequest) messaging.FileResponse { // save the file to ftp and download via ftp on browser
	fileResponse := messaging.FileResponse{}

	if len(request.Body) == 0 {

	} else {
		var saveServerPath string = request.RootSavePath
		var accessServerPath string = request.RootGetPath

		fmt.Println(request.RootSavePath)
		fmt.Println(request.RootGetPath)

		file := FileData{}
		json.Unmarshal(request.Body, &file)

		temp := common.DecodeFromBase64(file.Body)
		ioutil.WriteFile((saveServerPath + request.FilePath + file.FileName), []byte(temp), 0666)
		err := webbrowser.Open(accessServerPath + request.FilePath + file.FileName)
		if err != nil {
			fileResponse.IsSuccess = false
			fileResponse.Message = "Downloading Failed!" + err.Error()
		} else {
			fileResponse.IsSuccess = true
			fileResponse.Message = "Downloading file successfully completed"
		}

	}

	return fileResponse
}
示例#2
0
func StartWeb(wg sync.WaitGroup) {
	defer wg.Done()

	cfg := config.Read()
	listenUri := fmt.Sprintf("%s:%d", cfg.Server.Host, cfg.Server.Port)

	mux := http.NewServeMux()

	mux.HandleFunc("/creds/info", web.RawCredHandler)
	mux.HandleFunc("/creds/info/", web.InfoCredHandler)
	mux.HandleFunc("/creds", CredHandler)

	mux.HandleFunc("/users/", UsersHandler)

	mux.HandleFunc("/connect", ConnectHandler)
	mux.HandleFunc("/ping", PingHandler)
	mux.HandleFunc("/protocol-handler", ProtocolHandlerHandler)

	static := http.FileServer(http.Dir(config.AssetDir("htdocs")))
	mux.Handle("/", static)

	server := &http.Server{
		Addr:    listenUri,
		Handler: mux,
	}

	log.Println("Webservice will start on", listenUri)
	if cfg.Application.OpenWebUIOnStart {
		log.Println("Opening web browser…")
		// TODO: Create proper welcome page
		webbrowser.Open(fmt.Sprintf("%s", listenUri))
	}
	panic(server.ListenAndServe())
}
示例#3
0
func Initialize(newAddressList *addresslist.SafeIPList,
	newSandwichSettings *settings.Settings,
	newShutdown func(fileindex.FileManifest)) {
	addressList = newAddressList
	sandwichSettings = newSandwichSettings
	shutdown = newShutdown
	go downloadThread()
	go downloadThread()
	go downloadThread()
	go downloadThread()
	DownloadQueue = make(chan *IPFilePair, 1000)
	file, err := os.Open(util.ConfPath("manifest-cache.json"))
	if err != nil && os.IsNotExist(err) {
		fileManifest = client.BuildFileManifest()
	} else if err != nil {
		log.Println(err)
		fileManifest = client.BuildFileManifest()
	} else if xml, err := ioutil.ReadAll(file); err != nil {
		log.Println(err)
		fileManifest = client.BuildFileManifest()
		file.Close()
	} else if fileManifest, err = fileindex.UnmarshalManifest(xml); err != nil {
		fileManifest = client.BuildFileManifest()
	} else {
		fileManifest = client.CleanManifest(fileManifest)
		file.Close()
	}
	go InitializeFancyStuff()
	if !sandwichSettings.DontOpenBrowserOnStart {
		webbrowser.Open("http://localhost:" + sandwichSettings.LocalServerPort)
	}
}
示例#4
0
func openIssue(issue *github.Issue) error {
	task := fmt.Sprintf("Open issue #%v in the browser", *issue.Number)
	if err := webbrowser.Open(*issue.HTMLURL); err != nil {
		return errs.NewError(task, err)
	}
	return nil
}
示例#5
0
func (jts *JobTypeServer) ServeTestGin( //--port int,
	htmlFiles_l []string) error {
	router := jts.mkGinEngine(htmlFiles_l)
	server := httptest.NewServer(router)
	defer server.Close()
	url := server.URL

	//	port_s := ""
	//	if port > 0 && port < 65536 {
	//		port_s = fmt.Sprintf(":%d", port)
	//	}
	//	url := fmt.Sprintf("http://localhost%s/", port_s)

	go func() {
		time.Sleep(100 * time.Millisecond)
		err := webbrowser.Open(url)
		if err != nil {
			log.Error("FAILED to open url in browser", "err", err)
		}
	}()

	//	server.Start()
	time.Sleep(3 * time.Second)
	return nil
	//	router := jts.mkGinEngine(htmlFiles_l)
	//	return router.Run(port_s) // listen and server on 0.0.0.0:8080
}
示例#6
0
func main() {

	var home RefHandler
	var search SearchHandler
	var login LoginHandler
	var logout LogoutHandler
	var admin AdminViewHandler
	var searchAdmin SearchAdminHandler
	var edit EditHandler
	var delete DeleteHandler
	var new NewHandler

	port := ":8080"
	log.Println("Starting Web Server 127.0.0.1" + port)
	go Exit()

	webbrowser.Open("http://localhost" + port)

	mux := mux.NewRouter()

	mux.Handle("/", home).Name("home")
	mux.Handle("/search", search)
	mux.Handle("/login", login).Methods("POST")
	mux.Handle("/logout", logout)
	mux.Handle("/admin", admin)
	mux.Handle("/admin/search", searchAdmin)
	mux.Handle("/admin/new", new)
	mux.Handle("/admin/edit/{id}", edit)
	mux.Handle("/admin/delete/{id}", delete)

	err := http.ListenAndServe(port, mux)
	check(err)
}
示例#7
0
func ServeGin(port int, baseDir string, htmlFiles_l []string) error {
	router := gin.Default()

	router.GET("/", func(c *gin.Context) {
		eh := errHandler_T{}
		var index_b []byte
		eh.safe(func() {
			for _, fn := range htmlFiles_l {
				index_b, eh.err = ioutil.ReadFile(fn)
				if eh.err == nil {
					var n int64
					n, eh.err = io.Copy(c.Writer, bytes.NewBuffer(index_b))
					log.Info("serving local file index.html", "file", fn, "size", n, "err", eh.err)
					break
				}
			}
			if len(index_b) == 0 {
				eh.err = wui.WriteWuiHtml(c.Writer)
				log.Info("serving builtin index.html", "err", eh.err)
			}
		})

		eh.ifErr(func() { c.AbortWithError(http.StatusBadRequest, eh.err) })
	})

	router.POST("/jobs/:jobType", func(c *gin.Context) {
		//		time.Sleep(300 * time.Millisecond)
		eh := errHandler_T{}
		eh.handleJobPost(baseDir, c)
	})

	router.GET("/jobs/:jobType", func(c *gin.Context) {
		//		time.Sleep(300 * time.Millisecond)
		eh := errHandler_T{}
		eh.handleJobList(baseDir, c)
	})

	router.GET("/ping", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "pong",
		})
	})

	port_s := ""
	if port > 0 && port < 65536 {
		port_s = fmt.Sprintf(":%d", port)
	}
	url := fmt.Sprintf("http://localhost%s/", port_s)

	go func() {
		time.Sleep(100 * time.Millisecond)
		err := webbrowser.Open(url)
		if err != nil {
			log.Error("FAILED to open url in browser", "err", err)
		}
	}()

	return router.Run(port_s) // listen and server on 0.0.0.0:8080
}
示例#8
0
文件: fire.go 项目: sara62/fire
// opens browser with Subreddits representation
func browserOutput(subreddits []*Subreddit, port string) {

	viewHandler := func(w http.ResponseWriter, r *http.Request) {
		page := `<html>
			<head>
				<style type="text/css">
					body {margin: 0 auto; max-width: 640px; background: black; color: #CCC; font-family: Courier New, Courier; line-height: 1.2em;}
					.content {padding: 10px;}
					.entry {margin-bottom: 20px;}
					.entry-title a:link, .entry-title a:visited {color: #9df; text-decoration: none;}
					.entry-permalink a:link, .entry-permalink a:visited {color: #CCC; text-decoration: none; font-size: 0.8em;}
					.entry a:hover {color: #6cf;}
					.entry-image {width: 100%; margin-top: 10px;}
				</style>
			</head>
		  	<body>
		  		<div class="content">
				    {{ range . }}
						<h1>{{ .Name }}</h1>
						<div class="subreddit">
						{{ range .Entries }}
							<div class="entry">
								<span class="entry-score">{{ .Score }}<span>
								<span class="entry-title"><a target="_blank" href="{{ .URL }}">{{ .Title }}</a><span>
								<span class="entry-permalink"><a target="_blank" href="http://www.reddit.com{{ .Permalink }}">comments</a><span>
								{{ if .IsImage }}
								    <br /><img class="entry-image" src="{{ .URL }}" alt="" />
								{{ end }}
								{{ if .HasEmbed }}
									<br />{{ .EmbedHtml }}
								{{ end }}
							</div>
						{{ end }}
						</div>
				    {{ end }}
			    </div>
		  	</body>
		</html>`

		t := template.New("browser")
		t, _ = t.Parse(page)
		t.Execute(w, subreddits)
	}

	wait := make(chan bool)
	http.HandleFunc("/", viewHandler)
	log.Println("HTTP server starting, go to http://localhost:" + port)
	go func() {
		if err := http.ListenAndServe(":"+port, nil); err != nil {
			log.Fatal("ListenAndServe: ", err)
		}
		wait <- true
	}()
	webbrowser.Open("http://localhost:" + port)
	<-wait
}
示例#9
0
func main() {
	noBrowser := false
	flag.BoolVar(&noBrowser, "noBrowser", false, "If set, no browser is opened automatically.")
	flag.Parse()
	done := make(chan bool, 1)

	go bowieweb.Serve(done)
	// start web browser
	if !noBrowser {
		webbrowser.Open("http://localhost:8000")
	}
	// wait for bowieweb to finish serving
	<-done
}
示例#10
0
func main() {
  ​anaconda.SetConsumerKey("j62kyFWBVqCiJElWSHvofSz59")
  anaconda.SetConsumerSecret("FmA9RF7MAEwLbvXfvYRgZMMstinToo6kbR7CcwfpdhWrsEPyrg")
  // webbrowser.Open()
	url, cred, _ := anaconda.AuthorizationURL("")
	webbrowser.Open(url)

	var pincode int64
	fmt.Scan(&pincode)

	newcred, _, _ := anaconda.GetCredentials(cred, strconv.FormatInt(pincode, 10))

	fmt.Printf("%v\n%v\n", newcred.Token, newcred.Secret)
}
示例#11
0
func main() {
	data, err := ioutil.ReadFile(*googleConfigJSON)
	if err != nil {
		log.Panic(err)
	}
	conf, err := Oauth2ConfigFromJSON(data)
	if err != nil {
		log.Panic(err)
	}

	// Redirect user to consent page to ask for permission
	// for the scopes specified above.
	url := conf.AuthCodeURL("state", oauth2.AccessTypeOffline)
	fmt.Printf("Enter the code returned after authorising access: ")
	webbrowser.Open(url)

	// Use the authorization code that is pushed to the redirect URL.
	// NewTransportWithCode will do the handshake to retrieve
	// an access token and initiate a Transport that is
	// authorized and authenticated by the retrieved token.
	var code string
	if _, err := fmt.Scan(&code); err != nil {
		log.Panic(err)
	}
	tok, err := conf.Exchange(oauth2.NoContext, code)
	if err != nil {
		log.Panic(err)
	}

	ac := gads.AuthConfig{
		OAuth2Config: conf,
		OAuth2Token:  tok,
		Auth: gads.Auth{
			CustomerId:     "INSERT_YOUR_CLIENT_CUSTOMER_ID_HERE",
			DeveloperToken: "INSERT_YOUR_DEVELOPER_TOKEN_HERE",
			UserAgent:      "tests (Golang 1.4 github.com/emiddleton/gads)",
		},
	}
	configData, err := json.MarshalIndent(&ac, "", "    ")
	if err != nil {
		log.Panic(err)
	}
	err = ioutil.WriteFile(*newConfigJSON, configData, 0600)
	if err != nil {
		log.Panic(err)
	}
}
示例#12
0
文件: gomd.go 项目: nochso/gomd
func WaitForServer() {
	log.Printf("Waiting for listener on port %d", *args.Port)
	url := fmt.Sprintf("http://localhost:%d/edit/%s", *args.Port, url.QueryEscape(*args.File))
	for {
		time.Sleep(time.Millisecond * 50)
		resp, err := http.Get(url)
		if err != nil {
			continue
		}
		resp.Body.Close()
		break
	}
	log.Println("Opening " + url)
	if err := webbrowser.Open(url); err != nil {
		log.Printf("Possible error while opening browser: %s", err)
	}
}
func main() {
	go func() {
		fmt.Println("Création du .json le ", time.Now())
		fmt.Println("Veuillez patienter quelques instants. Une fois fini, un message vous l'indiquera.")
		createFile(filenameCsv)

		if err := filepath.Walk(root, walkpath); err == nil {
			if err := jsonWrite(filenameCsv); err == nil {
				webbrowser.Open("http://localhost:8080")
			}
		}
	}()
	log.Println("Le serveur est bien démarré")
	http.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("."))))

	http.ListenAndServe(":8080", nil)

}
示例#14
0
文件: pics.go 项目: rwcarlsen/gallery
func view(cmd string, args []string) {
	desc := "view listed pictures in browser-based gallery (or piped from stdin)"
	fs := newFlagSet(cmd, "[PIC-ID...]", desc)
	fs.BoolVar(&noedit, "noedit", false, "don't allow editing of anything in library")
	fs.StringVar(&addr, "addr", "127.0.0.1:", "ip and port to serve gallery at")
	fs.BoolVar(&all, "all", false, "true to view every file in the library")
	fs.Parse(args)

	l, err := net.Listen("tcp", addr)
	check(err)
	addr = l.Addr().String()
	go runserve(l, fs.Args())
	log.Printf("serving on address %v", addr)

	err = webbrowser.Open(addr)
	check(err)

	select {}
}
示例#15
0
文件: main.go 项目: baopham/go-pr
func main() {
	app := cli.NewApp()
	app.Name = "go-pr"
	app.Usage = "Create a Pull Request for the current branch"
	app.UsageText = `
    go-pr @target-branch # default target-user to your Github user
    go-pr target-user/target-repo@target-branch
    go-pr target-user/target-repo # default target-branch to master
    go-pr target-user # default target-branch to master and target-repo to the name of your Github repo
    `
	app.Version = "0.0.1"
	app.Author = "Bao Pham"
	app.Email = "*****@*****.**"

	app.Before = func(c *cli.Context) error {
		if len(c.Args()) < 1 {
			return errors.New("Target is required")
		}

		return nil
	}

	app.Action = func(c *cli.Context) {
		remote := getRemote()

		branch := getBranch()

		currentRepo := NewRepo(remote, branch)

		target := parseTarget(c.Args().First(), currentRepo)

		if !currentRepo.IsGithub() {
			println("Only support Github for now")
			os.Exit(1)
		}

		webbrowser.Open(fmt.Sprintf("https://github.com/%s/%s/compare/%s...%s:%s",
			target.username, target.name, target.branch,
			currentRepo.username, currentRepo.branch))
	}

	app.Run(os.Args)
}
示例#16
0
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())

	proxy := goproxy.NewProxyHttpServer()
	proxy.OnResponse().DoFunc(proxyHandler)
	go func() {
		err := http.ListenAndServe(":8080", proxy)
		if err != nil {
			log.Fatal(err)
		}
	}()
	go func() {
		time.Sleep(time.Second * 1)
		webbrowser.Open("http://localhost:8081/admin/cable-Systeminfo.asp")
	}()
	proxyUrl, _ := url.Parse("http://localhost:8080/")
	httpClient = &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(proxyUrl)}}
	http.HandleFunc("/", handler)
	log.Fatal(http.ListenAndServe(":8081", nil))
}
示例#17
0
文件: pics.go 项目: rwcarlsen/gallery
func serve(cmd string, args []string) {
	desc := "serve listed pics in a browser-based picture gallery (or piped from stdin)"
	fs := newFlagSet(cmd, "[PIC-ID...]", desc)
	fs.StringVar(&addr, "addr", "127.0.0.1:7777", "ip and port to serve gallery at")
	view := fs.Bool("view", false, "opens browser window to gallery page")
	fs.BoolVar(&noedit, "noedit", false, "don't allow editing of anything in library")
	fs.BoolVar(&all, "all", false, "true to view every file in the library")
	fs.Parse(args)

	l, err := net.Listen("tcp", addr)
	check(err)
	go runserve(l, fs.Args())

	log.Printf("serving on address %v", addr)
	if *view {
		err = webbrowser.Open(addr)
		check(err)
	}

	select {}
}
示例#18
0
func Auth(cKey string) (token string, err error) {
	fmt.Println("Beginning authentication")
	rToken, err := requestToken(cKey)
	if err != nil {
		return
	}

	url := fmt.Sprintf("https://getpocket.com/auth/authorize?request_token=%s&redirect_uri=%s", rToken, redirURI)
	if err = webbrowser.Open(url); err == nil {
		c := make(chan bool)
		fmt.Println("Communicating with Pocket.")
		http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
			fmt.Println("Got a response from Pocket.")
			fmt.Fprint(w, "You can close this window now.")
			c <- true
		})
		go func() {
			if err := http.ListenAndServe(":50212", nil); err != nil {
				panic(err)
			}
		}()

		fmt.Println("Waiting for response.")
		<-c
	} else {
		fmt.Println("Please open the following URL in your browser, log in and then press enter")
		fmt.Println(url)
		var str string
		fmt.Scanf("%s", &str)
	}

	fmt.Println("Continuing authetication")

	token, err = accessToken(cKey, rToken)
	if err != nil {
		return
	}
	return
}
示例#19
0
func openPorts(cmd *cobra.Command, args []string) error {
	// TODO: Work your own magic here
	//	fmt.Println("port called")
	if len(args) == 0 {
		return errors.New("missing port argument list")
	}

	portMappings_l := make([]string, 0, len(args)+2)
	for _, port_s := range args {
		srv := httptest.NewServer(http.HandlerFunc( //--"/",
			func(w http.ResponseWriter, r *http.Request) {
				fmt.Fprintf(os.Stderr, "%+v\n", *r)
				http.Error(w, "temp server", http.StatusNotImplemented)
			}))
		srvUrlLen := len(srv.URL)
		colonIdx := strings.LastIndex(srv.URL, ":")
		localPort_s := srv.URL[colonIdx+1 : srvUrlLen]
		portMappings_l = append(portMappings_l, localPort_s+":"+port_s)
		webbrowser.Open(srv.URL)
	}
	fmt.Printf("-p %s\n", strings.Join(portMappings_l, " -p "))
	return nil
}
示例#20
0
文件: service.go 项目: huin/artemis
func runServer(l net.Listener, s *http.Server, openInBrowser bool) {
	urls, err := netutil.ExpandHostedAddrToURLs(l.Addr(), url.URL{
		Scheme: "http",
		Path:   "/",
	})
	if err != nil {
		log.Printf("Could not resolve URL(s) for %s: %v", l.Addr(), err)
	} else if len(urls) < 1 {
		log.Printf("No URLs resolved for %s", l.Addr())
	} else {
		for i, u := range urls {
			log.Printf("Web server URL #%d: %s", i, u.String())
		}
		if openInBrowser {
			if err := webbrowser.Open(urls[0].String()); err != nil {
				log.Printf("Could not open web browser: %v", err)
			}
		}
	}
	log.Printf("Web server started on %v", l.Addr())
	err = s.Serve(l)
	log.Printf("Web server stopped on %v with error: %v", l.Addr(), err)
}
示例#21
0
func ssoLogin() {
	url := os.Getenv("SSO_URL")
	if url == "" {
		org := os.Getenv("HEROKU_ORGANIZATION")
		for org == "" {
			org = getString("Enter your organization name: ")
		}
		url = "https://sso.heroku.com/saml/" + org + "/init?cli=true"
	}
	Err("Opening browser for login...")
	err := webbrowser.Open(url)
	if err != nil {
		Errln(" " + err.Error() + ".\nNavigate to " + cyan(url))
	} else {
		Errln(" done")
	}
	token := getPassword("Enter your access token (typing will be hidden): ")
	user := getUserFromToken(token)
	if user == "" {
		ExitIfError(errors.New("Access token invalid."))
	}
	saveOauthToken(user, token)
	Println("Logged in as " + cyan(user))
}
示例#22
0
// OpenStory is a part of common.IssueTracker interface.
func (tracker *issueTracker) OpenStory(storyId string) error {
	u := fmt.Sprintf("https://github.com/%v/%v/issues/%v",
		tracker.config.GitHubOwner, tracker.config.GitHubRepository, storyId)

	return webbrowser.Open(u)
}
示例#23
0
// OpenPath opens the application in browser with given path
//++ now uses github.com/toqueteos/webbrowser
//++ might use https://bitbucket.org/tebeka/go-wise/src/d8db9bf5c4d1/desktop.go?at=default
//++ preferably write own implementation specific for bapp
//++ (check if certain browsers are installed, specify browser preference on bapp as in: `bapp.PreferBrowser(Browser ... )`  )
func (b *Bapp) OpenPath(path string) {
	webbrowser.Open(fmt.Sprintf("http://localhost:%d%s", b.port, path))
}
示例#24
0
文件: devd.go 项目: mikesavior/devd
func main() {
	httpIP := kingpin.Flag("address", "Address to listen on").
		Short('A').
		Default("127.0.0.1").
		String()

	allInterfaces := kingpin.Flag("a", "Listen on all addresses").
		Short('a').
		Bool()

	certFile := kingpin.Flag("cert", "Certificate bundle file - enables TLS").
		Short('c').
		PlaceHolder("PATH").
		Default("").
		ExistingFile()

	throttleDownKbps := kingpin.Flag(
		"down",
		"Throttle downstream from the client to N kilobytes per second",
	).
		PlaceHolder("N").
		Short('d').
		Default("0").
		Int()

	logHeaders := kingpin.Flag("logheaders", "Log headers").
		Short('H').
		Default("false").
		Bool()

	ignoreHeaders := kingpin.Flag(
		"ignore",
		"Disable logging matching requests. Regexes are matched over 'host/path'",
	).
		Short('I').
		PlaceHolder("REGEX").
		Strings()

	livereloadRoutes := kingpin.Flag("livereload", "Enable livereload for static files").
		Short('l').
		Default("false").
		Bool()

	latency := kingpin.Flag("latency", "Add N milliseconds of round-trip latency").
		PlaceHolder("N").
		Short('n').
		Default("0").
		Int()

	openBrowser := kingpin.Flag("open", "Open browser window on startup").
		Short('o').
		Default("false").
		Bool()

	httpPort := kingpin.Flag(
		"port",
		"Port to listen on - if not specified, devd will auto-pick a sensible port",
	).
		Short('p').
		Int()

	enableTimer := kingpin.Flag("logtime", "Log timing").
		Short('T').
		Default("false").
		Bool()

	throttleUpKbps := kingpin.Flag(
		"up",
		"Throttle upstream from the client to N kilobytes per second",
	).
		PlaceHolder("N").
		Short('u').
		Default("0").
		Int()

	watch := kingpin.Flag("watch", "Watch path to trigger livereload").
		PlaceHolder("PATH").
		Short('w').
		Strings()

	debug := kingpin.Flag("debug", "Debugging for devd development").
		Default("false").
		Bool()

	excludes := kingpin.Flag("exclude", "Glob pattern for files to exclude from livereload.").
		PlaceHolder("PATTERN").
		Short('x').
		Strings()

	routes := kingpin.Arg(
		"route",
		`Routes have the following forms:
			[SUBDOMAIN]/<PATH>=<DIR>
			[SUBDOMAIN]/<PATH>=<URL>
			<DIR>
			<URL>
		`,
	).Required().Strings()

	kingpin.Version(version)

	kingpin.Parse()

	logger := termlog.NewLog()

	if *debug {
		logger.Enable("debug")
	}
	if *enableTimer {
		logger.Enable("timer")
	}
	if *throttleDownKbps == 0 {
		*throttleDownKbps = slowdown.MaxRate
	}
	if *throttleUpKbps == 0 {
		*throttleUpKbps = slowdown.MaxRate
	}

	if *allInterfaces {
		*httpIP = "0.0.0.0"
	}

	tlsEnabled := false
	if *certFile != "" {
		tlsEnabled = true
	}

	var hl net.Listener
	var err error
	if *httpPort > 0 {
		hl, err = net.Listen("tcp", fmt.Sprintf("%v:%d", *httpIP, *httpPort))
	} else {
		hl, err = pickPort(*httpIP, portLow, portHigh, tlsEnabled)
	}
	if err != nil {
		kingpin.Fatalf("Could not bind to port: %s", err)
		return
	}

	templates := ricetemp.MustMakeTemplates(rice.MustFindBox("templates"))
	if err != nil {
		kingpin.Fatalf("Error loading templates: %s", err)
		return
	}

	ignores := make([]*regexp.Regexp, 0, 0)
	for _, expr := range *ignoreHeaders {
		v, err := regexp.Compile(expr)
		if err != nil {
			kingpin.Fatalf("%s", err)
		}
		ignores = append(ignores, v)
	}

	routeColl := make(routeCollection)
	for _, s := range *routes {
		err := routeColl.Set(s)
		if err != nil {
			kingpin.FatalUsage("Invalid route specification: %s", err)
		}
	}

	mux := http.NewServeMux()
	var livereloadEnabled = false
	if *livereloadRoutes || len(*watch) > 0 {
		livereloadEnabled = true
	}

	for match, route := range routeColl {
		handler := devdHandler(
			logger,
			route,
			templates,
			*logHeaders,
			ignores,
			livereloadEnabled,
			*latency,
		)
		mux.Handle(match, http.StripPrefix(route.Path, handler))
	}

	lr := livereload.NewServer("livereload", logger)
	if livereloadEnabled {
		mux.Handle("/livereload", lr)
		mux.Handle("/livereload.js", http.HandlerFunc(lr.ServeScript))
	}
	if *livereloadRoutes {
		err = WatchRoutes(routeColl, lr)
		if err != nil {
			kingpin.Fatalf("Could not watch routes for livereload: %s", err)
		}
	}
	if len(*watch) > 0 {
		err = WatchPaths(*watch, *excludes, lr, logger)
		if err != nil {
			kingpin.Fatalf("Could not watch path for livereload: %s", err)
		}
	}

	var tlsConfig *tls.Config
	if *certFile != "" {
		tlsConfig, err = getTLSConfig(*certFile)
		if err != nil {
			kingpin.Fatalf("Could not load certs: %s", err)
			return
		}
		hl = tls.NewListener(hl, tlsConfig)
	}
	hl = slowdown.NewSlowListener(
		hl,
		float64(*throttleUpKbps)*1024,
		float64(*throttleDownKbps)*1024,
	)

	url := formatURL(tlsEnabled, *httpIP, hl.Addr().(*net.TCPAddr).Port)
	logger.Say("Listening on %s (%s)", url, hl.Addr().String())
	if *openBrowser {
		go func() {
			webbrowser.Open(url)
		}()
	}
	server := &http.Server{
		Addr:    hl.Addr().String(),
		Handler: hostPortStrip(mux),
	}
	err = server.Serve(hl)
	logger.Shout("Server stopped: %v", err)
}
示例#25
0
func main() {
	http.Handle("/", http.FileServer(assetFS()))
	fmt.Println("Serving on port 8000")
	webbrowser.Open("http://localhost:8000")
	http.ListenAndServe(":8000", nil)
}
示例#26
0
func (tracker *issueTracker) OpenStory(storyId string) error {
	relativeURL, _ := url.Parse("browse/" + storyId)
	return webbrowser.Open(tracker.config.ServerURL().ResolveReference(relativeURL).String())
}
示例#27
0
func (tracker *issueTracker) OpenStory(storyId string) error {
	productId := tracker.config.ProductId()
	return webbrowser.Open(fmt.Sprintf("https://sprint.ly/product/%v/item/%v", productId, storyId))
}
示例#28
0
func StartWebkit() {
	webbrowser.Open("127.0.0.1" + UsePort + "/index.html")
}
示例#29
0
文件: devd.go 项目: eticzon/devd
func main() {
	address := kingpin.Flag("address", "Address to listen on").
		Short('A').
		Default("127.0.0.1").
		String()

	allInterfaces := kingpin.Flag("all", "Listen on all addresses").
		Short('a').
		Bool()

	certFile := kingpin.Flag("cert", "Certificate bundle file - enables TLS").
		Short('c').
		PlaceHolder("PATH").
		ExistingFile()

	forceColor := kingpin.Flag("color", "Enable colour output, even if devd is not connected to a terminal").
		Short('C').
		Bool()

	downKbps := kingpin.Flag(
		"down",
		"Throttle downstream from the client to N kilobytes per second",
	).
		PlaceHolder("N").
		Short('d').
		Default("0").
		Uint()

	logHeaders := kingpin.Flag("logheaders", "Log headers").
		Short('H').
		Default("false").
		Bool()

	ignoreLogs := kingpin.Flag(
		"ignore",
		"Disable logging matching requests. Regexes are matched over 'host/path'",
	).
		Short('I').
		PlaceHolder("REGEX").
		Strings()

	livereloadNaked := kingpin.Flag("livereload", "Enable livereload").
		Short('L').
		Default("false").
		Bool()

	livereloadRoutes := kingpin.Flag("livewatch", "Enable livereload and watch for static file changes").
		Short('l').
		Default("false").
		Bool()

	moddMode := kingpin.Flag("modd", "Modd is our parent - synonym for -LCt").
		Short('m').
		Bool()

	latency := kingpin.Flag("latency", "Add N milliseconds of round-trip latency").
		PlaceHolder("N").
		Short('n').
		Default("0").
		Int()

	openBrowser := kingpin.Flag("open", "Open browser window on startup").
		Short('o').
		Default("false").
		Bool()

	port := kingpin.Flag(
		"port",
		"Port to listen on - if not specified, devd will auto-pick a sensible port",
	).
		Short('p').
		Int()

	credspec := kingpin.Flag(
		"password",
		"HTTP basic password protection",
	).
		PlaceHolder("USER:PASS").
		Short('P').
		String()

	quiet := kingpin.Flag("quiet", "Silence all logs").
		Short('q').
		Default("false").
		Bool()

	tls := kingpin.Flag("tls", "Serve TLS with auto-generated self-signed certificate (~/.devd.crt)").
		Short('s').
		Default("false").
		Bool()

	noTimestamps := kingpin.Flag("notimestamps", "Disable timestamps in output").
		Short('t').
		Default("false").
		Bool()

	logTime := kingpin.Flag("logtime", "Log timing").
		Short('T').
		Default("false").
		Bool()

	upKbps := kingpin.Flag(
		"up",
		"Throttle upstream from the client to N kilobytes per second",
	).
		PlaceHolder("N").
		Short('u').
		Default("0").
		Uint()

	watch := kingpin.Flag("watch", "Watch path to trigger livereload").
		PlaceHolder("PATH").
		Short('w').
		Strings()

	cors := kingpin.Flag("crossdomain", "Set the CORS header Access-Control-Allowed: *").
		Short('X').
		Default("false").
		Bool()

	excludes := kingpin.Flag("exclude", "Glob pattern for files to exclude from livereload").
		PlaceHolder("PATTERN").
		Short('x').
		Strings()

	debug := kingpin.Flag("debug", "Debugging for devd development").
		Default("false").
		Bool()

	routes := kingpin.Arg(
		"route",
		`Routes have the following forms:
			[SUBDOMAIN]/<PATH>=<DIR>
			[SUBDOMAIN]/<PATH>=<URL>
			<DIR>
			<URL>
		`,
	).Required().Strings()

	kingpin.Version(devd.Version)

	kingpin.Parse()

	if *moddMode {
		*forceColor = true
		*noTimestamps = true
		*livereloadNaked = true
	}

	realAddr := *address
	if *allInterfaces {
		realAddr = "0.0.0.0"
	}

	var creds *devd.Credentials
	if *credspec != "" {
		var err error
		creds, err = devd.CredentialsFromSpec(*credspec)
		if err != nil {
			kingpin.Fatalf("%s", err)
			return
		}
	}

	hdrs := make(http.Header)
	if *cors {
		hdrs.Set("Access-Control-Allow-Origin", "*")
	}

	dd := devd.Devd{
		// Shaping
		Latency:  *latency,
		DownKbps: *downKbps,
		UpKbps:   *upKbps,

		AddHeaders: &hdrs,

		// Livereload
		LivereloadRoutes: *livereloadRoutes,
		Livereload:       *livereloadNaked,
		WatchPaths:       *watch,
		Excludes:         *excludes,

		Credentials: creds,
	}

	if err := dd.AddRoutes(*routes); err != nil {
		kingpin.Fatalf("%s", err)
	}

	if err := dd.AddIgnores(*ignoreLogs); err != nil {
		kingpin.Fatalf("%s", err)
	}

	logger := termlog.NewLog()
	if *quiet {
		logger.Quiet()
	}
	if *debug {
		logger.Enable("debug")
	}
	if *logTime {
		logger.Enable("timer")
	}
	if *logHeaders {
		logger.Enable("headers")
	}
	if *forceColor {
		logger.Color(true)
	}
	if *noTimestamps {
		logger.TimeFmt = ""
	}

	if *tls {
		home, err := homedir.Dir()
		if err != nil {
			kingpin.Fatalf("Could not get user's homedir: %s", err)
		}
		dst := path.Join(home, ".devd.cert")
		if _, err := os.Stat(dst); os.IsNotExist(err) {
			err := devd.GenerateCert(dst)
			if err != nil {
				kingpin.Fatalf("Could not generate cert: %s", err)
			}
		}
		*certFile = dst
	}

	err := dd.Serve(
		realAddr,
		*port,
		*certFile,
		logger,
		func(url string) {
			if *openBrowser {
				err := webbrowser.Open(url)
				if err != nil {
					kingpin.Fatalf("Failed to open browser: %s", err)
				}
			}
		},
	)
	if err != nil {
		kingpin.Fatalf("%s", err)
	}
}
示例#30
0
func gui() {
	connect()
	var c Container

	//Stack for the control
	l := ui.NewLabel("Image to start")
	imageName := ui.NewTextField()
	imageName.SetText("ipython/scipystack")
	startBtn := ui.NewButton("Launch")
	controlStack := ui.NewVerticalStack(l, imageName, startBtn)
	controlGrp := ui.NewGroup("Launch Image", controlStack)
	controlGrp.SetMargined(true)

	// Table of running containers
	table := ui.NewTable(reflect.TypeOf(c))
	openBrowserBtn := ui.NewButton("Open in browser")
	killBtn := ui.NewButton("Kill")
	manageRunningContainerGrp := ui.NewHorizontalStack(openBrowserBtn, killBtn)
	containerControlGrp := ui.NewVerticalStack(table, manageRunningContainerGrp)
	containerListGrp := ui.NewGroup("Running containers", containerControlGrp)
	containerListGrp.SetMargined(true)

	//Container info area
	selectedContainerInfo := ui.NewTextField()

	// Now make a new 2 column stack
	topStack := ui.NewHorizontalStack(controlGrp, containerListGrp)
	topStack.SetStretchy(0)
	topStack.SetStretchy(1)

	mainStack := ui.NewVerticalStack(topStack, selectedContainerInfo)
	mainStack.SetStretchy(0)
	mainStack.SetStretchy(1)

	startBtn.OnClicked(func() {
		go Start(imageName.Text())
	})

	table.OnSelected(func() {
		c := table.Selected()
		table.Lock()
		d := table.Data().(*[]Container)
		//this makes a shallow copy of the structure so that we can access elements per
		//   http://giantmachines.tumblr.com/post/51007535999/golang-struct-shallow-copy
		newC := *d
		table.Unlock()
		if c > -1 {
			fmt.Println("Getting info for container ", newC[c].Name)
			selectedContainerInfo.SetText(Info(newC[c].Name))
		}
	})

	openBrowserBtn.OnClicked(func() {
		c := table.Selected()
		table.Lock()
		d := table.Data().(*[]Container)
		//this makes a shallow copy of the structure so that we can access elements per
		//   http://giantmachines.tumblr.com/post/51007535999/golang-struct-shallow-copy
		newC := *d
		table.Unlock()
		url := fmt.Sprintf("%s.%s", newC[c].Name, os.Getenv("DOMAIN_NAME"))
		webbrowser.Open(url)
	})

	killBtn.OnClicked(func() {
		c := table.Selected()
		table.Lock()
		d := table.Data().(*[]Container)
		//this makes a shallow copy of the structure so that we can access elements per
		//   http://giantmachines.tumblr.com/post/51007535999/golang-struct-shallow-copy
		newC := *d
		table.Unlock()
		go Kill(newC[c].Name)
	})

	w = ui.NewWindow("Manage Containers on RCS", 600, 450, mainStack)
	w.SetMargined(true)

	w.OnClosing(func() bool {
		ui.Stop()
		return true
	})
	go updateTable(table)
	w.Show()

}