gpt4 book ai didi

html - ResponseWriter 为什么以及何时会生成原始 html?

转载 作者:IT王子 更新时间:2023-10-29 02:33:35 27 4
gpt4 key购买 nike

我不明白为什么代码正确生成了 view.html 和 post.html 数据,但将其全部显示为原始文本。我一直在关注指南 here在我构建它时,我认为从 Execute 函数生成的 html 将被发送到 ResponserWriter 来处理显示它,但我得到的错误似乎表明我对 Execute 的理解或 ResponseWriter 是错误的。

package main

import (
"os"
"fmt"
"time"
"bufio"
"net/http"
"html/template"
)

type UserPost struct {
Name string
About string
PostTime string
}

func check(e error) {
if e != nil {
fmt.Println("Error Recieved...")
panic(e)
}
}


func lineCounter(workingFile *os.File) int {
fileScanner := bufio.NewScanner(workingFile)
lineCount := 0
for fileScanner.Scan() {
lineCount++
}
return lineCount
}

func loadPage(i int) (*UserPost, error) {
Posts,err := os.Open("dataf.txt")
check(err)
var PostArray [512]UserPost = parsePosts(Posts,i)
Name := PostArray[i].Name
About := PostArray[i].About
PostTime := PostArray[i].PostTime
Posts.Close()
return &UserPost{Name: Name[:len(Name)-1], About: About[:len(About)-1], PostTime: PostTime[:len(PostTime)-1]}, nil
}

func viewHandler(w http.ResponseWriter, r *http.Request) {
tmp,err := os.Open("dataf.txt")
check(err)
num := (lineCounter(tmp)/3)
tmp.Close()
for i := 0; i < num; i++ {
p, _ := loadPage(i)
t, _ := template.ParseFiles("view.html")
t.Execute(w, p)
}
p := UserPost{Name: "", About: "", PostTime: ""}
t, _ := template.ParseFiles("post.html")
t.Execute(w, p)
}

func inputHandler(w http.ResponseWriter, r *http.Request) {
Name := r.FormValue("person")
About := r.FormValue("body")
PostTime := time.Now().String()

filePaste,err := os.OpenFile("dataf.txt", os.O_RDWR | os.O_CREATE | os.O_APPEND | os.SEEK_END, 0666)
check(err)
filePaste.WriteString(Name+"~\n")
filePaste.WriteString(About+"~\n")
filePaste.WriteString(PostTime+"~\n")
filePaste.Close()
fmt.Println("Data recieved: ", Name,About,PostTime)
http.Redirect(w, r, "/#bottom", http.StatusFound) //Use "/#bottom" to go to bottom of html page.
}

//os.File is the file type.
func parsePosts(fileToParse *os.File,num int) [512]UserPost {
var buffer [512]UserPost
reader := bufio.NewReader(fileToParse)

//This For loop reads each "forum post" then saves it to the buffer, then iterates to the next.
for i := 0;i <= num; i++ {
currentPost := new(UserPost)
str, err := reader.ReadString('~')
check(err)
currentPost.Name = str

//I search for '~' because my files save the end of reading line with that, so i can keep formatting saved (\n placement).
str2, err2 := reader.ReadString('~')
check(err2)
currentPost.About = str2

str3, err3 := reader.ReadString('~')
check(err3)
currentPost.PostTime = str3

buffer[i] = *currentPost
}
return buffer
}

func main() {
fmt.Println("Listening...")
http.HandleFunc("/", viewHandler)
http.HandleFunc("/post/", inputHandler)
http.ListenAndServe(":8080", nil)
}

view.html

<h4>{{.Name}}</h4>

<font size="3">
<div>{{printf "%s" .About}}</div>
</font>
<br>
<font size="2" align="right">
<div align="right">{{.PostTime}}</div>
</font>

post.html

<form action="/post/" method="POST">

<div><textarea name="person" rows="1" cols="30">{{printf "%s" .Name}}</textarea></div>

<div><textarea name="body" rows="5" cols="100">{{printf "%s" .About}}</textarea></div>

<div><input type="submit" value="Submit"></div>

<a name="bottom"></a>
</form>

我目前一直在读取一个空的 dataf.txt 文件。

最佳答案

正如提示的那样,这是因为您还没有设置内容类型。引自 http.ResponseWriter :

// Write writes the data to the connection as part of an HTTP reply.
// If WriteHeader has not yet been called, Write calls WriteHeader(http.StatusOK)
// before writing the data. If the Header does not contain a
// Content-Type line, Write adds a Content-Type set to the result of passing
// the initial 512 bytes of written data to DetectContentType.
Write([]byte) (int, error)

如果您不自己设置内容类型,请先调用ResponseWriter.Write()会调用 http.DetectContentType() 猜猜要设置什么。如果你发送的内容以"<form>"开头,它不会被检测为 HTML,但是 "text/plain; charset=utf-8"将被设置(“指示”浏览器将内容显示为文本,而不是尝试将其解释为 HTML)。

如果内容以 "<html>" 开头例如,内容类型 "text/html; charset=utf-8"将自动设置,无需进一步操作即可工作。

但是,如果您知道自己发送的是什么,就不要依赖自动检测,而且自己设置它比对其运行检测算法要快得多,因此只需在写入/发送任何数据之前添加以下行:

w.Header().Set("Content-Type", "text/html; charset=utf-8")

同时让你的 post.html模板完整、有效的 HTML 文档。

还有另一条建议:在您的代码中,您虔诚地忽略了检查返回的错误。不要那样做。您至少可以在控制台上打印它们。如果您不遗漏错误,您将为自己节省很多时间。

关于html - ResponseWriter 为什么以及何时会生成原始 html?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36027099/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com