Last active
September 28, 2018 08:40
-
-
Save broady/c79a65cb49d7b6a56448b3345a23b3d6 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 hello | |
import ( | |
"encoding/base64" | |
"fmt" | |
"net/http" | |
"google.golang.org/appengine" | |
"golang.org/x/oauth2/google" | |
"google.golang.org/api/pubsub/v1" | |
) | |
func init() { | |
http.HandleFunc("/publish", publishHandler) | |
} | |
func publishHandler(w http.ResponseWriter, r *http.Request) { | |
ctx := appengine.NewContext(r) | |
hc, err := google.DefaultClient(ctx, pubsub.PubsubScope) | |
if err != nil { | |
handleError(w, err) | |
return | |
} | |
pubsubService, err := pubsub.New(hc) | |
if err != nil { | |
handleError(w, err) | |
return | |
http.Error(w, err.Error(), http.StatusInternalServerError) | |
} | |
msgData := []byte("test!") | |
resp, err := pubsubService.Projects.Topics.Publish( | |
"projects/YOUR-PROJECT-ID/topics/YOUR-TOPIC-ID", | |
&pubsub.PublishRequest{ | |
Messages: []*pubsub.PubsubMessage{ | |
{ | |
Data: base64.StdEncoding.EncodeToString(msgData), | |
}, | |
}, | |
}, | |
).Do() | |
if err != nil { | |
handleError(w, err) | |
return | |
} | |
fmt.Fprintf(w, "ok! id: %q", resp.MessageIds[0]) | |
} | |
func handleError(w http.ResponseWriter, err error) { | |
// TODO(you): log the error, etc. | |
http.Error(w, err.Error(), http.StatusInternalServerError) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment