码迷,mamicode.com
首页 > Web开发 > 详细

014-Go Web 对pg增删改查测试

时间:2018-06-17 12:39:43      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:into   mode   修改   ddr   chap   edit   defer   string   DPoS   

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
}

 

014-Go Web 对pg增删改查测试

标签:into   mode   修改   ddr   chap   edit   defer   string   DPoS   

原文地址:https://www.cnblogs.com/yshyee/p/9192512.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!