在本教程中,我们将解释如何在Golang中创建REST API。
REST(Representational State Transfer)是最常用的接口,用于填充动态数据和执行操作,如添加、更新和删除网络应用。REST APIs在各种应用中都被用来进行GET、POST、PUT或DELETE等HTTP请求,对数据进行CRUD操作。
在本教程中,我们将解释如何用Golang创建简单的REST API来对动态数据执行GET、POST、DELETE和PUT操作。我们将主要关注这个的基本概念,所以我们将对员工的JSON数据而不是数据库执行操作。所以你可以根据你的应用需求,通过与数据库的连接来使用它。
所以,让我们继续编写代码,在Golang中创建REST API。
1.创建服务器来处理API请求
我们需要创建服务器来处理对API的HTTP请求。所以我们将在main.go 文件中创建一个函数apiRequests() ,并在func main() 中调用。这个函数apiRequests() 将处理所有对根URL的请求。
package main
import (
"fmt"
"log"
"net/http"
)
func homePage(w http.ResponseWriter, r *http.Request){
fmt.Fprintf(w, "Welcome to the API Home page!")
}
func apiRequests() {
http.HandleFunc("/", homePage)
log.Fatal(http.ListenAndServe(":3000", nil))
}
func main() {
apiRequests()
}
当我们运行上述代码时,API将在第3000帖开始。URLhttp://localhost:3000/ 将被加载到浏览器上,并看到API主页的欢迎信息,这意味着我们已经创建了REST API的基础。
2.为REST API创建雇员假数据
在本教程中,我们将创建简单的REST API来执行CRUD操作 GET, POST, DELETE and PUT 雇员数据。我们将在func main() 中创建一些假的雇员数据。我们将执行
func main() {
Employees = []Employee{
Employee{Id: "1", Name: "Jhon Smith", Address: "New Jersy USA", Salary: "20000"},
Employee{Id: "2", Name: "William", Address: "Wellington Newziland", Salary: "12000"},
Employee{Id: "3", Name: "Adam", Address: "London England", Salary: "15000"},
}
}
3.获取所有员工数据
现在我们将开始实现我们的REST API方法。我们将实现函数getAllEmployees() ,以获得所有雇员的数据。
func getAllEmployees(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(Employees)
}
我们还将处理路由,并在动作employees 中调用函数getAllEmployees() ,以获得所有JSON格式的雇员。我们将使用基于gorilla/mux 的HTTP 路由器来代替标准库,并在本教程的例子中使用。
func apiRequests() {
route := mux.NewRouter().StrictSlash(true)
route.HandleFunc("/employees", getAllEmployees)
log.Fatal(route.ListenAndServe(":3000", route))
}
当我们在方法GET 上加载URLhttp://localhost:3000/employees 时,它将以JSON格式显示所有雇员。
{"Id":"1","Name":"Jhon Smith","Address":"New Jersy USA","Salary":"20000"},
{"Id":"2","Name":"William","Address":"Wellington Newziland","Salary":"12000"},
{"Id":"3","Name":"Adam","Address":"London England","Salary":"15000"}
我们也可以通过传递雇员ID来获得特定的雇员记录。为此,我们将创建函数getEmployee() 来获取雇员数据。
func getEmployee(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
key := vars["id"]
for _, employee := range Employees {
if employee.Id == key {
json.NewEncoder(w).Encode(employee)
}
}
}
我们将调用函数getEmployee() 在路由/employee/{id} ,以获得雇员的ID。
func apiRequests() {
route := mux.NewRouter().StrictSlash(true)
route.HandleFunc("/employee/{id}", getEmployee)
log.Fatal(http.ListenAndServe(":3000", route))
}
当我们加载URLhttp://localhost:3000/employee/3 时,它将以JSON格式显示该ID的雇员。
{"Id":"3","Name":"Adam","Address":"London England","Salary":"15000"}
4.创建雇员记录
我们将实现创建一个新的雇员记录的功能。我们将创建函数createEmployee() 来添加一个新的雇员记录。
func createEmployee(w http.ResponseWriter, r *http.Request) {
reqBody, _ := ioutil.ReadAll(r.Body)
var employee Employee
json.Unmarshal(reqBody, &employee)
Employees = append(Employees, employee)
json.NewEncoder(w).Encode(employee)
}
我们将在方法POST 和路由employee 上调用函数createEmployee() 来发布雇员的详细信息,以添加一个新的记录。
func apiRequests() {
route.HandleFunc("/employee", createEmployee).Methods("POST")
log.Fatal(http.ListenAndServe(":3000", route))
}
当我们运行我们的API和POST ,并使用下面的post body,它将创建一个新的雇员记录。
{
"Id": "4",
"Name": "Peter",
"Address": "London, UK",
"Salary": "40000"
}
当我们访问带有雇员ID 4的URL,如http://localhost:3000/employee/4 ,它将以JSON格式显示雇员的ID。
{"Id":"4","Name":"Peter","Address":"London, UK","Salary":"40000"}
5.删除雇员记录
我们将通过创建函数deleteEmployee() 来实现删除雇员的功能。
func deleteEmployee(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
for index, employee := range Employees {
if employee.Id == id {
Employees = append(Employees[:index], Employees[index+1:]...)
}
}
}
我们将在路由/employee/{id} 上调用函数deleteEmployee() 来删除雇员。
func apiRequests() {
route := mux.NewRouter().StrictSlash(true)
route.HandleFunc("/employee/{id}", deleteEmployee).Methods("DELETE")
log.Fatal(http.ListenAndServe(":3000", route))
}
当我们用DELETE 方法向URLhttp://localhost:3000/employee/3 发出HTTP请求,并附上雇员ID。它将删除该雇员。
6.完整的REST API代码
下面是这个例子的完整运行代码。
package main
import (
"encoding/json"
"fmt"
"log"
"io/ioutil"
"net/http"
"github.com/gorilla/mux"
)
type Employee struct {
Id string `json:"Id"`
Name string `json:"Name"`
Address string `json:"Address"`
Salary string `json:"Salary"`
}
var Employees []Employee
func homePage(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome to the API Home page!")
}
func getAllEmployees(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(Employees)
}
func getEmployee(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
key := vars["id"]
for _, employee := range Employees {
if employee.Id == key {
json.NewEncoder(w).Encode(employee)
}
}
}
func createEmployee(w http.ResponseWriter, r *http.Request) {
reqBody, _ := ioutil.ReadAll(r.Body)
var employee Employee
json.Unmarshal(reqBody, &employee)
Employees = append(Employees, employee)
json.NewEncoder(w).Encode(employee)
}
func deleteEmployee(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
for index, employee := range Employees {
if employee.Id == id {
Employees = append(Employees[:index], Employees[index+1:]...)
}
}
}
func apiRequests() {
route := mux.NewRouter().StrictSlash(true)
route.HandleFunc("/", homePage)
route.HandleFunc("/employees", getAllEmployees)
route.HandleFunc("/employee", createEmployee).Methods("POST")
route.HandleFunc("/employee/{id}", deleteEmployee).Methods("DELETE")
route.HandleFunc("/employee/{id}", getEmployee)
log.Fatal(http.ListenAndServe(":3000", route))
}
func main() {
Employees = []Employee{
Employee{Id: "1", Name: "Jhon Smith", Address: "New Jersy USA", Salary: "20000"},
Employee{Id: "2", Name: "William", Address: "Wellington Newziland", Salary: "12000"},
Employee{Id: "3", Name: "Adam", Address: "London England", Salary: "15000"},
}
apiRequests()
}
总结
在本教程中,我们已经实现了HTTP方法GET 、POST 和DELETE 来读取、添加和删除雇员数据。我们没有实现PUT 方法来更新雇员数据。你可以在你的终端进行尝试,并分享你的建议,如果有任何关于这一点。