golang 创建 restful 服务

有关 restful 可以参看
会说话Restful
创建工程【www.xihefangpei.com
创建工程,然后创建 main 文件,引用所需包。

1package main
2
3import (
4 "encoding/json"
5 "log"
6 "net/http"
7 "math/rand"
8 "strconv"
9 "github.com/gorilla/mux"
10)
11
12func main(){
13
14}
设计路由
这里引用一个 Mux 的包用于创建路由\

1func main(){
2 //Init Router
3 r := mux.NewRouter()
4 //Route Handlers / Endpoints
5 r.HandleFunc("/api/tuts", getTuts).Methods("GET")
6}
1//Init Router
2 r := mux.NewRouter()
3 //Route Handlers / Endpoints
4 r.HandleFunc("/api/tuts", getTuts).Methods("GET")
5 r.HandleFunc("/api/tuts/{id}", getTut).Methods("GET")
6 r.HandleFunc("/api/tuts", createTut).Methods("POST")
7 r.HandleFunc("/api/tuts/{id}", updateTut).Methods("PUT")
8 r.HandleFunc("/api/tuts/{id}", deleteTut).Methods("DELETE")
定义服务
1log.Fatal(http.ListenAndServe(":4200",r))
定义数据模型结构
1// tut struct (Model)
2type Tut struct{
3 ID string json:"id"
4 Isbn string json:"isbn"
5 Title string json:"title"
6 Author Author json:"author"
7}
8
9// Author Struct
10type Author struct{
11 Name string json:"name"
12}
定义请求的处理句柄
1func getTuts(w http.ResponseWriter, r
http.Request){
2
3}
4// get Single Tut
5func getTut(w http.ResponseWriter, r http.Request){
6
7}
8// create new Tut
9func createTut(w http.ResponseWriter, r
http.Request){
10
11}
12//update tut
13func updateTut(w http.ResponseWriter, r http.Request){
14
15}
16//delete tut
17func deleteTut(w http.ResponseWriter, r
http.Request){
18
19}
模拟数据库
1tuts = append(tuts, Tut{ID:"1",Isbn:"123",Title:"angular base tut",Author:&Author{
2 Name:"zidea",
3 }})
4
5 tuts = append(tuts, Tut{ID:"2",Isbn:"345",Title:"vue base tut",Author:&Author{
6 Name:"tina",
7 }})
8
9 tuts = append(tuts, Tut{ID:"3",Isbn:"456",Title:"react base tut",Author:&Author{
10 Name:"zidea",
11 }})
实现获取所有课程的列表
1func getTuts(w http.ResponseWriter, r *http.Request){
2 w.Header().Set("Content-Type","application/json")
3 json.NewEncoder(w).Encode(tuts)
4}
修改代码后我们需要重新 build 后再次启动服务。
然后可以 Postman 开测试一下我们的接口是否好用

实现单条查找
1func getTut(w http.ResponseWriter, r *http.Request){
2 w.Header().Set("Content-Type","application/json")
3 params := mux.Vars(r) //Get params
4 // loop through tuts and find with id
5 for _, item := range tuts {
6 if item.ID == params["id"]{
7 json.NewEncoder(w).Encode(item)
8 return
9 }
10 }
11
12 json.NewEncoder(w).Encode(&Tut{})
13}

创建课程
1func createTut(w http.ResponseWriter, r *http.Request){
2 w.Header().Set("Content-Type","application/json")
3 var tut Tut
4 _ = json.NewDecoder(r.Body).Decode(&tut)
5 tut.ID = strconv.Itoa(rand.Intn(1000)) // Mock Id
6 tuts = append(tuts, tut)
7 json.NewEncoder(w).Encode(tut)
8}
测试接口

实现删除课程
1func deleteTut(w http.ResponseWriter, r *http.Request){
2 fmt.Println("call delete handler")
3 w.Header().Set("Content-Type","application/json")
4 params := mux.Vars(r)
5 fmt.Println(params["id"])
6 for index, item := range tuts{
7 if item.ID == params["id"]{
8 tuts = append(tuts[:index],tuts[index+1:]...)
9 break
10 }
11 }
12
13 json.NewEncoder(w).Encode(tuts)
14}

更新课程
1func updateTut(w http.ResponseWriter, r *http.Request){
2 fmt.Println("call delete handler")
3 w.Header().Set("Content-Type","application/json")
4 params := mux.Vars(r)
5 fmt.Println(params["id"])
6 for index, item := range tuts{
7 if item.ID == params["id"]{
8 tuts = append(tuts[:index],tuts[index+1:]...)
9 var tut Tut
10 _ = json.NewDecoder(r.Body).Decode(&tut)
11 tut.ID = params["id"] // Mock Id
12 tuts = append(tuts, tut)
13 json.NewEncoder(w).Encode(tut)
14 return
15 }
16 }
17
18 json.NewEncoder(w).Encode(tuts)
19}

讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!