Skip to content

Instantly share code, notes, and snippets.

@joedborg
Created October 10, 2014 18:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joedborg/6e4098962e999303e814 to your computer and use it in GitHub Desktop.
Save joedborg/6e4098962e999303e814 to your computer and use it in GitHub Desktop.
Example of a POST handle in Go that uses Twilio to SMS the form
package main
import (
"fmt"
twilio "github.com/carlosdp/twiliogo"
"net/http"
"strings"
)
var form = []string{
"Make",
"Model",
"Engine Capacity",
}
func sendSms(body []string) {
client := twilio.NewClient($SID, $API_KEY)
message, err := twilio.NewMessage(client, $FROM, $TO, twilio.Body(strings.Join(body, ", ")))
if err != nil {
fmt.Println(err)
} else {
fmt.Println(message.Status)
}
}
func handleForm(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "<html><body><form method='POST' action='/submit'><table>")
for key := range form {
fmt.Fprintf(w, "<tr><th>%s</th><td><input type='text' name='%s'></td></tr>", form[key], form[key])
}
fmt.Fprintf(w, "</table>")
fmt.Fprintf(w, "<input type='submit'>")
fmt.Fprintf(w, "</form></body></html>")
}
func handlePost(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
values := []string{}
for key := range form {
values = append(values, fmt.Sprintf("%s: %s", form[key], r.PostFormValue(form[key])))
print(r.PostFormValue(form[key]) + "\n")
}
sendSms(values)
}
func main() {
http.HandleFunc("/", handleForm)
http.HandleFunc("/submit", handlePost)
http.ListenAndServe(":8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment