To create a simple RESTful API server with CRUD operations in Go, you can follow these steps:
$ go mod init <module_name>
package main
import (
"encoding/json"
"log"
"net/http"
"github.com/gorilla/mux"
)
type Todo struct {
ID string `json:"id,omitempty"`
Title string `json:"title,omitempty"`
Completed bool `json:"completed,omitempty"`
}
var todos []Todo
func GetTodos(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(todos)
}
func CreateTodo(w http.ResponseWriter, r *http.Request) {
var todo Todo
json.NewDecoder(r.Body).Decode(&todo)
todo.ID = uuid.New().String()
todos = append(todos, todo)
json.NewEncoder(w).Encode(todo)
}
func UpdateTodo(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
for index, item := range todos {
if item.ID == params["id"] {
todos = append(todos[:index], todos[index+1:]...)
var todo Todo
json.NewDecoder(r.Body).Decode(&todo)
todo.ID = params["id"]
todos = append(todos, todo)
json.NewEncoder(w).Encode(todo)
return
}
}
}
func DeleteTodo(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
for index, item := range todos {
if item.ID == params["id"] {
todos = append(todos[:index], todos[index+1:]...)
break
}
}
json.NewEncoder(w).Encode(todos)
}
func main() {
router := mux.NewRouter()
todos = append(todos, Todo{ID: "1", Title: "Task 1", Completed: false})
todos = append(todos, Todo{ID: "2", Title: "Task 2", Completed: true})
router.HandleFunc("/todos", GetTodos).Methods("GET")
router.HandleFunc("/todos", CreateTodo).Methods("POST")
router.HandleFunc("/todos/{id}", UpdateTodo).Methods("PUT")
router.HandleFunc("/todos/{id}", DeleteTodo).Methods("DELETE")
log.Fatal(http.ListenAndServe(":8000", router))
}
$ go build
$ ./<module_name>
Now you have a simple RESTful API server in Go with CRUD operations. You can use tools like curl
or Postman to test the endpoints.