-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
94 lines (78 loc) · 2.44 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package main
import (
"net/http"
"strconv"
"github.com/labstack/echo/v4"
)
// Inisiasi Constructor Data
type Student struct {
ID int `json:"id"`
Name string `json:"name"`
Age int `json:"age"`
Grade string `json:"grade"`
}
// Inisiasi Database (Simpan di dalam slice)
var students []Student
func main() {
// Inisiasi Echo Framework
e := echo.New()
// Routing
e.GET("/students", getStudents) // Mendapatkan semua data siswa
e.GET("/students/:id", getStudentByID) // Mendapatkan data siswa berdasarkan ID
e.POST("/students", createStudent) // Menambahkan data siswa
e.PUT("/students/:id", updateStudent) // Mengubah data siswa berdasarkan ID
e.DELETE("/students/:id", deleteStudent) // Menghapus data siswa berdasarkan ID
e.Logger.Fatal(e.Start(":8080"))
}
// Mendapatkan semua data siswa dan mengembalikan HTTP Status
func getStudents(c echo.Context) error {
return c.JSON(http.StatusOK, students)
}
// Mendapatkan data siswa berdasarkan ID dan mengembalikan HTTP Status
func getStudentByID(c echo.Context) error {
id, _ := strconv.Atoi(c.Param("id"))
for _, student := range students {
if student.ID == id {
return c.JSON(http.StatusOK, student)
}
}
return c.JSON(http.StatusNotFound, "Student Not Found")
}
// Menambahkan data siswa dan mengembalikan HTTP Status
func createStudent(c echo.Context) error {
student := new(Student)
if err := c.Bind(student); err != nil {
return err
}
student.ID = len(students) + 1
students = append(students, *student)
return c.JSON(http.StatusCreated, student)
}
// Mengubah data siswa berdasarkan ID dan mengembalikan HTTP Status
func updateStudent(c echo.Context) error {
id, _ := strconv.Atoi(c.Param("id"))
for i, student := range students {
if student.ID == id {
updatedStudent := new(Student)
if err := c.Bind(updatedStudent); err != nil {
return err
}
students[i].Name = updatedStudent.Name
students[i].Age = updatedStudent.Age
students[i].Grade = updatedStudent.Grade
return c.JSON(http.StatusOK, students[i])
}
}
return c.JSON(http.StatusNotFound, "Student Not Found")
}
// Menghapus data siswa berdasarkan ID dan mengembalikan HTTP Status
func deleteStudent(c echo.Context) error {
id, _ := strconv.Atoi(c.Param("id"))
for i := range students {
if students[i].ID == id {
students = append(students[:i], students[i+1:]...)
return c.NoContent(http.StatusNoContent)
}
}
return c.JSON(http.StatusNotFound, "Student Not Found")
}