GoLang Gin框架restful接口
Gin框架实现restful风格的API
Get、Post、Put、Delete
1、主函数
func main() {
router := gin.Default()
router.GET("/students", getAllStudent)
router.GET("/students/:id", getStudentById)
router.POST("/students", addStudent)
router.PUT("/students", updateStudent)
router.DELETE("/students/:id", deleteStudent)
_ = router.Run("localhost:8080")
}
2、Get
func getAllStudent(context *gin.Context) {
context.IndentedJSON(http.StatusOK, classInfo)
}
func getStudentById(context *gin.Context) {
id := context.Param("id")
for _, student := range classInfo {
if student.ID == id {
context.IndentedJSON(http.StatusOK, student)
return
}
}
context.IndentedJSON(http.StatusNotFound, gin.H{"message": "album not found"})
}
3、Post
func addStudent(context *gin.Context) {
var student Student
if err := context.BindJSON(&student); err != nil {
context.IndentedJSON(http.StatusOK, "params error")
return
}
classInfo = append(classInfo, student)
context.IndentedJSON(http.StatusCreated, student)
}
4、Put
func updateStudent(context *gin.Context) {
var student Student
if err := context.BindJSON(&student); err != nil {
context.IndentedJSON(http.StatusOK, "params error")
return
}
for i, s := range classInfo {
if s.ID == student.ID {
classInfo[i] = student
context.IndentedJSON(http.StatusOK, "update success")
return
}
}
context.IndentedJSON(http.StatusNotFound, "not found student")
}
5、Delete
func deleteStudent(context *gin.Context) {
id := context.Param("id")
var k int = 0
for _, student := range classInfo {
if student.ID != id {
classInfo[k] = student
k++
}
}
classInfo = classInfo[:k]
context.IndentedJSON(http.StatusOK, "delete success")
}