...
1
16
17
18 package testwebserver
19
20 import (
21 "fmt"
22 "log"
23 "net/http"
24
25 "github.com/spf13/cobra"
26 )
27
28
29 var CmdTestWebserver = &cobra.Command{
30 Use: "test-webserver",
31 Short: "Starts a simple HTTP fileserver",
32 Long: "Starts a simple HTTP fileserver on the given --port, which serves any file specified in the URL path, if it exists.",
33 Args: cobra.MaximumNArgs(0),
34 Run: main,
35 }
36
37 var (
38 port int
39 )
40
41 func init() {
42 CmdTestWebserver.Flags().IntVar(&port, "port", 80, "Port number.")
43 }
44
45 func main(cmd *cobra.Command, args []string) {
46 fs := http.StripPrefix("/", http.FileServer(http.Dir("/")))
47
48 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
49 w.Header().Set("Cache-Control", "private")
50
51 w.Header().Set("Access-Control-Allow-Origin", "*")
52 w.Header().Set("Access-Control-Allow-Credentials", "true")
53 w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
54 w.Header().Set("Access-Control-Allow-Headers", "DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,Cache-Control,Content-Type")
55
56 r.Header.Del("If-Modified-Since")
57 fs.ServeHTTP(w, r)
58 })
59
60 go log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", port), nil))
61
62 select {}
63 }
64
View as plain text