欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Go语言Web编程实现Get和Post请求发送与解析的方法详解

程序员文章站 2022-03-20 16:34:46
本文实例讲述了go语言web编程实现get和post请求发送与解析的方法。分享给大家供大家参考,具体如下: 这是一篇入门文章,通过一个简单的例子介绍golang的web编...

本文实例讲述了go语言web编程实现get和post请求发送与解析的方法。分享给大家供大家参考,具体如下:

这是一篇入门文章,通过一个简单的例子介绍golang的web编程主要用到的技术。

文章结构包括:

1. client-get 请求
2. client-post 请求
3. server 处理 get 和 post 数据

在数据的封装中,我们部分采用了json,因而本文也涉及到golang中json的编码和解码。

一、client-get

复制代码 代码如下:
package main
import (
        "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)
}

二、client-post

复制代码 代码如下:
package main
import (
        "fmt"
        "net/url"
        "net/http"
        "io/ioutil"
        "log"
        "bytes"
        "encoding/json"
)
type server struct {
        servername string
        serverip   string
}
type serverslice struct {
        servers []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.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)
        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)
                return
        }
        fmt.printf("%s", result)
}

三、server

复制代码 代码如下:
package main
import (
        "fmt"
        "net/http"
        "strings"
        "html"
        "io/ioutil"
        "encoding/json"
)
type server struct {
        servername string
        serverip   string
}
type serverslice struct {
        servers []server
        serversid  string
}
func main() {
        http.handlefunc("/", handler)
        http.listenandserve(":9001", nil)
}
func handler(w http.responsewriter, r *http.request) {
        r.parseform() //解析参数,默认是不会解析的
        fmt.fprintf(w, "hi, i love you %s", html.escapestring(r.url.path[1:]))
        if r.method == "get" {
                fmt.println("method:", r.method) //获取请求的方法
                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" {
                result, _:= ioutil.readall(r.body)
                r.body.close()
                fmt.printf("%s\n", result)
                //未知类型的推荐处理方法
                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{}:
                                        fmt.println(k, "is an array:")
                                        for i, u := range vv {
                                                fmt.println(i, u)
                                        }
                                default:
                                        fmt.println(k, "is of a type i don't know how to handle")
                         }
                  }
                 //结构已知,解析到结构体
                 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)
                 }
        }
}

希望本文所述对大家go语言程序设计有所帮助。