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