sslobodr | d046be8 | 2019-01-16 10:02:22 -0500 | [diff] [blame] | 1 | // Copyright 2011 Google Inc. All rights reserved. |
| 2 | // Use of this source code is governed by the Apache 2.0 |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | // +build !appengine |
| 6 | |
| 7 | package internal |
| 8 | |
| 9 | import ( |
| 10 | "io" |
| 11 | "log" |
| 12 | "net/http" |
| 13 | "net/url" |
| 14 | "os" |
| 15 | "path/filepath" |
| 16 | "runtime" |
| 17 | ) |
| 18 | |
| 19 | func Main() { |
| 20 | MainPath = filepath.Dir(findMainPath()) |
| 21 | installHealthChecker(http.DefaultServeMux) |
| 22 | |
| 23 | port := "8080" |
| 24 | if s := os.Getenv("PORT"); s != "" { |
| 25 | port = s |
| 26 | } |
| 27 | |
| 28 | host := "" |
| 29 | if IsDevAppServer() { |
| 30 | host = "127.0.0.1" |
| 31 | } |
| 32 | if err := http.ListenAndServe(host+":"+port, http.HandlerFunc(handleHTTP)); err != nil { |
| 33 | log.Fatalf("http.ListenAndServe: %v", err) |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | // Find the path to package main by looking at the root Caller. |
| 38 | func findMainPath() string { |
| 39 | pc := make([]uintptr, 100) |
| 40 | n := runtime.Callers(2, pc) |
| 41 | frames := runtime.CallersFrames(pc[:n]) |
| 42 | for { |
| 43 | frame, more := frames.Next() |
| 44 | // Tests won't have package main, instead they have testing.tRunner |
| 45 | if frame.Function == "main.main" || frame.Function == "testing.tRunner" { |
| 46 | return frame.File |
| 47 | } |
| 48 | if !more { |
| 49 | break |
| 50 | } |
| 51 | } |
| 52 | return "" |
| 53 | } |
| 54 | |
| 55 | func installHealthChecker(mux *http.ServeMux) { |
| 56 | // If no health check handler has been installed by this point, add a trivial one. |
| 57 | const healthPath = "/_ah/health" |
| 58 | hreq := &http.Request{ |
| 59 | Method: "GET", |
| 60 | URL: &url.URL{ |
| 61 | Path: healthPath, |
| 62 | }, |
| 63 | } |
| 64 | if _, pat := mux.Handler(hreq); pat != healthPath { |
| 65 | mux.HandleFunc(healthPath, func(w http.ResponseWriter, r *http.Request) { |
| 66 | io.WriteString(w, "ok") |
| 67 | }) |
| 68 | } |
| 69 | } |