-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.go
101 lines (90 loc) · 2.62 KB
/
app.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package main
import (
"fmt"
"encoding/json"
"log"
"net/http"
"gopkg.in/mgo.v2/bson"
"github.com/gorilla/mux"
"github.com/Plee/Mongolang/models"
"github.com/Plee/Mongolang/api"
"github.com/Plee/Mongolang/config"
)
// 实例化后端MovieDao
var movieApi =api.MoviesAPI{}
var configer = config.Config{}
func AllMovies(w http.ResponseWriter,r *http.Request){
// fmt.Fprintln(w, "not implemented yet !")
defer r.Body.Close()
movies, err:=movieApi.FindAll()
fmt.Printf("%s\n",movies)
if err !=nil {
respondWithError(w, http.StatusBadRequest, "Can not find the data")
return
}
respondWithJson(w, http.StatusOK,movies)
}
func FindMovie(w http.ResponseWriter,r *http.Request){
params := mux.Vars(r)
movie, err :=movieApi.FindById(params["id"])
fmt.Printf("%s\n",movie)
if err != nil{
respondWithError(w, http.StatusBadRequest,"Invalid Movie Id ")
return
}
respondWithJson(w, http.StatusOK,movie)
}
func CreateMovie(w http.ResponseWriter,r *http.Request){
defer r.Body.Close()
var movie models.Movies
err := json.NewDecoder(r.Body).Decode(&movie)
fmt.Printf("%s\n",movie)
if err != nil {
respondWithError(w, http.StatusBadRequest,"Invalid request payload")
}
movie.ID = bson.NewObjectId()
if err := movieApi.Create(movie); err !=nil{
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
respondWithJson(w, http.StatusCreated, movie)
}
func DeleteMovies(w http.ResponseWriter, r *http.Request){
defer r.Body.Close()
var movie models.Movies
if err := json.NewDecoder(r.Body).Decode(&movie); err != nil{
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
if err := movieApi.Delete(movie); err !=nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
respondWithJson(w, http.StatusOK, map[string]string{"result":"success"} )
}
func respondWithError(w http.ResponseWriter,code int, msg string){
respondWithJson(w,code,map[string]string{"error":msg})
}
func respondWithJson(w http.ResponseWriter, code int, payload interface{}){
res,_ :=json.Marshal(payload)
w.Header().Set("Content-Type","application/json")
w.WriteHeader(code)
w.Write(res)
}
// 解析配置文件"config.toml", 初始化建立数据库连接
func init(){
configer.Read()
movieApi.Server = configer.Server
movieApi.Database = configer.Database
movieApi.Connect()
}
func main(){
r := mux.NewRouter()
r.HandleFunc("/movies",AllMovies).Methods("GET")
r.HandleFunc("/movies/new",CreateMovie).Methods("POST")
r.HandleFunc("/movies/{id}",FindMovie).Methods("GET")
r.HandleFunc("/movies",DeleteMovies).Methods("DELETE")
if err:=http.ListenAndServe(":8888",r); err!=nil{
log.Fatal(err)
}
}