Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read input from a HTML form and save it in a file - Golang

Tags:

forms

go

I am trying to set up a very simple web server where the user access a site and writes a string and an int.Then I want to save these two inputs, my idea was to do it to a text file that also can be displayed in the browser: .../textfile/

I don´t know what the norm on SO is on how much code is OK to post but here is what I have so far:

type Person struct {
    name  string
    hours int
}

const filename string = "timelister"

func upload(w http.ResponseWriter, r *http.Request) {
    t, _ := template.ParseFiles("upload.html")
    t.Execute(w, nil)
}

func (person *Person) open() {
    newFilename := filename + ".txt"
    _, err := os.OpenFile(newFilename, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)
    if err != nil {
        log.Fatal("Open Filename: ", err)
    }
}

func returnInput() //want to implement this
func saveInput() //want to implemet this


func main() {
    http.HandleFunc("/", upload)
    http.ListenAndServe(":8080", nil)

}

And my HTML-form: (without all the formating)

     Name: <input type="text" name="Name">
        <input type="submit" value="submit"></br>
     Hours: <input type="text" name="Hours">
            <input type="submit" value="submit">

So my initial thoughts was to implement two functions returnInput() and saveInput() but maybe there are som built in functions that are easier to use?

If somebody could point me in the right direction on how to save the input from the HTML form than I would be very greatful! Thanks in advance.

like image 694
miner Avatar asked Sep 20 '12 13:09

miner


1 Answers

You'll need to pick a format to write to the file. Let's pick JSON for no reason in particular. So given a form like:

<form action="/save" method="post"> ... </form>

you could have the following handler

import (
    "strconv"
    "http"
    "os"
    "encoding/json"
)

type Data struct {
    Name string
    Hours int
}

func save(w http.ResponseWriter, r *http.Request) {
    name := r.FormValue("Name")
    hours, err := strconv.Atoi(r.FormValue("Hours"))
    if err != nil {
        http.Error(w, err.Error(), 500)
        return
    }

    data := &Data{name, hours}

    b, err := json.Marshal(data)
    if err != nil {
        http.Error(w, err.Error(), 500)
        return
    }

    f, err := os.Open("somefile.json")
    if err != nil {
        http.Error(w, err.Error(), 500)
        return
    }

    f.Write(b)
    f.Close()
}

func init() {
    http.HandleFunc("/save", save)
}
like image 104
dskinner Avatar answered Nov 08 '22 14:11

dskinner