Go Basic Learning Record - Writing Web Application - Blog Editor Perfect Update Function

Keywords: Go github SQL git Database

Every time I put my practice code on github and typed a tag, which is convenient for the students to use later. Here I share my practice with the code of the following branches.

https://github.com/durban89/typescript_demo.git
tag: 1.1.1

Last article[ Go Basic Learning Record - Writing Web Application - Perfect Blog Editing Function ] We just read the articles we need from the database and display them at the front end. If we want to modify them, how to operate them. Today's share continues with the last article.

First step, add update Model

Since updating involves updating logic, that is, how to write updates to the database. Here I perfect the previous Update function and change the Update function to Update Data. The main reason is that I also wrote an Update function in the sqlite library. The go tool prompts me to repeat the question of whether the mechanism of go or not, which should not be under the same package. This function has the same function, temporarily modified to Update Data, but here should also be the design problem, and then to improve, first of all, the logic of editing updates will be improved, Update Data functions are implemented as follows.

// Update Data Updates Data
func (b *Blog) UpdateData() (int64, error) {
    var updateString = strings.Join(b.MergeUpdate(), " , ")
    var whereString = strings.Join(b.MergeWhere(), " AND ")

    sql := fmt.Sprintf("UPDATE %s SET %s WHERE %s", tableName, updateString, whereString)
    stmt, err := Conn.Prepare(sql)
    if err != nil {
        return 0, err
    }

    res, err := stmt.Exec()
    if err != nil {
        return 0, err
    }

    affect, err := res.RowsAffected()
    if err != nil {
        return 0, err
    }

    return affect, nil
}

Of course, there is a problem here. It is recommended that the parameters to be modified be put into Exec, which should prevent SQL injection.

Step 2: Add update Controller

The updated Model is available, then the logic of Controller is modified, and the function ArticleEdit is modified. The code is implemented as follows

// ArticleEdit Edits Articles
func ArticleEdit(w http.ResponseWriter, r *http.Request) {
    id := r.URL.Query().Get("id")
    if id == "" {
        http.NotFound(w, r)
        return
    }

    where := []db.Where{}
    update := []db.UpdateSection{}

    if strings.ToLower(r.Method) == "get" {

        where = append(where, db.Where{
            Name:  "autokid",
            Value: id,
        })

        blogModel := &models.Blog{
            Select: []string{"*"},
            Where:  where,
        }

        p, err := blogModel.QueryOne()

        if err != nil {
            http.NotFound(w, r)
            return
        }

        crutime := time.Now().Unix()
        h := md5.New()
        io.WriteString(h, strconv.FormatInt(crutime, 10))
        token := fmt.Sprintf("%x", h.Sum(nil))

        p.Token = token
        helpers.RenderTemplate(w, "edit", p)
    } else if strings.ToLower(r.Method) == "post" {
        title := r.FormValue("title")
        if title == "" {
            http.Redirect(w, r, fmt.Sprintf("/edit?id=%s", id), http.StatusFound)
            return
        }

        update = append(update, db.UpdateSection{
            Name:  "title",
            Value: title,
        })

        where = append(where, db.Where{
            Name:  "autokid",
            Value: id,
        })

        blogModel := &models.Blog{
            Update: update,
            Where:  where,
        }

        _, err := blogModel.UpdateData()

        if err != nil {
            http.NotFound(w, r)
            return
        }

        http.Redirect(w, r, fmt.Sprintf("/edit?id=%s", id), http.StatusFound)
        return
    }

}

It feels a little like the previous writing.

Step 3: Add Update View

In order to modify the template, mainly to modify the submitted address. take

<form action="/save/{{.Title}}" method="POST">

Change to

<form action="/edit/?id={{.ID}}" method="POST">

To see the completed example, please go here, as follows

Project Update Address

https://github.com/durban89/typescript_demo.git
tag: 1.1.2

Posted by wayz1229 on Fri, 01 Feb 2019 11:15:16 -0800