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.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With