Skip to content

Commit b18e064

Browse files
committed
add support for single file
1 parent 8465b7d commit b18e064

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

cmd/start.go

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"fmt"
55
"net/http"
66
"os"
7+
"path/filepath"
78
"strconv"
89

910
"github.com/mdp/qrterminal/v3"
@@ -18,7 +19,7 @@ var showQrCode bool
1819
func init() {
1920
rootCmd.AddCommand(startCmd)
2021
startCmd.Flags().StringVarP(&folder, "directory", "d", "", "Path of the web folder")
21-
startCmd.Flags().StringVarP(&filePath, "file", "f", "", "Path of a file (for hosting a single file)")
22+
startCmd.Flags().StringVarP(&filePath, "file", "f", "", "Path of a file (for sharing a single file)")
2223
startCmd.Flags().BoolVar(&showQrCode, "qrcode", false, "Show QR code of server URL")
2324
startCmd.Flags().IntVarP(&port, "port", "p", 8080, "Port number")
2425
}
@@ -30,18 +31,22 @@ var startCmd = &cobra.Command{
3031
Args: cobra.MinimumNArgs(0),
3132

3233
Run: func(cmd *cobra.Command, args []string) {
33-
3434
if filePath != "" {
35+
http.HandleFunc("/", func(res http.ResponseWriter, req *http.Request) {
36+
res.Header().Add("Content-Disposition", "attachment;filename=\""+filepath.Base(filePath)+"\"")
37+
http.ServeFile(res, req, filePath)
38+
})
39+
} else {
40+
fileHandler := http.FileServer(http.Dir(folder))
41+
http.Handle("/", fileHandler)
3542
}
3643

37-
fileHandler := http.FileServer(http.Dir(folder))
38-
3944
ips, err := externalIPs()
4045
if err != nil {
4146
panic(err)
4247
}
4348

44-
fmt.Println("Http server is running at: ")
49+
fmt.Println("Http server is running at:")
4550
fmt.Println("http://localhost:" + strconv.Itoa(port))
4651
for _, ip := range ips {
4752
url := "http://" + ip + ":" + strconv.Itoa(port)
@@ -51,7 +56,7 @@ var startCmd = &cobra.Command{
5156
}
5257
}
5358

54-
err = http.ListenAndServe(fmt.Sprint(":", port), fileHandler)
59+
err = http.ListenAndServe(fmt.Sprint(":", port), nil)
5560
fmt.Println("bye~")
5661
if err != nil {
5762
panic(err)

0 commit comments

Comments
 (0)