Go HTTP pass JSON data

Source: Internet
Author: User

The server and client of Go HTTP are briefly described in the previous blog post. This article describes how to pass data in JSON format in HTTP.

Server
Package Mainimport ("Encoding/json" "FMT" "html" "Io/ioutil" "Log" "Net/http") Type CMD struct {reqtype int FileName string}func Main () {http. Handlefunc ("/bar", func (w http). Responsewriter, R *http. Request) {fmt. fprintf (W, "Hello,%q", HTML. Escapestring (R.url. Path)) If R.method = = "POST" {b, err: = Ioutil. ReadAll (r.body) if err! = Nil {log. Println ("Read failed:", err)} defer r.body.close () c MD: = &cmd{} err = json. Unmarshal (b, cmd) if err! = Nil {log. PRINTLN ("JSON format error:", err)} log. Println ("cmd:", cmd)} else {log. PRINTLN ("Only support Post") fmt. Fprintf (W, "only support Post")}) log. Fatal (http. Listenandserve (": 8080", nil))}

Receive data for JSON decoding.

Client
package mainimport (        "bytes"        "io/ioutil"        "log"        "net/http")func main() {        url := "http://127.0.0.1:8080/bar"        contentType := "application/json;charset=utf-8"        b := []byte("Hello, Server")        body := bytes.NewBuffer(b)        resp, err := http.Post(url, contentType, body)        if err != nil {                log.Println("Post failed:", err)                return        }        defer resp.Body.Close()        content, err := ioutil.ReadAll(resp.Body)        if err != nil {                log.Println("Read failed:", err)                return        }        log.Println("content:", string(content))}

The data to be sent is converted to JSON format and sent.

Reference

http://www.01happy.com/golang-http-client-get-and-post/
http://blog.csdn.net/typ2004/article/details/38669949

Go HTTP pass JSON data

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.