Created
December 22, 2022 12:38
-
-
Save vcx/93cfba49cc3efbf19b5848c978cb05df to your computer and use it in GitHub Desktop.
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
package main | |
import ( | |
"context" | |
"fmt" | |
"io/ioutil" | |
"log" | |
"net/http" | |
"os" | |
"cloud.google.com/go/pubsub" | |
) | |
var topic *pubsub.Topic | |
func main() { | |
ctx := context.Background() | |
client, err := pubsub.NewClient(ctx, mustGetenv("GOOGLE_CLOUD_PROJECT")) | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer client.Close() | |
topicName := mustGetenv("PUBSUB_TOPIC") | |
topic = client.Topic(topicName) | |
http.HandleFunc("/pubsub/publish", publishHandler) | |
port := os.Getenv("PORT") | |
if port == "" { | |
port = "8080" | |
log.Printf("Defaulting to port %s", port) | |
} | |
log.Printf("Listening on port %s", port) | |
if err := http.ListenAndServe(":"+port, nil); err != nil { | |
log.Fatal(err) | |
} | |
} | |
func mustGetenv(k string) string { | |
v := os.Getenv(k) | |
if v == "" { | |
log.Fatalf("%s environment variable not set.", k) | |
} | |
return v | |
} | |
func publishHandler(w http.ResponseWriter, req *http.Request) { | |
ctx := context.Background() | |
bytesFromRequest, _ := ioutil.ReadAll(req.Body) | |
msg := &pubsub.Message{ | |
Data: []byte(bytesFromRequest), | |
} | |
if _, err := topic.Publish(ctx, msg).Get(ctx); err != nil { | |
http.Error(w, fmt.Sprintf("Could not publish message: %v", err), 500) | |
return | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment