main.go 1.73 KB
Newer Older
Erin Krengel's avatar
Erin Krengel committed
1
2
3
package main

import (
Erin Krengel's avatar
wip    
Erin Krengel committed
4
5
	"context"
	"log"
Erin Krengel's avatar
Erin Krengel committed
6
	"net/http"
Erin Krengel's avatar
wip    
Erin Krengel committed
7
8
9
	"os"

	"cloud.google.com/go/pubsub"
10
11
	"cloud.google.com/go/storage"
	"gitlab.com/rocore/demo-app/pkg/handlers"
Erin Krengel's avatar
Erin Krengel committed
12
13
14
)

func main() {
Erin Krengel's avatar
wip    
Erin Krengel committed
15
16
	ctx := context.Background()

Erin Krengel's avatar
Erin Krengel committed
17
18
19
	// Get configuration from environment variables. These are
	// required configuration values, so we will use an helper
	// function get the values and exit if the value is not set.
20
21
22
	project := getConfigurationValue("PROJECT")
	topicName := getConfigurationValue("TOPIC")
	bucketName := getConfigurationValue("BUCKET")
Erin Krengel's avatar
wip    
Erin Krengel committed
23

Erin Krengel's avatar
Erin Krengel committed
24
25
26
	// Set up the GCP resources we need.
	topic := getPubSubTopic(ctx, project, topicName)
	bkt := getBucketHandle(ctx, bucketName)
Erin Krengel's avatar
wip    
Erin Krengel committed
27

Erin Krengel's avatar
Erin Krengel committed
28
29
	// Create two handlers. One is a basic health endpoint and
	// the other is the handler we will be testing.
30
31
32
	mux := http.NewServeMux()
	mux.HandleFunc("/ping", handlers.PingHandler)
	mux.HandleFunc("/message", handlers.MessageHandler(topic, bkt))
Sean Holung's avatar
Sean Holung committed
33

34
35
36
37
	// Start server.
	log.Println("starting server")
	if err := http.ListenAndServe(":8080", mux); err != nil {
		log.Fatalf("error listening on localhost:8080: %v", err)
Erin Krengel's avatar
wip    
Erin Krengel committed
38
	}
Erin Krengel's avatar
Erin Krengel committed
39
}
40

41
42
43
44
func getConfigurationValue(envVar string) string {
	value := os.Getenv(envVar)
	if value == "" {
		log.Fatalf("%s not set", envVar)
45
	}
46
47
	log.Printf("%s: %s", envVar, value)
	return value
48
}
Erin Krengel's avatar
Erin Krengel committed
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64

func getPubSubTopic(ctx context.Context, project, topicName string) *pubsub.Topic {
	pubsubClient, err := pubsub.NewClient(ctx, project)
	if err != nil {
		log.Fatalf("cannot create pubsub client: %v", err)
	}
	return pubsubClient.Topic(topicName)
}

func getBucketHandle(ctx context.Context, bucketName string) *storage.BucketHandle {
	storageClient, err := storage.NewClient(ctx)
	if err != nil {
		log.Fatalf("cannot create storage client: %v", err)
	}
	return storageClient.Bucket(bucketName)
}