Golang笔记

在Golang iris web 框架里使用数据库

在Golang iris web 框架里使用数据库

func main() {
    dbinfo := fmt.Sprintf("port=32768 user=%s password=%s dbname=%s sslmode=disable", "postgres", "pass123", "postgres")
    db, err := sql.Open("postgres", dbinfo)
    if err != nil {
        fmt.Printf("err: %+v ", err)
    }
    defer db.Close()

    iris.Get("/people", GetAll(db))
    iris.Get("/people/:id", Get(db))
    iris.Post("/people/:id", Post(db))
    iris.Delete("/people/:id", Delete(db))

    iris.Listen(":8000")
}

func GetAll(db *sql.DB) iris.HandlerFunc {
    return func(ctx *iris.Context) {
        p, err := posts.GetAll(db)
        if err != nil {
            fmt.Printf("%v", err)
            ctx.Error("Failed to load people list", 503)
        }

        ctx.JSON(200, p)
    }
}

func Get(db *sql.DB) iris.HandlerFunc {
    return func(ctx *iris.Context) {
        ID, err := strconv.Atoi(ctx.Param("id"))
        if err != nil {
            handleError(ctx, "Failed to load people list", err)
        }

        p, err := posts.Get(db, ID)
        if err != nil {
            handleError(ctx, "Failed to load people list", err)
        }

        ctx.JSON(200, p)
    }
}

func Post(db *sql.DB) iris.HandlerFunc {
    return func(ctx *iris.Context) {
        name := ctx.Param("name")
        hobby := ctx.Param("hobby")

        err := posts.Post(db, name, hobby)
        if err != nil {
            handleError(ctx, "Failed to save person", err)
            return
        }

        ctx.Write("ok")
    }
}

func Delete(db *sql.DB) iris.HandlerFunc {
    return func(ctx *iris.Context) {
        ID, err := strconv.Atoi(ctx.Param("id"))
        if err != nil {
            handleError(ctx, "Failed to load people list", err)
        }

        err = posts.Delete(db, ID)
        if err != nil {
            handleError(ctx, "Failed to load people list", err)
        }

        ctx.Write("ok")
    }
}

func handleError(ctx *iris.Context, message string, err error) {
    fmt.Printf("%v", err)
    ctx.Error(message, 503)
}

// posts/posts.go
func GetAll(db *sql.DB) ([]Person, error) {
    rows, err := db.Query("SELECT * FROM people")
    if err != nil {
        return nil, fmt.Errorf("failed to get people list: %v", err)
    }

    var people []Person
    for rows.Next() {
        p, err := readPerson(rows)
        if err != nil {
            return nil, fmt.Errorf("failed to get people list: %v", err)
        }

        people = append(people, p)
    }

    return people, nil
}

func Get(db *sql.DB, ID int) (Person, error) {
    rows, err := db.Query("SELECT * FROM people WHERE id = $1", ID)
    rows.Next()
    if err != nil {
        return Person{}, fmt.Errorf("failed to get people list: %v", err)
    }

    return readPerson(rows)
}

func Post(db *sql.DB, name, hobby string) error {
    _, err := db.Query("INSERT INTO people (name, hobby) VALUES ($1, $2)", name, hobby)
    return err
}

func Delete(db *sql.DB, ID int) error {
    _, err := db.Query("DELETE * FROM people WHERE id = $1", ID)
    return err
}

func readPerson(rows *sql.Rows) (Person, error) {
    var id int
    var name string
    var hobby string
    err := rows.Scan(&id, &name, &hobby)
    if err != nil {
        return Person{}, fmt.Errorf("failed to get people list: %v", err)
    }

    return Person{id, name, hobby}, nil
}

type Person struct {
    ID    int
    Name  string
    Hobby string
}
本文网址: https://golangnote.com/topic/151.html (转载注明出处)
关于GolangNote:记录在工作中使用golang 遇到、面临的相关问题及解决方法。如果你在这里获得一些知识或信息,解决你的编程问题,请考虑捐赠给不幸的人或者你喜欢的慈善机构,除捐赠外,种植树木、志愿服务或减少排碳的行为也很有益处。如果你有任何问题可以在下面 留言
Be the first to comment!
Captcha image
Relative Articles