From 4c68c7240f900362b8f50a977929037b35d901dd Mon Sep 17 00:00:00 2001 From: Maxim Slipenko Date: Fri, 19 Aug 2022 06:17:28 +0300 Subject: [PATCH] Add index page to the development server (#146) * Add index page to dev server * Add target=_blank to packwiz-installer link * Improve sentence about packwiz-installer Co-authored-by: comp500 --- cmd/serve-templates/index.html | 44 ++++++++++++++++++++++++++++++++++ cmd/serve.go | 23 +++++++++++++++++- 2 files changed, 66 insertions(+), 1 deletion(-) create mode 100644 cmd/serve-templates/index.html diff --git a/cmd/serve-templates/index.html b/cmd/serve-templates/index.html new file mode 100644 index 0000000..791e6c8 --- /dev/null +++ b/cmd/serve-templates/index.html @@ -0,0 +1,44 @@ + + + + + + + packwiz development server + + + +

+ It works! Packwiz development server is running! +

+

+ Use packwiz-installer to install the pack from this HTTP server - works best with MultiMC/PolyMC/ATLauncher, or standalone for servers. +

+

+ Your pack.toml is hosted at http://localhost:{{.Port}}/pack.toml. +

+
+

+ packwiz +

+ + diff --git a/cmd/serve.go b/cmd/serve.go index e8da099..ced7567 100644 --- a/cmd/serve.go +++ b/cmd/serve.go @@ -1,7 +1,10 @@ package cmd import ( + "bytes" + _ "embed" "fmt" + "html/template" "io" "net/http" "os" @@ -18,6 +21,9 @@ import ( var refreshMutex sync.RWMutex +//go:embed serve-templates/index.html +var indexPage string + // serveCmd represents the serve command var serveCmd = &cobra.Command{ Use: "serve", @@ -26,6 +32,8 @@ var serveCmd = &cobra.Command{ Aliases: []string{"server"}, Args: cobra.NoArgs, Run: func(cmd *cobra.Command, args []string) { + port := strconv.Itoa(viper.GetInt("serve.port")) + if viper.GetBool("serve.basic") { http.Handle("/", http.FileServer(http.Dir("."))) } else { @@ -43,7 +51,21 @@ var serveCmd = &cobra.Command{ indexPath := filepath.Join(filepath.Dir(viper.GetString("pack-file")), filepath.FromSlash(pack.Index.File)) indexDir := filepath.Dir(indexPath) + t, err := template.New("index-page").Parse(indexPage) + if err != nil { + fmt.Println(err) + os.Exit(1) + } + + indexPageBuf := new(bytes.Buffer) + t.Execute(indexPageBuf, struct{ Port string }{Port: port}) + http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { + if req.URL.Path == "/" { + _, _ = w.Write(indexPageBuf.Bytes()) + return + } + urlPath := strings.TrimPrefix(path.Clean("/"+strings.TrimPrefix(req.URL.Path, "/")), "/") indexRelPath, err := filepath.Rel(indexDir, filepath.FromSlash(urlPath)) if err != nil { @@ -144,7 +166,6 @@ var serveCmd = &cobra.Command{ }) } - port := strconv.Itoa(viper.GetInt("serve.port")) fmt.Println("Running on port " + port) err := http.ListenAndServe(":"+port, nil) if err != nil {