aboutsummaryrefslogtreecommitdiffstats
path: root/commands/webui.go
blob: b31013adeb9afac94844002cb8dc90c667c8561d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package commands

import (
	"fmt"
	"github.com/MichaelMure/git-bug/graphql"
	"github.com/MichaelMure/git-bug/webui"
	"github.com/gorilla/mux"
	"github.com/phayes/freeport"
	"github.com/skratchdot/open-golang/open"
	"github.com/spf13/cobra"
	"github.com/vektah/gqlgen/handler"
	"log"
	"net/http"
)

var port int

func runWebUI(cmd *cobra.Command, args []string) error {
	if port == 0 {
		var err error
		port, err = freeport.GetFreePort()
		if err != nil {
			return err
		}
	}

	addr := fmt.Sprintf("127.0.0.1:%d", port)
	webUiAddr := fmt.Sprintf("http://%s", addr)

	fmt.Printf("Web UI: %s\n", webUiAddr)
	fmt.Printf("Graphql API: http://%s/graphql\n", addr)
	fmt.Printf("Graphql Playground: http://%s/playground\n", addr)

	router := mux.NewRouter()

	// Routes
	router.Path("/playground").Handler(handler.Playground("git-bug", "/graphql"))
	router.Path("/graphql").Handler(graphql.NewHandler(repo))
	router.PathPrefix("/").Handler(http.FileServer(webui.WebUIAssets))

	open.Run(webUiAddr)

	log.Fatal(http.ListenAndServe(addr, router))

	return nil
}

var webUICmd = &cobra.Command{
	Use:   "webui",
	Short: "Launch the web UI",
	RunE:  runWebUI,
}

func init() {
	RootCmd.AddCommand(webUICmd)
	webUICmd.Flags().IntVarP(&port, "port", "p", 0, "Port to listen to")
}