Golang get and POST request sending and parsing for Web programming

Source: Internet
Author: User

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


Package Mainimport (        "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 ());       If err! = Nil {               log. Fatal (ERR) return         }       result, err: = Ioutil. ReadAll (Res. Body)         Res. Body.close ()         if err! = 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 Server struct {ServerName string ServerIP string}type serverslice struct {S        ervers []server serversid string}func Main () {var s serverslice  var NewServer Server;        Newserver.servername = "Guangzhou_vpn"; Newserver.serverip = "127.0.0.1" s.servers = Append (S.servers, newserver)   s.servers = append (s.s  Ervers, 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)         if err! = 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)          If Err! = Nil {                 Log. Fatal (ERR)                 return        }        result, err: = Ioutil. ReadAll (Res. Body)         Res. Body.close ()         if err! = Nil {                 log. Fatal (ERR)               &NBSp return       }        FMT. Printf ("%s", result)}


Third, the Server


Package Mainimport ("FMT" "Net/http" "Strings" "html" "Io/ioutil" "Encoding/jso n ") type Server struct {ServerName string ServerIP string}type serverslice struct {Servers []serve R serversid String}func Main () {  HTTP. Handlefunc ("/", handler) HTTP. Listenandserve (": 9001", nil)}func Handler (w http. Responsewriter, R *http. Request) {r.parseform ()//parse parameter, default is FMT not resolved. fprintf (W, "Hi, I Love you%s", HTML. Escapestring (R.url. Path[1:]))  if R.method = = "GET" { fmt. Println ("Method:", R.method)//Get the method requested by FMT. Println ("username", r.form["username"]) fmt. PRINTLN ("Password", r.form["password"]) for k, V: = Range R.form { fmt.                       Print ("Key:", K, ";")  fmt. Println ("Val:", Strings. Join (V, ""))  }} else if R.method = = "POST" {&nbsp result, _:= Ioutil. ReadAll (R.body)  r.body.close ()  fmt. The recommended handling method for Printf ("%s\n", result)//unknown type  var f interface{}  json.                       Unmarshal (result, &f) m: = f. (map[string]interface{})  for K, V: = range m {                                        switch VV: = V. (type) { case string:  fmt. Println (k, "is string", vv)  case int:  fmt. Println (k, "is int", VV)  case float64:  fmt . Println (K, "is Float64", vv)  case []interface{}: & Nbsp;fmt.                                               Println (K, "is an array:")  for i, U: = Range VV { &nbsP;fmt.                                       Println (i, U)  }  default:  fmt. Println (K, "is of a type I don ' t know how to Handle")}  } /struct known, resolves to struct  var s serverslice;     json. Unmarshal ([]byte (Result), &s)           FMT. Println (S.SERVERSID);           for i:=0; I<len (s.servers); i++ {                FMT. Println (S.servers[i]. ServerName)                   FMT . Println (S.servers[i]. ServerIP)         } }}



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.