Last active
December 27, 2015 09:28
-
-
Save ymotongpoo/7303603 to your computer and use it in GitHub Desktop.
echo slack-bot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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