This article shows the steps to build a RESTful API using Golang, including importing the necessary packages, creating a router, defining handlers, registering routes, and starting the server. In addition, instructions are provided for handling error conditions, such as returning error messages and correct HTTP status codes.
Building a RESTful API in Golang is simple and efficient. This article will take you step by step to understand how to create an API and Handle common error scenarios.
import ( "encoding/json" "fmt" "log" "net/http" "github.com/gorilla/mux" )
r := mux.NewRouter()
func indexHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Hello, World!") } func postHandler(w http.ResponseWriter, r *http.Request) { var data map[string]interface{} if err := json.NewDecoder(r.Body).Decode(&data); err != nil { http.Error(w, "Invalid JSON", http.StatusBadRequest) return } log.Printf("Received data: %v", data) json.NewEncoder(w).Encode(map[string]interface{}{"status": "success"}) }
r.HandleFunc("/", indexHandler).Methods("GET") r.HandleFunc("/post", postHandler).Methods("POST")
http.ListenAndServe(":8080", r)
Create a simple API to store and retrieve user data:
type User struct { Name string `json:"name"` Email string `json:"email"` } func userHandler(w http.ResponseWriter, r *http.Request) { switch r.Method { case "GET": json.NewEncoder(w).Encode([]User{{Name: "John", Email: "john@example.com"}}) case "POST": var user User if err := json.NewDecoder(r.Body).Decode(&user); err != nil { http.Error(w, "Invalid JSON", http.StatusBadRequest) return } fmt.Fprint(w, "User created:", user) default: http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) } }
Then register the route:
r.HandleFunc("/users", userHandler)
Now you can easily test the API using curl
or other tools:
curl -X GET localhost:8080/users
The above is the detailed content of How to build a RESTful API and handle errors using Golang?. For more information, please follow other related articles on the PHP Chinese website!