test-webserver.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. // Package testwebserver offers a tiny web server that serves a static file.
  14. package testwebserver
  15. import (
  16. "fmt"
  17. "log"
  18. "net/http"
  19. "github.com/spf13/cobra"
  20. )
  21. // CmdTestWebserver is used by agnhost Cobra.
  22. var CmdTestWebserver = &cobra.Command{
  23. Use: "test-webserver",
  24. Short: "Starts a simple HTTP fileserver",
  25. Long: "Starts a simple HTTP fileserver on the given --port, which serves any file specified in the URL path, if it exists.",
  26. Args: cobra.MaximumNArgs(0),
  27. Run: main,
  28. }
  29. var (
  30. port int
  31. )
  32. func init() {
  33. CmdTestWebserver.Flags().IntVar(&port, "port", 80, "Port number.")
  34. }
  35. func main(cmd *cobra.Command, args []string) {
  36. fs := http.StripPrefix("/", http.FileServer(http.Dir("/")))
  37. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  38. w.Header().Set("Cache-Control", "private")
  39. // Needed for local proxy to Kubernetes API server to work.
  40. w.Header().Set("Access-Control-Allow-Origin", "*")
  41. w.Header().Set("Access-Control-Allow-Credentials", "true")
  42. w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
  43. w.Header().Set("Access-Control-Allow-Headers", "DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,Cache-Control,Content-Type")
  44. // Disable If-Modified-Since so update-demo isn't broken by 304s
  45. r.Header.Del("If-Modified-Since")
  46. fs.ServeHTTP(w, r)
  47. })
  48. go log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", port), nil))
  49. select {}
  50. }