How to create a simple RESTful API server with CRUD operations in Go?

To create a simple RESTful API server with CRUD operations in Go, you can follow these steps:

  1. Create a new Go module for your project:
$ go mod init <module_name>
  1. Import the required packages:
package main import ( "encoding/json" "log" "net/http" "github.com/gorilla/mux" )
  1. Define a struct for your data model:
type Todo struct { ID string `json:"id,omitempty"` Title string `json:"title,omitempty"` Completed bool `json:"completed,omitempty"` }
  1. Implement the CRUD handlers:
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) }
  1. Define and configure your routes:
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)) }
  1. Build and run your application:
$ 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.