This is a creation in Article, where the information may have evolved or changed.
First write a server that can receive the POST request:
Package Mainimport ("FMT" "Net/http") func Main () {http. Handlefunc ("/postpage", func (w http). Responsewriter, R *http. Request) {//accepts a POST request and then prints the value of the key and Value fields in the form if R.method = = "POST" {var (key string = R.postformvalue ("key") value String = R.postformvalue ("value")) FMT. Printf ("Key is :%s\n", key) Fmt. PRINTF ("value is:%s\n", Value)}) Err: = http. Listenandserve (": +", nil) if err! = Nil {fmt. Println (Err. Error ()) return}}
We then use the Net/http package to send the POST request:
Package Mainimport ("FMT" "Net/http" "Net/url") func main () {//Here Add the body content of the post data: = Make (URL. Values) data["key"] = []string{"This was key"}data["value"] = []string{"This is value"}//send the Post form to the target server res, err: = http. Postform ("Http://127.0.0.1/postpage", data) if err! = Nil {fmt. Println (Err. Error ()) Return}defer Res. Body.close () fmt. Println ("Post send Success")}
If you do not want to use a ready-made package, then the following code is directly through the HTTP protocol implementation of the POST request, the effect is the same as the above code:
Package Mainimport ("FMT" "NET") Func main () {///Because the Post method belongs to the HTTP protocol, the HTTP protocol is based on TCP, so first establish a//TCP connection, Send our POST request via this TCP connection conn, err: = Net. Dial ("TCP", "127.0.0.1:80") if err! = Nil {fmt. Println (Err. Error ()) Return}defer Conn. Close ()//construct POST request var post stringpost + = "Post/postpage http/1.1\r\n" post + = "content-type:application/ X-www-form-urlencoded\r\n "Post + =" content-length:37\r\n "post + =" connection:keep-alive\r\n "post + =" Accept-language : zh-cn,zh;q=0.8,en;q=0.6\r\n "post + =" \ r \ n "Post + =" Key=this is Key&value=this is value\r\n "If _, ERR: = conn. Write ([]byte (POST)); Err! = Nil {fmt. Println (Err. Error ()) return}fmt. Println ("Post send success.")}
Run the first code of the program, and then run the second or third program to send a POST request, run the result
If reproduced please specify the source: http://blog.csdn.net/gophers/article/details/22870185