Home > Article > Backend Development > How to build a RESTful API and process JSON responses using Golang?
How to build and process a RESTful API with JSON responses using Golang Steps: Create a Golang project and install Gorilla Mux. Define routes and handle HTTP requests. Install the JSON codec package to use the JSON codec. Handles requests based on the request method and converts the data to JSON and writes the response.
1. Create a Golang project
go mod init <project-name>
2. Install Gorilla Mux Routing package
go get github.com/gorilla/mux
3. Define routing
import ( "github.com/gorilla/mux" "net/http" ) func main() { router := mux.NewRouter() router.HandleFunc("/", HomeHandler).Methods("GET") // ... 其他路由定义 http.ListenAndServe(":8080", router) }
4. Process HTTP request
func HomeHandler(w http.ResponseWriter, r *http.Request) { // 根据请求方法处理请求 switch r.Method { case "GET": // ... 处理 GET 请求 case "POST": // ... 处理 POST 请求 // ... 其他方法处理 } }
1. Install the JSON codec package
go get github.com/json-iterator/go
2. Use the JSON codec
import ( "encoding/json" "fmt" "net/http" ) func WriteJSONResponse(w http.ResponseWriter, data interface{}) { w.Header().Set("Content-Type", "application/json") if err := json.NewEncoder(w).Encode(data); err != nil { // 处理错误 } }
Example API: Get all users
Route definition:
router.HandleFunc("/users", GetAllUsersHandler).Methods("GET")
Request handler:
import ( "net/http" "github.com/json-iterator/go" ) // ... func GetAllUsersHandler(w http.ResponseWriter, r *http.Request) { users := [...]UserModel{ {ID: 1, Name: "John Doe"}, {ID: 2, Name: "Jane Doe"}, } // 将用户模型转换为 JSON 并写入响应 WriteJSONResponse(w, users) }
Client:
Send a GET request to the /users
endpoint and parse the JSON response.
The above is the detailed content of How to build a RESTful API and process JSON responses using Golang?. For more information, please follow other related articles on the PHP Chinese website!