Go language get post mode JSON

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.
Learning go language, read a document for a period of time, want to write a server, when the interface data to find the data, the format of "Form-data" data is the simplest,</span>
Incoming post JSON data: {"username": "", "Password": "123456"}
<span style= "font-family:arial, Helvetica, Sans-serif;" >req. Postform</span>
Req. Header.get ("Content-type") req. Hostreq.Formreq.FormValue ("username") req. Formvalue ("password")

When you get the "Application/json", you need to deal with it (get only string below):

Package Utilsimport ("bytes" "Io/ioutil" "net/http")/** gets the body's data (JSON) converted to string* bytes to String*/func getdatastring ( Req *http. Request) String {result, err: = Ioutil. ReadAll (req. Body) If err! = Nil {return "{\" code\ ": 1,\" msg\ ": \" failed\ "}"} else {return bytes. Newbuffer (Result). String ()}}

When you get the "Application/json", you need to deal with it (just get the JSON to map):

Packages that need to be introduced, "Io/ioutil", "Net/http", "Encoding/json"

var user map[string]interface{}body, _: = Ioutil. ReadAll (req. Body) JSON. Unmarshal (body, &user) fmt. Println ("Get username in JSON:", user["username"]) fmt. PRINTLN ("Get Password in JSON:", user["password"]. ( String)//Turn string to determine length through Len (password)!=0

Comparison of data obtained:

Byte[]

[123 34 117 115 101 114 110 97 109 101 34 58 34 115 121 115 116 101 109 34 44 34 112 97 115 115 119 111 114 100 34 58 34 4 9 50 51 52 53 54 34 125]
String
{"username": "System", "Password": "123456"}

Map

Map[username:system password:123456]







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.