Article directory
[Go language programming notes (1)]
Go Post/Get request&&data processing
Preface
We know that in web services, post/get requests are usually used, but the corresponding requests are basically made through Postman.
Now that there is a business need, we make the request directly internally. How to do it? And how to process the obtained psot request data?
1. net/http
Get request[No nonsense, direct code]
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
response, err := http.Get("http://www.baidu.com")
if err != nil {
// handle error
}
//程序在使用完回复后必须关闭回复的主体。
defer response.Body.Close()
body, _ := ioutil.ReadAll(response.Body)
fmt.Println(string(body))
}
Post request[No nonsense, direct code]
package main
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
)
func main() {
//body := "{\"action\":20}"
body := "{\"BPM\":20}"
res, err := http.Post("http://localhost:8080/", "application/json;charset=utf-8", bytes.NewBuffer([]byte(body)))
if err != nil {
fmt.Println("Fatal error ", err.Error())
}
defer res.Body.Close()
content, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println("Fatal error ", err.Error())
}
fmt.Println(string(content))
}
Among them the content in body is actually the data you need to enter in postman:
Pay special attention to the escape character "" .
2. How to process the data obtained by Post? ?
1.string Convert ASCII to string
The code is as follows (example):
content, err := ioutil.ReadAll(res.Body)
fmt.Println(string(content))
2.json and struct data binding
The code is as follows (example):
type people struct {
name string `json:"name"`
age int `json:"age"`
id int `json:"id"`
}
## json.Unmarshal packs string into json The code is as follows (example):
var someOne student
if err := json.Unmarshal([]byte(msg), &someOne); err == nil {
fmt.Println(someOne)
fmt.Println(someOne.people)
} else {
fmt.Println(err)
}
Summarize
The above is about how to convert Post data into json and bind it to struct, which is simple and efficient.