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.

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{  ServerNamestring  ServerIPstring}type Serverslicestruct{  Servers []server  Serversidstring}func Main () {  varS Serverslice  varNewServer 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{  ServerNamestring  ServerIPstring}type Serverslicestruct{  Servers []server  Serversidstring}func Main () {  http. Handlefunc ("/", handler)  http. Listenandserve (": 9001", nil)}func Handler (w http. Responsewriter, R *http. Request) {  R.parseform ()//parse parameter, default is not resolved  Fmt. 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 request    Fmt. 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 methods    varFInterface{}    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<len (s.servers); i++ {      Fmt. Println (S.servers[i]. ServerName)      Fmt. Println (S.servers[i]. ServerIP)    }  } }

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.