Permalink
Browse files

Reorg into a couple of subpackages.

  • Loading branch information...
cespare committed Jan 10, 2013
1 parent 0be9ead commit c22692c558fea2761e66571d525781e1c22a1a20
Showing with 137 additions and 98 deletions.
  1. +24 −98 pratbot.go
  2. +64 −0 src/authutil/authutil.go
  3. +49 −0 src/connection/connection.go
View
@@ -1,129 +1,55 @@
package main
import (
- "bytes"
- "code.google.com/p/go.net/websocket"
- "crypto/sha256"
- "crypto/tls"
- "encoding/base64"
- "encoding/json"
+ "log"
"flag"
"fmt"
- "log"
"os"
- "sort"
- "strconv"
- "strings"
- "time"
-)
-const (
- server = "pratchat.com:443"
+ "connection"
)
var (
- apikey = flag.String("apikey", "", "Prat API key")
+ server = flag.String("server", "", "Prat server")
+ apiKey = flag.String("apikey", "", "Prat API key")
secret = flag.String("secret", "", "Prat API secret")
- ws *websocket.Conn
+ tls = flag.Bool("tls", true, "Connect via TLS")
+ port = flag.Int("port", 0, "Port (defaults to 80/443)")
+
+ addrString string
)
func init() {
flag.Parse()
- if *apikey == "" || *secret == "" {
- flag.Usage()
- os.Exit(-1)
- }
-}
-
-type ByPair [][]string
-
-func (p ByPair) Len() int { return len(p) }
-func (p ByPair) Less(i, j int) bool { return p[i][0] < p[j][0] }
-func (p ByPair) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
-
-func prepareQueryString(params map[string]string, exclude []string) string {
- var result [][]string
- for k, v := range params {
- excluded := false
- for _, e := range exclude {
- if k == e {
- excluded = true
- break
- }
+ for _, f := range []string{*server, *apiKey, *secret} {
+ if f == "" {
+ flag.Usage()
+ os.Exit(-1)
}
- if !excluded {
- result = append(result, []string{k, v})
- }
- }
- sort.Sort(ByPair(result))
- var pairs []string
- for _, p := range result {
- pairs = append(pairs, strings.Join(p, "="))
}
- return strings.Join(pairs, "")
-}
-func Signature(secret, method, path, body string, params map[string]string) string {
- exclude := []string{"signature"}
- signature := secret + strings.ToUpper(method) + path + prepareQueryString(params, exclude) + body
- h := sha256.New()
- h.Write([]byte(signature))
- var buf bytes.Buffer
- enc := base64.NewEncoder(base64.URLEncoding, &buf)
- enc.Write(h.Sum(nil))
- enc.Close()
- return buf.String()[:43]
-}
-
-func ConnectionString() string {
- expires := int(time.Now().Unix() + 300)
- params := map[string]string{"api_key": *apikey, "expires": strconv.Itoa(expires)}
- signature := Signature(*secret, "GET", "/eventhub", "", params)
- params["signature"] = signature
- var kv []string
- for k, v := range params {
- kv = append(kv, k+"="+v)
+ if *port == 0 {
+ if *tls {
+ *port = 443
+ } else {
+ *port = 80
+ }
}
- return fmt.Sprintf("wss://%s/eventhub?%s", server, strings.Join(kv, "&"))
-}
-
-type Message struct {
- Action string `json:"action"`
- Data map[string]string `json:"data"`
-}
-func SendMessage(channel, msg string) error {
- data := map[string]string{"channel": channel, "message": msg}
- m := &Message{
- Action: "publish_message",
- Data: data,
+ proto := "ws"
+ if *tls {
+ proto = "wss"
}
- j, err := json.Marshal(m)
- if err != nil {
- return err
- }
- if _, err := ws.Write(j); err != nil {
- return err
- }
- return nil
+ addrString = fmt.Sprintf("%s://%s:%d", proto, *server, *port)
}
func main() {
- origin := "http://localhost/"
- var err error
- config, err := websocket.NewConfig(ConnectionString(), origin)
- if err != nil {
- log.Fatal(err)
- }
- // Ignore certs for now
- config.TlsConfig = &tls.Config{InsecureSkipVerify: true}
- ws, err = websocket.DialConfig(config)
+ conn, err := connection.Connect(addrString, *apiKey, *secret)
if err != nil {
log.Fatal(err)
}
- fmt.Println("Connected.")
- if SendMessage("general", "Hello from bot!") != nil {
+ if conn.SendMessage("general", "Hello from bot!") != nil {
log.Fatal(err)
}
}
View
@@ -0,0 +1,64 @@
+package authutil
+
+import (
+ "bytes"
+ "crypto/sha256"
+ "encoding/base64"
+ "fmt"
+ "sort"
+ "strconv"
+ "strings"
+ "time"
+)
+
+type ByPair [][]string
+
+func (p ByPair) Len() int { return len(p) }
+func (p ByPair) Less(i, j int) bool { return p[i][0] < p[j][0] }
+func (p ByPair) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
+
+func prepareQueryString(params map[string]string, exclude []string) string {
+ var result [][]string
+ for k, v := range params {
+ excluded := false
+ for _, e := range exclude {
+ if k == e {
+ excluded = true
+ break
+ }
+ }
+ if !excluded {
+ result = append(result, []string{k, v})
+ }
+ }
+ sort.Sort(ByPair(result))
+ var pairs []string
+ for _, p := range result {
+ pairs = append(pairs, strings.Join(p, "="))
+ }
+ return strings.Join(pairs, "")
+}
+
+func Signature(secret, method, path, body string, params map[string]string) string {
+ exclude := []string{"signature"}
+ signature := secret + strings.ToUpper(method) + path + prepareQueryString(params, exclude) + body
+ h := sha256.New()
+ h.Write([]byte(signature))
+ var buf bytes.Buffer
+ enc := base64.NewEncoder(base64.URLEncoding, &buf)
+ enc.Write(h.Sum(nil))
+ enc.Close()
+ return buf.String()[:43]
+}
+
+func ConnectionString(addrString, apiKey, secret string) string {
+ expires := int(time.Now().Unix() + 300)
+ params := map[string]string{"api_key": apiKey, "expires": strconv.Itoa(expires)}
+ signature := Signature(secret, "GET", "/eventhub", "", params)
+ params["signature"] = signature
+ var kv []string
+ for k, v := range params {
+ kv = append(kv, k+"="+v)
+ }
+ return fmt.Sprintf("%s/eventhub?%s", addrString, strings.Join(kv, "&"))
+}
@@ -0,0 +1,49 @@
+package connection
+
+import (
+ "encoding/json"
+ "code.google.com/p/go.net/websocket"
+ "crypto/tls"
+
+ "authutil"
+)
+
+type Conn struct {
+ ws *websocket.Conn
+}
+
+type Message struct {
+ Action string `json:"action"`
+ Data map[string]string `json:"data"`
+}
+
+func (c *Conn) SendMessage(channel, msg string) error {
+ data := map[string]string{"channel": channel, "message": msg}
+ m := &Message{
+ Action: "publish_message",
+ Data: data,
+ }
+ j, err := json.Marshal(m)
+ if err != nil {
+ return err
+ }
+ if _, err := c.ws.Write(j); err != nil {
+ return err
+ }
+ return nil
+}
+
+func Connect(addrString, apiKey, secret string) (*Conn, error) {
+ origin := "http://localhost/"
+ config, err := websocket.NewConfig(authutil.ConnectionString(addrString, apiKey, secret), origin)
+ if err != nil {
+ return nil, err
+ }
+ // Ignore certs for now
+ config.TlsConfig = &tls.Config{InsecureSkipVerify: true}
+ ws, err := websocket.DialConfig(config)
+ if err != nil {
+ return nil, err
+ }
+ return &Conn{ws}, nil
+}

0 comments on commit c22692c

Please sign in to comment.