1. 程式人生 > >014-Go Web 對pg增刪改查測試

014-Go Web 對pg增刪改查測試

sca AC %d ons password tab exe pack git

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增刪改查測試