Golang get and POST request sending and parsing for Web programming

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Golang get and POST request sending and parsing for Web programming

Time 2014-08-19 15:26:48 CSDN Blog original http://blog.csdn.net/typ2004/article/details/38669949

This article is an introductory article that introduces the techniques used by Golang Web programming through a simple example.

The structure of the article includes:

    1. Client-get Request
    2. Client-post Request
    3. Server processes Get and Post data

In the encapsulation of data, we use JSON in part, so this article also involves the encoding and decoding of JSON in Golang.

First, Client-get

 PackageMainimport ("FMT""Net/url""Net/http""Io/ioutil""Log") Func main () {u,_: = URL. Parse ("Http://localhost:9001/xiaoyue")Q: = U.query ()Q. Set ("username","User")Q. Set ("Password","passwd") U.rawquery =Q. Encode () res, err: = http. Get (U.string ());ifErr! = Nil {Log. Fatal (ERR)return}result, err: = Ioutil. ReadAll (Res. Body) Res. Body.close ()ifErr! = Nil {Log. Fatal (ERR)return} FMT. Printf ('%s', result)}

Second, Client-post

Package Mainimport ("FMT""Net/url""Net/http""Io/ioutil""Log""bytes""Encoding/json") Type Serverstruct{ServerNamestringServerIPstring}type Serverslicestruct{Servers []serverserversidstring}func Main () {varS ServerslicevarNewServer Server;newserver.servername ="Guangzhou_vpn"; Newserver.serverip ="127.0.0.1"S.servers = Append (s.servers, newserver) s.servers = append (S.servers, Server{servername:"Shanghai_vpn", ServerIP:"127.0.0.2"}) S.servers = Append (S.servers, Server{servername:"Beijing_vpn", ServerIP:"127.0.0.3"}) S.serversid ="team1"B, err: = json. Marshal (s)ifErr! = Nil {fmt. Println ("JSON err:", err)}body: = bytes. Newbuffer ([]byte(b)) Res,err: = http. Post ("Http://localhost:9001/xiaoyue","Application/json;charset=utf-8", body)ifErr! = Nil {log. Fatal (ERR)return}result, err: = Ioutil. ReadAll (Res. Body) Res. Body.close ()ifErr! = Nil {log. Fatal (ERR)return}fmt. Printf ('%s ', result)}
Package Mainimport ("FMT""Net/http""Strings""HTML""Io/ioutil""Encoding/json") Type Serverstruct{ServerNamestringServerIPstring}type Serverslicestruct{Servers []serverserversidstring}func Main () {http. Handlefunc ("/", handler) HTTP. Listenandserve (": 9001", nil)}func Handler (w http. Responsewriter, R *http. Request) {r.parseform ()//parse parameter, default is not resolvedFmt. fprintf (W,"Hi, I Love you%s"Html. Escapestring (R.url. path[1:]))ifR.method = ="GET"{FMT. Println ("Method:", R.method)//How to get the requestFmt. Println ("username", r.form["username"]) FMT. Println ("Password", r.form["Password"]) forK, V: = Range R.form {fmt. Print ("key:"K"; ") FMT. Println ("val:", strings. Join (V,""))}}Else ifR.method = ="POST"{result, _:= ioutil. ReadAll (R.body) r.body.close () fmt. Printf ("%s\n", result)//unknown types of recommended processing methodsvarFInterface{}json. Unmarshal (result, &f) m: = f. (map[string]Interface{}) forK, V: = range m {SwitchVV: = V. (type) { Case string: FMT. Println (k,"is string", VV) Case int: FMT. Println (k,"is int", VV) CaseFloat64:fmt. Println (k,"is Float64", VV) Case[]Interface{}:fmt. Println (k,"is an array:") forI, U: = Range VV {fmt. Println (I, U)}default: FMT. Println (k,"is of a type I don ' t know what to handle")  }  }//structure known, parse to struct vars serverslice; Json. Unmarshal ([]byte(result), &s) fmt. Println (S.SERVERSID); fori:=0; I
 
  < pre="">
 
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.