如何从HTML表单中读取输入并将其保存到文件中 – Golang

huangapple go评论89阅读模式
英文:

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

问题

我正在尝试设置一个非常简单的Web服务器,用户可以访问一个网站并输入一个字符串和一个整数。然后,我想保存这两个输入,我的想法是将它们保存到一个文本文件中,该文件也可以在浏览器中显示:.../textfile/

我不知道在SO上发布多少代码是可以的,但是这是我目前的代码:

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)

}

我的HTML表单:(省略了所有的格式)

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

所以我的初步想法是实现两个函数returnInput()和saveInput(),但也许有一些内置函数更容易使用?

如果有人能指导我如何保存HTML表单中的输入,我将非常感激!提前谢谢。

英文:

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 = &quot;timelister&quot;

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

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

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


func main() {
    http.HandleFunc(&quot;/&quot;, upload)
    http.ListenAndServe(&quot;:8080&quot;, nil)

}

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

     Name: &lt;input type=&quot;text&quot; name=&quot;Name&quot;&gt;
      	&lt;input type=&quot;submit&quot; value=&quot;submit&quot;&gt;&lt;/br&gt;
     Hours: &lt;input type=&quot;text&quot; name=&quot;Hours&quot;&gt;
            &lt;input type=&quot;submit&quot; value=&quot;submit&quot;&gt;

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.

答案1

得分: 14

你需要选择一个格式来写入文件。让我们选择JSON,没有特定的原因。所以给定一个表单,如下所示:

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

你可以有以下处理程序

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)
}
英文:

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:

&lt;form action=&quot;/save&quot; method=&quot;post&quot;&gt; ... &lt;/form&gt;

you could have the following handler

import (
    &quot;strconv&quot;
    &quot;http&quot;
    &quot;os&quot;
    &quot;encoding/json&quot;
)

type Data struct {
    Name string
    Hours int
}

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

    data := &amp;Data{name, hours}

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

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

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

func init() {
    http.HandleFunc(&quot;/save&quot;, save)
}

huangapple
  • 本文由 发表于 2012年9月20日 21:43:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/12513963.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定