Home >Backend Development >Golang >How to get JSON data from server using REST API in Golang?
Steps to obtain JSON data in Golang: Create an HTTP client; use HTTP requests to specify the request method, URL and request body; add HTTP headers; perform HTTP requests; check the response status code; parse the JSON response.
In Golang, you can use the net/http
package easily Get JSON data from REST API. Here's how to do it:
You need to create a client for making HTTP requests.
// 创建一个新的 HTTP 客户端 client := &http.Client{}
Construct an HTTP request, specify the request method, URL and request body (if necessary).
// 创建一个新的 HTTP 请求 req, err := http.NewRequest(method, url, body) if err != nil { fmt.Println(err) return }
You can add HTTP headers to the request as needed.
// 添加 HTTP 头 req.Header.Add("Content-Type", "application/json")
Use the client to perform HTTP requests.
// 执行 HTTP 请求 resp, err := client.Do(req) if err != nil { fmt.Println(err) return }
Check the response status code to ensure the request was successful.
// 检查响应状态代码 if resp.StatusCode != http.StatusOK { fmt.Println("请求失败: ", resp.Status) return }
Use the JSON decoder to decode the JSON response.
// 创建 JSON 解码器 decoder := json.NewDecoder(resp.Body) // 解析 JSON 响应 var data interface{} if err := decoder.Decode(&data); err != nil { fmt.Println(err) return }
Suppose you want to get user data from JSONPlaceholder API, you can use the following code:
func main() { // 创建 HTTP 请求 resp, err := http.Get("https://jsonplaceholder.typicode.com/users") if err != nil { fmt.Println(err) return } // 检查状态代码 if resp.StatusCode != 200 { fmt.Println(resp.Status) return } // 解析 JSON 响应 var users []map[string]interface{} decoder := json.NewDecoder(resp.Body) if err := decoder.Decode(&users); err != nil { fmt.Println(err) return } // 打印用户名称 for _, user := range users { fmt.Println(user["name"]) } }
This is how to get from the server using REST API in Golang Methods for JSON data.
The above is the detailed content of How to get JSON data from server using REST API in Golang?. For more information, please follow other related articles on the PHP Chinese website!