blob: 5782fffcfb40dbcb6c7206afc964ee191c3f518a [file] [log] [blame]
David Symondsbbcdc9d2014-02-19 11:36:36 +11001// Copyright 2011 Google Inc. All rights reserved.
2// Use of this source code is governed by the Apache 2.0
3// license that can be found in the LICENSE file.
4
5/*
6Package channel implements the server side of App Engine's Channel API.
7
8Create creates a new channel associated with the given clientID,
9which must be unique to the client that will use the returned token.
10
11token, err := channel.Create(c, "player1")
12if err != nil {
13// handle error
14}
15// return token to the client in an HTTP response
16
17Send sends a message to the client over the channel identified by clientID.
18
19channel.Send(c, "player1", "Game over!")
20*/
Dave Dayd510d6e2014-11-13 17:12:34 +110021package channel // import "google.golang.org/appengine/channel"
David Symondsbbcdc9d2014-02-19 11:36:36 +110022
23import (
24"encoding/json"
25
26"google.golang.org/appengine"
27"google.golang.org/appengine/internal"
28basepb "google.golang.org/appengine/internal/base"
29pb "google.golang.org/appengine/internal/channel"
30)
31
32// Create creates a channel and returns a token for use by the client.
33// The clientID is an application-provided string used to identify the client.
34func Create(c appengine.Context, clientID string) (token string, err error) {
35req := &pb.CreateChannelRequest{
36ApplicationKey: &clientID,
37}
38resp := &pb.CreateChannelResponse{}
39err = c.Call(service, "CreateChannel", req, resp, nil)
40token = resp.GetToken()
41return token, remapError(err)
42}
43
44// Send sends a message on the channel associated with clientID.
45func Send(c appengine.Context, clientID, message string) error {
46req := &pb.SendMessageRequest{
47ApplicationKey: &clientID,
48Message: &message,
49}
50resp := &basepb.VoidProto{}
51return remapError(c.Call(service, "SendChannelMessage", req, resp, nil))
52}
53
54// SendJSON is a helper function that sends a JSON-encoded value
55// on the channel associated with clientID.
56func SendJSON(c appengine.Context, clientID string, value interface{}) error {
57m, err := json.Marshal(value)
58if err != nil {
59return err
60}
61return Send(c, clientID, string(m))
62}
63
64// remapError fixes any APIError referencing "xmpp" into one referencing "channel".
65func remapError(err error) error {
66if e, ok := err.(*internal.APIError); ok {
67if e.Service == "xmpp" {
68e.Service = "channel"
69}
70}
71return err
72}
73
74var service = "xmpp" // prod
75
76func init() {
77if appengine.IsDevAppServer() {
78service = "channel" // dev
79}
80internal.RegisterErrorCodeMap("channel", pb.ChannelServiceError_ErrorCode_name)
81}