webui.go

 1package commands
 2
 3import (
 4	"fmt"
 5	"github.com/MichaelMure/git-bug/graphql"
 6	"github.com/MichaelMure/git-bug/webui"
 7	"github.com/gorilla/mux"
 8	"github.com/phayes/freeport"
 9	"github.com/skratchdot/open-golang/open"
10	"github.com/spf13/cobra"
11	"log"
12	"net/http"
13)
14
15var port int
16
17func runWebUI(cmd *cobra.Command, args []string) error {
18	if port == 0 {
19		var err error
20		port, err = freeport.GetFreePort()
21		if err != nil {
22			log.Fatal(err)
23		}
24	}
25
26	addr := fmt.Sprintf("127.0.0.1:%d", port)
27	webUiAddr := fmt.Sprintf("http://%s", addr)
28
29	fmt.Printf("Web UI available at %s\n", webUiAddr)
30
31	graphqlHandler, err := graphql.NewHandler(repo)
32
33	if err != nil {
34		return err
35	}
36
37	router := mux.NewRouter()
38
39	// Routes
40	router.Path("/graphql").Handler(graphqlHandler)
41	router.PathPrefix("/").Handler(http.FileServer(webui.WebUIAssets))
42
43	open.Run(webUiAddr)
44
45	log.Fatal(http.ListenAndServe(addr, router))
46
47	return nil
48}
49
50var webUICmd = &cobra.Command{
51	Use:   "webui",
52	Short: "Launch the web UI",
53	RunE:  runWebUI,
54}
55
56func init() {
57	RootCmd.AddCommand(webUICmd)
58	webUICmd.Flags().IntVarP(&port, "port", "p", 0, "Port to listen to")
59}