|
package main |
|
|
|
import ( |
|
"fmt" |
|
"io" |
|
"log" |
|
"net/http" |
|
"os" |
|
|
|
"cloud.google.com/go/compute/metadata" |
|
) |
|
|
|
func main() { |
|
mux := http.NewServeMux() |
|
serviceName := os.Getenv("K_SERVICE") |
|
mux.HandleFunc("/call", func(w http.ResponseWriter, r *http.Request) { |
|
destination := r.URL.Query().Get("destination") |
|
|
|
idToken, err := metadata.Get("instance/service-accounts/default/identity?audience=" + destination) |
|
if err != nil { |
|
http.Error(w, fmt.Sprintf("caller=%s: %s", serviceName, err.Error()), http.StatusInternalServerError) |
|
return |
|
} |
|
|
|
req, _ := http.NewRequest(http.MethodGet, destination, nil) |
|
req.Header.Set("Authorization", "Bearer "+idToken) |
|
resp, err := http.DefaultClient.Do(req) |
|
if err != nil { |
|
http.Error(w, fmt.Sprintf("caller=%s: %s", serviceName, err.Error()), http.StatusInternalServerError) |
|
return |
|
} |
|
if resp.StatusCode != http.StatusOK { |
|
http.Error(w, fmt.Sprintf("caller=%s: callee returns: %d\n", serviceName, resp.StatusCode), http.StatusInternalServerError) |
|
io.Copy(w, resp.Body) |
|
return |
|
} |
|
defer resp.Body.Close() |
|
|
|
fmt.Fprintf(w, "caller=%s: ", serviceName) |
|
io.Copy(w, resp.Body) |
|
}) |
|
mux.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) { |
|
fmt.Fprintf(w, "callee=%s", serviceName) |
|
}) |
|
listenAndServe(mux) |
|
} |
|
|
|
func listenAndServe(handler http.Handler) { |
|
port := "8080" |
|
if s := os.Getenv("PORT"); s != "" { |
|
port = s |
|
} |
|
|
|
if err := http.ListenAndServe(":"+port, handler); err != nil { |
|
log.Fatalf("http.listenAndServe: %v", err) |
|
} |
|
} |