golang 请求添加json

发布时间:2024-07-05 01:01:10

Golang请求与JSON处理 Introduction Golang (or Go) is a powerful and efficient programming language that has gained popularity in recent years. It provides built-in support for making HTTP requests and handling JSON data. In this article, we will explore how to make HTTP requests and work with JSON in Golang. HTTP Requests When working with HTTP requests in Go, the standard library package "net/http" provides a rich set of functionalities. You can send HTTP GET, POST, PUT, DELETE requests, and more. Let's dive into some examples. GET Request To make a GET request in Go, we use the "net/http" package's "Get" function. Here's an example: H2: Making a GET Request P: ```go package main import ( "fmt" "net/http" "io/ioutil" ) func main() { response, err := http.Get("https://api.example.com/users") if err != nil { fmt.Println("Error:", err) return } defer response.Body.Close() body, err := ioutil.ReadAll(response.Body) if err != nil { fmt.Println("Error:", err) return } fmt.Println(string(body)) } ``` In the code above, we import the necessary packages, make the GET request to "https://api.example.com/users", and read the response body. Finally, we print the response body as a string. POST Request To send a POST request with JSON payload, we need to set the "Content-Type" header as "application/json" and provide the JSON data in the request body. Here's an example: H2: Sending a POST Request P: ```go package main import ( "fmt" "bytes" "net/http" ) func main() { url := "https://api.example.com/users" jsonStr := []byte(`{"name":"John","email":"john@example.com"}`) req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr)) if err != nil { fmt.Println("Error:", err) return } req.Header.Set("Content-Type", "application/json") client := &http.Client{} response, err := client.Do(req) if err != nil { fmt.Println("Error:", err) return } defer response.Body.Close() fmt.Println("Status:", response.Status) } ``` In the code above, we create a new POST request using the "http.NewRequest" function. We set the "Content-Type" header and provide the JSON data in the request body. Then, we send the request using an HTTP client and print the response status. JSON Handling Golang provides a built-in package called "encoding/json" for working with JSON data. This package allows us to marshal Go objects into JSON strings and unmarshal JSON strings into Go objects. Marshaling JSON To convert a Go object into a JSON string, we use the "json.Marshal" function. Here's an example: H2: Marshaling JSON P: ```go package main import ( "fmt" "encoding/json" ) type User struct { Name string `json:"name"` Email string `json:"email"` } func main() { user := User{Name: "John", Email: "john@example.com"} jsonStr, err := json.Marshal(user) if err != nil { fmt.Println("Error:", err) return } fmt.Println(string(jsonStr)) } ``` In the code above, we define a struct called "User" with two fields "Name" and "Email". We create a new "User" instance and marshal it into a JSON string using the "json.Marshal" function. Finally, we print the JSON string. Unmarshaling JSON To convert a JSON string into a Go object, we use the "json.Unmarshal" function. Here's an example: H2: Unmarshaling JSON P: ```go package main import ( "fmt" "encoding/json" ) type User struct { Name string `json:"name"` Email string `json:"email"` } func main() { jsonStr := []byte(`{"name":"John","email":"john@example.com"}`) var user User err := json.Unmarshal(jsonStr, &user) if err != nil { fmt.Println("Error:", err) return } fmt.Println(user) } ``` In the code above, we define the same "User" struct. We create a JSON string and unmarshal it into the "user" variable using the "json.Unmarshal" function. Finally, we print the "user" object, which will have the values from the JSON string. Conclusion Golang provides powerful tools for making HTTP requests and handling JSON data. With the "net/http" package, we can easily send various types of requests. Additionally, the "encoding/json" package allows us to marshal and unmarshal JSON data effortlessly. By combining these capabilities, Golang offers a seamless experience when working with JSON API endpoints.

相关推荐