I am able to load a html page ( index.html ) who's <body></body>
contents looks like the following:
<form action="ask" method="get">
<input type="text" name="q" />
</form>
What I am trying to so is render index.html and then on submission of the ask render a copy of index.html except have some of the contents come from my golang code as a results page.
When I submit the form in index.html, I get a blank page.
But I am getting no data received when going to localhost:8000/view or localhost:8000/view?q=hello+world in the browser. And in the terminal, I get this and a lot more, but this is the first line:
http: panic serving [::1]:53803: runtime error: invalid memory address or nil pointer dereference
what does it mean and how can I fix it?
WhenI go to /ask or /ask?q=hello+world, which is what I am trying to do, I get the blank page with no errors.
I am trying to handle ask on the initial page that is loaded and on the results page once that ask form has been submitted.
index.html, view.html, and edit.html all have this:
<form method="get" action="ask">
<input type="text" name="q" />
</form>
Here is my code now:
package main
import (
"fmt"
"net/http"
"github.com/zenazn/goji"
"github.com/zenazn/goji/web"
"html/template"
"io/ioutil"
)
type Page struct {
Title string
Body []byte
}
func (p *Page) save() error{
filename := p.Title + ".txt"
return ioutil.WriteFile(filename, p.Body, 0600)
}
func loadPage(title string) (*Page, error){
filename := title + ".txt"
body, err := ioutil.ReadFile(filename)
if err != nil{
return nil, err
}
return &Page{Title: title, Body: body}, nil
}
func renderTemplate(w http.ResponseWriter, tmpl string, p *Page){
t, err := template.ParseFiles(tmpl + ".html")
if err != nil{
fmt.Println(err)
}
t.Execute(w, p)
}
func viewHandler(w http.ResponseWriter, r *http.Request){
//title := r.URL.Path[len("/view/"):]
title := r.FormValue("q")
p, err := loadPage(title)
if err != nil{
fmt.Println(err)
}
renderTemplate(w, "view", p)
}
func editHandler(w http.ResponseWriter, r *http.Request){
//title := r.URL.Path[len("/edit/"):]
title := r.FormValue("q")
p, err := loadPage(title)
if err != nil{
p = &Page{Title: title}
fmt.Println(err)
}
renderTemplate(w, "edit", p)
}
func response(c web.C, w http.ResponseWriter, r *http.Request){
}
func serveSingle(filename string) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, filename)
}
}
func main() {
goji.Get("/", serveSingle("Projects/Go/src/web/site/index.html"))
goji.Handle("/ask", response)
http.HandleFunc("/view/", viewHandler)
http.HandleFunc("/edit/", editHandler)
goji.Serve()
}
So I want to handle ask from the index.html and the results page and run response, which will render the results page on submission of the ask form from index.html and the results page.