Skip to content

Instantly share code, notes, and snippets.

@ymotongpoo
Last active December 27, 2015 09:28
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ymotongpoo/7303603 to your computer and use it in GitHub Desktop.
Save ymotongpoo/7303603 to your computer and use it in GitHub Desktop.
echo slack-bot
package main
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
)
const BotCommand = "!bot"
type BotResponse struct {
Text string `json:"text"`
}
func NewBotResponse(s string) *BotResponse {
return &BotResponse {
Text: s,
}
}
func main() {
http.HandleFunc("/", root)
http.HandleFunc("/bot", bot)
http.ListenAndServe("0.0.0.0:8080", nil)
}
func root(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "hello, bot")
}
// echo bot server
func bot(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
fmt.Fprintf(w, err.Error())
return
}
original, err := url.QueryUnescape(r.PostForm.Get("text"))
if err != nil {
fmt.Fprintf(w, err.Error())
return
} else if !strings.HasPrefix(original, BotCommand) {
fmt.Fprintf(w, `bot command starts from "!bot"`)
return
}
splitted := strings.SplitN(original, " ", 2)
resp := NewBotResponse(splitted[1])
data, err := json.Marshal(resp)
if err != nil {
fmt.Fprintf(w, err.Error())
return
}
fmt.Fprintf(w, string(data))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment