zoukankan      html  css  js  c++  java
  • 014-Go Web 对pg增删改查测试

    1:data/data.go

    package data
    
    import(
        "fmt"
        "database/sql"
        _"github.com/lib/pq"
    )
    
    const(
        host = "192.168.72.128"
        port = 5432
        user = "test"
        password = "test"
        dbname = "testdb"
    )
    
    var Db *sql.DB
    
    func init(){
        var err error
    
        pgInfo := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", 
            host, port, user, password, dbname)
        
        Db, err = sql.Open("postgres", pgInfo)
    
        if err != nil{
            panic(err)
        }
    }

    2:post/post.go

    package post
    
    import(
        ."Chapter10/data"
    )
    
    type Post struct{
        ID        int     `json:"id"`
        Content    string     `json:"content"`
        Author    string    `json:"author"`
    }
    
    func (post *Post) AddPost()(err error){
        sql := "insert into post(content,author) values($1,$2) returning id"
        stmt, err := Db.Prepare(sql)
        if err != nil{
            return
        }
        defer stmt.Close()
        err = stmt.QueryRow(post.Content, post.Author).Scan(&post.ID)
        return
    }
    
    func (post *Post) DelPost()(err error){
        sql := "delete from post where id=$1"
        _,err = Db.Exec(sql, post.ID)
        return
    }
    
    func (post *Post) EditPost()(err error){
        sql := "update post set content=$1 where id=$2"
        _,err = Db.Exec(sql, post.Content, post.ID)
        return
    }
    
    func FindPost(id int)(err error, post Post){
        sql := "select id, content, author from post where id=$1"
        post = Post{}
        err = Db.QueryRow(sql, id).Scan(&post.ID, &post.Content, &post.Author)
        return
    }

    3:main.go

    package main
    
    import(
        "encoding/json"
        "net/http"
        "path"
        "strconv"
        "time"
        ."Chapter10/post"
    )
    
    type Result struct{
        No    int             `json:"no"`
        Msg    string         `json:"msg"`
        Obj interface{} `json:"obj,omitempty"`
        Time time.Time  `json:"response_time"`
    }
    
    func main(){
        server := http.Server{
            Addr: "127.0.0.1:8080",
        }
        http.HandleFunc("/post/", handlerRequest)
        server.ListenAndServe()
    }
    
    func handlerRequest(w http.ResponseWriter, r *http.Request){
        var err error
        switch r.Method{
        case "GET":
            err = handleGet(w, r)
        case "POST":
            err = handlePost(w, r)
        case "PUT":
            err = handlePut(w, r)
        }
    
        if err != nil{
            http.Error(w, err.Error(), http.StatusInternalServerError)
        }
    }
    
    
    
    func handleGet(w http.ResponseWriter, r *http.Request)(err error){
        id, err := strconv.Atoi(path.Base(r.URL.Path))
        if err != nil{
            return
        }
        err,post := FindPost(id)
        if err != nil{
            return
        }
    
        var result = Result{
            No:100,
            Msg:"获取POST信息",
            Obj:post,
            Time:time.Now(),
        }
    
        output, err := json.Marshal(&result)
        if err != nil{
            return
        }
        w.Header().Set("Content-Type", "application/json")
        w.Write(output)
        return
    }
    
    func handlePost(w http.ResponseWriter, r *http.Request)(err error){
        len := r.ContentLength
        body := make([]byte, len)
        r.Body.Read(body)
    
        var post Post
        json.Unmarshal(body, &post)
    
        err = post.AddPost()
        if err != nil{
            return
        }
    
        var result = Result{
            No:100,
            Msg:"保存POST信息",
            Time:time.Now(),
        }
        output, err := json.Marshal(&result)
        if err != nil{
            return
        }
        w.Header().Set("Content-Type", "application/json")
        w.Write(output)
        return
    }    
    
    func handlePut(w http.ResponseWriter, r *http.Request)(err error){
        len := r.ContentLength
        body := make([]byte, len)
        r.Body.Read(body)
    
        var post Post
        json.Unmarshal(body, &post)
    
        err = post.EditPost()
        if err != nil{
            return
        }
    
        var result = Result{
            No:100,
            Msg:"修改POST信息",
            Time:time.Now(),
        }
        output, err := json.Marshal(&result)
        if err != nil{
            return
        }
        w.Header().Set("Content-Type", "application/json")
        w.Write(output)
        return
    }
  • 相关阅读:
    我的开源2009
    Kooboo CMS
    Visual Studio 2008丢失XML高亮和提示
    Kooboo完全介绍二:创建第一个Kooboo站点
    Telnet发送邮件和.NET邮件匿名发送组件
    C#中循环结构的效率问题 Virus
    从Android中Activity之间的通信说开来 Virus
    新浪微博开放平台开发android客户端(2) Virus
    MongoDB在Windows2003上得安装配置及使用 Virus
    消息提示的架构演进理论篇 Virus
  • 原文地址:https://www.cnblogs.com/yshyee/p/9192512.html
Copyright © 2011-2022 走看看