Search code examples
goformsmartinihttp-post

Go martini handling of HTML form data


I am having trouble getting data from the HTML form. The template shows at localhost:3000, I submit and am taken to localhost:3000/results with a "404 page not found" results. The URL does not include any of the forms fields.

package main

import (
    "html/template"
    "net/http"
    "github.com/go-martini/martini"
)

func main() {
    m := martini.Classic()
    m.Get("/", func(res http.ResponseWriter, req *http.Request) { // res and req are injected by Martini
        t, _ := template.ParseFiles("form.gtpl")
        t.Execute(res, nil)
    })

    m.Get("/results", func(r *http.Request) string {
        text := r.FormValue("text")
        return text
    })
    m.Run()
}

and the template is: form.gtpl

<html>
<head>
<title>Title Here</title>
</head>
<body bgcolor="#E6E6FA">
<h1>Header Here</h1>
<form action="/results" method="POST">
    Date: <input type="text" name="dated" size="10" value="01/12/2015">        
    Triggers: <input type="text" name="triggers" size="100" value="Trigger1|Trigger2"><br><br>
    <textarea name ="text" rows="20" cols="150">random text here
</textarea>
    <input autofocus type="submit" value="Submit">
</form>
</body>
</html>

Solution

  • Notice in your form you've specified method="POST", but in the server code you have m.Get("/results",...). That line should be m.Post("/results",...). Martini is trying to route the request but there is no definition for POST /results only GET /results