(一) go 实现的基于REST的Web服务
参考: 《Go Web 编程》
1. go 实现的基于REST的Web服务
// webserver project server.go
package main
import (
"encoding/json"
"fmt"
"net/http"
//"strconv"
)
type Post struct {
Id int `json:"id"`
Content string `jsong:"content"`
Author string
}
// 全局变量,用来保存post
var posts []Post
func (post *Post) create() (err error) {
posts = append(posts, *post)
return
}
func (post *Post) delete() (err error) {
for pos, p := range posts {
if p.Id == post.Id {
posts[pos] = posts[len(posts)-1]
posts = posts[:len(posts)-1]
return
}
}
return
}
func main() {
fmt.Print("start the web server")
server := http.Server{
Addr: "127.0.0.1:8080",
}
http.HandleFunc("/CRUD/", handleRequest)
server.ListenAndServe()
}
func handleRequest(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)
case "DELETE":
err = handleDelete(w, r)
}
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func handleGet(w http.ResponseWriter, r *http.Request) (err error) {
// return posts value
result, err := json.Marshal(posts)
if err != nil {
w.WriteHeader(201)
return
}
w.Write([]byte(result))
return
}
func handlePost(w http.ResponseWriter, r *http.Request) (err error) {
// read post data
len := r.ContentLength
body := make([]byte, len)
r.Body.Read(body)
// parse body to post
var post Post
err = json.Unmarshal(body, &post)
if err != nil {
w.Write([]byte("parse json failed\n"))
return
}
// save post value to database or somewhere.
post.create()
// return posts value
result, err := json.Marshal(posts)
if err != nil {
w.WriteHeader(201)
return
}
w.Write([]byte(result))
w.WriteHeader(200)
return
}
func handlePut(w http.ResponseWriter, r *http.Request) (err error) {
w.Write([]byte("handlePut()"))
return
}
func handleDelete(w http.ResponseWriter, r *http.Request) (err error) {
// read post data
len := r.ContentLength
body := make([]byte, len)
r.Body.Read(body)
// parse body to post
var post Post
err = json.Unmarshal(body, &post)
if err != nil {
w.Write([]byte("parse json failed\n"))
return
}
// save post value to database or somewhere.
post.delete()
// return posts value
result, err := json.Marshal(posts)
if err != nil {
w.WriteHeader(201)
return
}
w.Write([]byte(result))
// var result string
// result = strconv.Itoa(post.Id)
// w.Write([]byte(result))
w.WriteHeader(200)
return
}