server.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. // A simple server that is alive for 10 seconds, then reports unhealthy for
  14. // the rest of its (hopefully) short existence.
  15. package main
  16. import (
  17. "fmt"
  18. "log"
  19. "net/http"
  20. "net/url"
  21. "time"
  22. )
  23. func main() {
  24. started := time.Now()
  25. http.HandleFunc("/started", func(w http.ResponseWriter, r *http.Request) {
  26. w.WriteHeader(200)
  27. data := (time.Since(started)).String()
  28. w.Write([]byte(data))
  29. })
  30. http.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
  31. duration := time.Since(started)
  32. if duration.Seconds() > 10 {
  33. w.WriteHeader(500)
  34. w.Write([]byte(fmt.Sprintf("error: %v", duration.Seconds())))
  35. } else {
  36. w.WriteHeader(200)
  37. w.Write([]byte("ok"))
  38. }
  39. })
  40. http.HandleFunc("/redirect", func(w http.ResponseWriter, r *http.Request) {
  41. loc, err := url.QueryUnescape(r.URL.Query().Get("loc"))
  42. if err != nil {
  43. http.Error(w, fmt.Sprintf("invalid redirect: %q", r.URL.Query().Get("loc")), http.StatusBadRequest)
  44. return
  45. }
  46. http.Redirect(w, r, loc, http.StatusFound)
  47. })
  48. log.Fatal(http.ListenAndServe(":8080", nil))
  49. }