Go REST API示例

package main  
import (  
   "encoding/json"  
   "log"  
   "net/http"  
   "github.com/gorilla/mux"  
)  
type Employee struct {  
   ID        string   'json:"id,omitempty"'  
   Firstname string   'json:"firstname,omitempty"'  
   Lastname  string   'json:"lastname,omitempty"'  
   Address   *Address 'json:"address,omitempty"'  
}  
type Address struct {  
   City  string 'json:"city,omitempty"'  
   State string 'json:"state,omitempty"'  
}  
var emp []Employee  
func GetEmpIdEndpoint(w http.ResponseWriter, req *http.Request) {  
   params := mux.Vars(req)  
   for _, item := range emp {  
      if item.ID == params["id"] {  
         json.NewEncoder(w).Encode(item)  
         return  
      }  
   }  
   json.NewEncoder(w).Encode(&Employee{})  
}  
func GetEmployeeEndpoint(w http.ResponseWriter, req *http.Request) {  
   json.NewEncoder(w).Encode(emp)  
}  
func CreateEmployeeEndpoint(w http.ResponseWriter, req *http.Request) {  
   params := mux.Vars(req)  
   var person Employee  
   _ = json.NewDecoder(req.Body).Decode(&person)  
   person.ID = params["id"]  
   emp = append(emp, person)  
   json.NewEncoder(w).Encode(emp)  
}  
func DeleteEmployeeEndpoint(w http.ResponseWriter, req *http.Request) {  
   params := mux.Vars(req)  
   for index, item := range emp {  
      if item.ID == params["id"] {  
         emp = append(emp[:index], emp[index+1:]...)  
         break  
      }  
   }  
   json.NewEncoder(w).Encode(emp)  
}  
func main() {  
   router := mux.NewRouter()  
   emp = append(emp, Employee{ID: "1", Firstname: "Nic", Lastname: "Raboy",   
   Address: &Address{City: "Dublin", State: "CA"}})  
   emp = append(emp, Employee{ID: "2", Firstname: "Maria", Lastname: "Raboy"})  
   router.HandleFunc("/employee", GetEmployeeEndpoint).Methods("GET")  
   router.HandleFunc("/employee/{id}", GetEmpIdEndpoint).Methods("GET")  
   router.HandleFunc("/employee/{id}", CreateEmployeeEndpoint).Methods("POST")  
   router.HandleFunc("/employee/{id}", DeleteEmployeeEndpoint).Methods("DELETE")  
   log.Fatal(http.ListenAndServe(":12345", router))  
}  

输出:

您可以通过在Chrome浏览器上安装Postman扩展来检查输出。

方法 --> Get,

URL -->http://localhost:8080/employee  
响应:  
[{"id":"1","firstname":"James","lastname":"Johnson","address":{"city":"Hoseynabad","state":"Kavir"}}  
,{"id":"2","firstname":"Sarah","lastname":"Taylor","address":{"city":"Kamenka","state":"Vyborgsky"}}]  

方法 --> GET,

URL -->http://localhost:8080/employee/1  
响应:  
{"id":"1","firstname":"James","lastname":"Johnson","address":  
"city":"Hoseynabad","state":"Kavir"}}  

方法 --> POST,

URL -->http://localhost:8080/employee/3  
响应:  
[{"id":"

标签: Golang, Golang下载, Golang教程, Golang技术, Golang学习, Golang学习教程, Golang语言, Golang开发, Golang入门教程, Golang进阶教程, Golang高级教程, Golang面试题, Golang笔试题, Golang编程思想