英文:
How to fetch data from the file and print it on a browser?
问题
在这段代码中,我创建了一个名为viewHandler
的函数,在该函数中,我创建了一个文本区域,并从工作目录中的文件中获取数据。但是,当我运行这段代码并检查浏览器时,它只显示一个带有文本区域和提交按钮的编辑界面。尽管我写了从文件中打印标题和正文的代码,但它没有从那里获取数据。
给出的结果如下:
type Page struct {
Title string
Body []byte
}
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 viewHandler(w http.ResponseWriter, r *http.Request) {
title := r.URL.Path[len("/edit/"):]
p, err := loadPage(title)
if err != nil {
p = &Page{Title: title}
}
fmt.Fprintf(w, "<h1>Editing %s</h1>"+
"<form action=\"/save/%s\" method=\"POST\">"+
"<textarea name=\"body\">%s</textarea><br>"+
"<input type=\"submit\" value=\"Save\">"+
"</form>",
p.Title, p.Title, p.Body)
}
func main() {
http.HandleFunc("/view/", viewHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
英文:
In this code, I made a function called viewHandler
in which I made the text area plus I am getting the data from a file that is present in the working directory but when I run this code and check the browser, it just shows me the Editing with a text area and submits button. Although I wrote to print the title and body from the file also but it is not fetching data from there.
Given result
type Page struct {
Title string
Body []byte
}
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 viewHandler(w http.ResponseWriter, r *http.Request) {
title := r.URL.Path[len("/edit/"):]
p, err := loadPage(title)
if err != nil {
p = &Page{Title: title}
}
fmt.Fprintf(w, "<h1>Editing %s</h1>"+
"<form action=\"/save/%s\" method=\"POST\">"+
"<textarea name=\"body\">%s</textarea><br>"+
"<input type=\"submit\" value=\"Save\">"+
"</form>",
p.Title, p.Title, p.Body)
}
func main() {
http.HandleFunc("/view/", viewHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
答案1
得分: 1
URL应该类似于http://localhost:8080/view/something
,这将导入一个名为something.txt
的文件。
请确保该文件与可执行文件位于同一文件夹中,并具有读取权限。
英文:
The url should be something like http://localhost:8080/view/something
and this will import a file named something.txt
.
Make sure the file exists in the same folder as the executable and has read permissions.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论