How to redirect to a url

package main

import (
  "net/http"
  "html/template"
)

type data struct {
  List string
}

func main() {
  http.HandleFunc("/", check)
}

func check(w http.ResponseWriter, r * http.Request) {
  if r.Method == "GET" {
    sinfo: = data {
      List: "Here is a list of the files Located with in",
    }

    var tpl_ds = "index.html"

    //t, err := template.New("").Parse(tpl_ds)
    t: = template.Must(template.ParseFiles(tpl_ds))

    r.ParseForm()
    t.Execute(w, sinfo)
  }

  if r.Method == "POST" {
    saveChoice(r.Form["choices"])
    http.Redirect(w, r, newUrl, http.StatusSeeOther)
  }
}

The http status 303 is the appropriate response here. So redirect the request with it.

if r.Method == "POST" {
    saveChoice(r.Form["choices"])
    http.Redirect(w, r, newUrl, http.StatusSeeOther)
}

And if your newUrl is supposed to return a proper html page to the browser, you don't need to use ajax. Use an html form.

<form action="/postHandler" method="post">
   {{range .List}}
    <input type="checkbox" name="choices" value="{{.}}"> <span>{{.}}</span><br>
   {{end}}
    <input type="submit" value="Submit">
</form>

Notice action of the form is defined as /postHandler. Put the name of the endpoint that runs your saveChoice function there.

So to avoid http: multiple response.WriteHeader calls error you get use this code.

  func checkcheck(w http.ResponseWriter, r *http.Request) {
    if r.Method == "GET" {
      sinfo := Stuff{
        List: some_slice
      }

      t, err := template.New("").Parse(tpl_ds)
      checkErr(err)
      err = r.ParseForm()
      checkErr(err)
      err = t.Execute(w, sinfo)
      checkErr(err)
    }

    if r.Method == "POST" {
        saveChoice(r.Form["choices"])
        http.Redirect(w, r, newUrl, http.StatusSeeOther)
    }
  }

Otherwise, the server attempts to render both the form and the redirected url which will result in mutiple calls to the response writer.

Tags:

Go