Last active
January 30, 2024 06:43
-
-
Save wjkoh/8eb4f55a6b4038f6e6c94e922585776b to your computer and use it in GitHub Desktop.
Google Cloud: Get Cloud Run URL in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// $ gcloud run deploy --source . | |
package main | |
import ( | |
"context" | |
"fmt" | |
"log" | |
"net/http" | |
"os" | |
"strings" | |
"errors" | |
"cloud.google.com/go/compute/metadata" | |
"google.golang.org/api/option" | |
"google.golang.org/api/run/v1" | |
) | |
func main() { | |
log.Print("starting server...") | |
http.HandleFunc("/", handler) | |
// Determine port for HTTP service. | |
port := os.Getenv("PORT") | |
if port == "" { | |
port = "8080" | |
log.Printf("defaulting to port %s", port) | |
} | |
// Start HTTP server. | |
log.Printf("listening on port %s", port) | |
if err := http.ListenAndServe(":"+port, nil); err != nil { | |
log.Fatal(err) | |
} | |
} | |
func getCloudRunUrl(ctx context.Context) (string, error) { | |
c := metadata.NewClient(nil) | |
r, err := c.Get("instance/region") | |
if err != nil { | |
return "", err | |
} | |
// projects/{project_number}/regions/us-central1 | |
rs := strings.Split(r, "/") | |
projectNumber := rs[1] | |
region := rs[3] | |
service := os.Getenv("K_SERVICE") | |
if service == "" { | |
return "", errors.New("K_SERVICE not set") | |
} | |
runService, err := run.NewService(ctx, | |
option.WithEndpoint(fmt.Sprintf("https://%s-run.googleapis.com", region))) | |
if err != nil { | |
return "", err | |
} | |
name := fmt.Sprintf("namespaces/%s/services/%s", projectNumber, service) | |
p, err := runService.Namespaces.Services.Get(name).Do() | |
if err != nil { | |
return "", err | |
} | |
return p.Status.Url, nil | |
} | |
func handler(w http.ResponseWriter, r *http.Request) { | |
url, err := getCloudRunUrl(r.Context()) | |
if err != nil { | |
http.Error(w, err.Error(), http.StatusInternalServerError) | |
return | |
} | |
fmt.Fprintf(w, "Cloud Run URL: %s\n", url) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment