我的Vue之旅 07 Axios + Golang + Sqlite3 实现简单评论机制( 四 )


package serverimport ( "fmt" "log" "net/http" "strconv" db "wolflong.com/vue_comment/lib/sqlite")type comment interface { QueryComment(pid int64) (json_ []byte, err error) InsertComment(uid, pid int64, text string) (json_ []byte, err error) DeleteComment(id int64) error}var c comment = db.Comment{}func checkError(err error) { if err != nil {panic(err) }}func insertComment(w http.ResponseWriter, r *http.Request) { if r.Method != "POST" {fmt.Fprintf(w, "Only POST Method")return } r.ParseForm() fmt.Println(r.Form) // ^ 简单实现,有待提高健壮性 uid, err := strconv.Atoi(r.Form["uid"][0]) checkError(err) pid, err := strconv.Atoi(r.Form["pid"][0]) checkError(err) text := r.Form["text"][0] inserted, err := c.InsertComment(int64(uid), int64(pid), text) if err != nil {fmt.Fprintf(w, "Error Insert")return } fmt.Fprint(w, string(inserted))}func deleteComment(w http.ResponseWriter, r *http.Request) { if r.Method != "POST" {fmt.Fprintf(w, "Only POST Method")return } r.ParseForm() fmt.Println(r.Form) id, err := strconv.Atoi(r.Form["id"][0]) checkError(err) err = c.DeleteComment(int64(id)) if err != nil {fmt.Fprintf(w, "Error Delete")return } fmt.Fprintf(w, "Success Delete")}func queryComment(w http.ResponseWriter, r *http.Request) { if r.Method != "GET" {fmt.Fprintf(w, "Only GET Method")return } r.ParseForm() fmt.Println(r.Form) pid, err := strconv.Atoi(r.Form["pid"][0]) checkError(err) json, err := c.QueryComment(int64(pid)) if err != nil {fmt.Fprintf(w, "Error Delete")return } fmt.Fprint(w, string(json))}func StartServer() { http.HandleFunc("/insertComment", insertComment) http.HandleFunc("/deleteComment", deleteComment) http.HandleFunc("/queryComment", queryComment) err := http.ListenAndServe(":1314", nil) if err != nil {log.Fatal("ListenAndServe: ", err) }}main.gopackage mainimport ( "fmt" http "wolflong.com/vue_comment/lib/http")func main() { fmt.Println("2022年10月16日 https://cnblogs.com/linxiaoxu") http.StartServer()}资料SQLite Join | 菜鸟教程 (runoob.com)
使用 SQLite 資料庫 - 使用 Golang 打造 Web 應用程式 (gitbook.io)
mattn/go-sqlite3: sqlite3 driver for go using database/sql (github.com)
sqlite3 package - github.com/mattn/go-sqlite3 - Go Packages
go-sqlite3/simple.go at master · mattn/go-sqlite3 (github.com)
05.3. 使用 SQLite 数据库 | 第五章. 访问数据库 |《Go Web 编程》| Go 技术论坛 (learnku.com)
04.1. 处理表单的输入 | 第四章. 表单 |《Go Web 编程》| Go 技术论坛 (learnku.com)
【我的Vue之旅 07 Axios + Golang + Sqlite3 实现简单评论机制】

经验总结扩展阅读