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))
}
输出:
You can check the output by installing postman extension for chrome browser
方法->获取,
url -->http://localhost:8080/employee
Response :
[{"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
Response :
{"id":"1", "firstname":"James", "lastname":"Johnson", "address":
"city":"Hoseynabad", "state":"Kavir"}}
方法-> POST,
url -->http://localhost:8080/employee/3
Response :
[{"id":"1", "firstname":"James", "lastname":"Johnson", "address":{"city":"Hoseynabad", "state":"Kavir"}}, {"id":"2", "firstname":"Sarah", "lastname":"Taylor", "address":{"city":"Kamenka", "state":"Vyborgsky"}}, {"id":"3", "firstname":"Roger", "lastname":"Ponting", "address":{"city":"San Pedro", "state":"LA"}}]
方法->删除
url -->http://localhost:8080/employee/2
Response :
[{"id":"1", "firstname":"James", "lastname":"Johnson", "address":{"city":"Hoseynabad", "state":"Kavir"}}, {"id":"3", "firstname":"Roger", "lastname":"Ponting", "address":{"city":"San Pedro", "state":"LA"}}]