Go语言Web编程实现Get和Post请求发送与解析的方法详解
本文实例讲述了Go语言Web编程实现Get和Post请求发送与解析的方法。分享给大家供大家参考,具体如下:
这是一篇入门文章,通过一个简单的例子介绍Golang的Web编程主要用到的技术。
文章结构包括:
1.Client-Get请求
2.Client-Post请求
3.Server处理Get和Post数据
在数据的封装中,我们部分采用了json,因而本文也涉及到Golang中json的编码和解码。
一、Client-Get
packagemain
import(
       "fmt"
       "net/url"
       "net/http"
       "io/ioutil"
       "log"
)
funcmain(){
       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)
}
二、Client-Post
packagemain
import(
       "fmt"
       "net/url"
       "net/http"
       "io/ioutil"
       "log"
       "bytes"
       "encoding/json"
)
typeServerstruct{
       ServerNamestring
       ServerIP  string
}
typeServerslicestruct{
       Servers[]Server
       ServersID string
}
funcmain(){
       varsServerslice
       varnewServerServer;
       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("jsonerr:",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)
}
三、Server
packagemain
import(
       "fmt"
       "net/http"
       "strings"
       "html"
       "io/ioutil"
       "encoding/json"
)
typeServerstruct{
       ServerNamestring
       ServerIP  string
}
typeServerslicestruct{
       Servers[]Server
       ServersID string
}
funcmain(){
       http.HandleFunc("/",handler)
       http.ListenAndServe(":9001",nil)
}
funchandler(whttp.ResponseWriter,r*http.Request){
       r.ParseForm()//解析参数,默认是不会解析的
       fmt.Fprintf(w,"Hi,Iloveyou%s",html.EscapeString(r.URL.Path[1:]))
       ifr.Method=="GET"{
               fmt.Println("method:",r.Method)//获取请求的方法
               fmt.Println("username",r.Form["username"])
               fmt.Println("password",r.Form["password"])
               fork,v:=ranger.Form{
                       fmt.Print("key:",k,";")
                       fmt.Println("val:",strings.Join(v,""))
               }
       }elseifr.Method=="POST"{
               result,_:=ioutil.ReadAll(r.Body)
               r.Body.Close()
               fmt.Printf("%s\n",result)
               //未知类型的推荐处理方法
               varfinterface{}
               json.Unmarshal(result,&f)
               m:=f.(map[string]interface{})
               fork,v:=rangem{
                       switchvv:=v.(type){
                               casestring:
                                       fmt.Println(k,"isstring",vv)
                               caseint:
                                       fmt.Println(k,"isint",vv)
                               casefloat64:
                                       fmt.Println(k,"isfloat64",vv)
                               case[]interface{}:
                                       fmt.Println(k,"isanarray:")
                                       fori,u:=rangevv{
                                               fmt.Println(i,u)
                                       }
                               default:
                                       fmt.Println(k,"isofatypeIdon'tknowhowtohandle")
                        }
                 }
                //结构已知,解析到结构体
                varsServerslice;
                json.Unmarshal([]byte(result),&s)
                fmt.Println(s.ServersID);
                fori:=0;i
希望本文所述对大家Go语言程序设计有所帮助。
 