Go語言是一種高效、簡潔、快速開發的編程語言,廣泛應用于Web開發、網絡編程、系統管理等各個領域。在我們日常的開發工作中,經常需要實現HTML輸入,下面我們來看看如何使用Go代碼實現HTML輸入。
package main import ( "fmt" "html/template" "net/http" ) type Page struct { Title string Body []byte } func (p *Page) save() error { filename := p.Title + ".txt" return ioutil.WriteFile(filename, p.Body, 0600) } 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("/view/"):] p, err := loadPage(title) if err != nil { http.Redirect(w, r, "/edit/"+title, http.StatusFound) return } fmt.Fprintf(w, "<h1>%s</h1><div>%s</div>", p.Title, template.HTML(p.Body)) } func editHandler(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, template.HTMLAttr(string(p.Body))) } func saveHandler(w http.ResponseWriter, r *http.Request) { title := r.URL.Path[len("/save/"):] body := r.FormValue("body") p := &Page{Title: title, Body: []byte(body)} err := p.save() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } http.Redirect(w, r, "/view/"+title, http.StatusFound) } func main() { http.HandleFunc("/view/", viewHandler) http.HandleFunc("/edit/", editHandler) http.HandleFunc("/save/", saveHandler) http.ListenAndServe(":8080", nil) }
需要注意的是,在viewHandler中需要將p.Body轉換為template.HTML類型,以保證HTML代碼可以正常輸出。
以上就是使用Go代碼實現HTML輸入的過程,相信通過上述代碼實現,大家可以更好地掌握Go語言的應用技巧。