channel.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // 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. Package channel implements the server side of App Engine's Channel API.
  6. Create creates a new channel associated with the given clientID,
  7. which must be unique to the client that will use the returned token.
  8. token, err := channel.Create(c, "player1")
  9. if err != nil {
  10. // handle error
  11. }
  12. // return token to the client in an HTTP response
  13. Send sends a message to the client over the channel identified by clientID.
  14. channel.Send(c, "player1", "Game over!")
  15. */
  16. package channel // import "google.golang.org/appengine/channel"
  17. import (
  18. "encoding/json"
  19. "golang.org/x/net/context"
  20. "google.golang.org/appengine"
  21. "google.golang.org/appengine/internal"
  22. basepb "google.golang.org/appengine/internal/base"
  23. pb "google.golang.org/appengine/internal/channel"
  24. )
  25. // Create creates a channel and returns a token for use by the client.
  26. // The clientID is an application-provided string used to identify the client.
  27. func Create(c context.Context, clientID string) (token string, err error) {
  28. req := &pb.CreateChannelRequest{
  29. ApplicationKey: &clientID,
  30. }
  31. resp := &pb.CreateChannelResponse{}
  32. err = internal.Call(c, service, "CreateChannel", req, resp)
  33. token = resp.GetToken()
  34. return token, remapError(err)
  35. }
  36. // Send sends a message on the channel associated with clientID.
  37. func Send(c context.Context, clientID, message string) error {
  38. req := &pb.SendMessageRequest{
  39. ApplicationKey: &clientID,
  40. Message: &message,
  41. }
  42. resp := &basepb.VoidProto{}
  43. return remapError(internal.Call(c, service, "SendChannelMessage", req, resp))
  44. }
  45. // SendJSON is a helper function that sends a JSON-encoded value
  46. // on the channel associated with clientID.
  47. func SendJSON(c context.Context, clientID string, value interface{}) error {
  48. m, err := json.Marshal(value)
  49. if err != nil {
  50. return err
  51. }
  52. return Send(c, clientID, string(m))
  53. }
  54. // remapError fixes any APIError referencing "xmpp" into one referencing "channel".
  55. func remapError(err error) error {
  56. if e, ok := err.(*internal.APIError); ok {
  57. if e.Service == "xmpp" {
  58. e.Service = "channel"
  59. }
  60. }
  61. return err
  62. }
  63. var service = "xmpp" // prod
  64. func init() {
  65. if appengine.IsDevAppServer() {
  66. service = "channel" // dev
  67. }
  68. internal.RegisterErrorCodeMap("channel", pb.ChannelServiceError_ErrorCode_name)
  69. }