porter.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. Copyright 2015 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. // A tiny binary for testing ports.
  14. //
  15. // Reads env vars; for every var of the form SERVE_PORT_X, where X is a valid
  16. // port number, porter starts an HTTP server which serves the env var's value
  17. // in response to any query.
  18. package main
  19. import (
  20. "fmt"
  21. "log"
  22. "net/http"
  23. "os"
  24. "strings"
  25. )
  26. const prefix = "SERVE_PORT_"
  27. const tlsPrefix = "SERVE_TLS_PORT_"
  28. func main() {
  29. for _, vk := range os.Environ() {
  30. // Put everything before the first = sign in parts[0], and
  31. // everything else in parts[1] (even if there are multiple =
  32. // characters).
  33. parts := strings.SplitN(vk, "=", 2)
  34. key := parts[0]
  35. value := parts[1]
  36. if strings.HasPrefix(key, prefix) {
  37. port := strings.TrimPrefix(key, prefix)
  38. go servePort(port, value)
  39. }
  40. if strings.HasPrefix(key, tlsPrefix) {
  41. port := strings.TrimPrefix(key, tlsPrefix)
  42. go serveTLSPort(port, value)
  43. }
  44. }
  45. select {}
  46. }
  47. func servePort(port, value string) {
  48. s := &http.Server{
  49. Addr: "0.0.0.0:" + port,
  50. Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  51. fmt.Fprint(w, value)
  52. }),
  53. }
  54. log.Printf("server on port %q failed: %v", port, s.ListenAndServe())
  55. }
  56. func serveTLSPort(port, value string) {
  57. s := &http.Server{
  58. Addr: "0.0.0.0:" + port,
  59. Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  60. fmt.Fprint(w, value)
  61. }),
  62. }
  63. certFile := os.Getenv("CERT_FILE")
  64. if len(certFile) == 0 {
  65. certFile = "localhost.crt"
  66. }
  67. keyFile := os.Getenv("KEY_FILE")
  68. if len(keyFile) == 0 {
  69. keyFile = "localhost.key"
  70. }
  71. log.Printf("tls server on port %q with certFile=%q, keyFile=%q failed: %v", port, certFile, keyFile, s.ListenAndServeTLS(certFile, keyFile))
  72. }