博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Go实现发送解析GET与POST请求
阅读量:4682 次
发布时间:2019-06-09

本文共 3986 字,大约阅读时间需要 13 分钟。

参考链接:

https://www.jb51.net/article/115693.htm

https://www.jb51.net/article/60900.htm

https://www.cnblogs.com/5bug/p/8494953.html

 

1、服务器解析GET请求,返回值为文本格式

package mainimport (	"log"	"net/http")func checkToken(w http.ResponseWriter, r *http.Request) {	r.ParseForm()	if r.Form["token"][0] == "chending123" {		w.WriteHeader(http.StatusOK)		w.Write([]byte("验证成功!"))	} else {		w.WriteHeader(http.StatusNotFound)		w.Write([]byte("验证失败!"))	}}func main() {	http.HandleFunc("/user/check", checkToken)	er := http.ListenAndServe("localhost:9090", nil)	if er != nil {		log.Fatal("ListenAndServe: ", er)	}}

2、返回值为json格式

package mainimport (    "log"    "net/http"    "encoding/json" )func checkToken(w http.ResponseWriter, r *http.Request) {    r.ParseForm()        var result ResponseJson        if r.Form["token"][0] == "chending123" {        w.WriteHeader(http.StatusOK)        result.Data = "chending"        result.Message = "验证成功!"    } else {        w.WriteHeader(http.StatusNotFound)        result.Message = "验证失败!"    }        bytes, _ := json.Marshal(result)    w.Write(bytes)}func main() {    http.HandleFunc("/user/check", checkToken)    er := http.ListenAndServe("localhost:9090", nil)    if er != nil {        log.Fatal("ListenAndServe: ", er)    }}type ResponseJson struct {      Data    string     Message string  }

3、解析POST请求与解析GET请求方法一致,POST格式为x-www-form-urlencoded

     默认地,表单数据会编码为 "application/x-www-form-urlencoded"

4、GET请求样式

http://localhost:9090/user/check?token=chending123

http://localhost:9090/user/confirm?user=chending&pass=123456

5、POST请求样式

http://localhost:9090/user/confirm

以application/json格式发送数据

{

  “user”: "chending",

  "pass": "123456"

}

6、Go的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)}

 

7、Go的POST发送

package mainimport (        "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)}

 8、GET设置请求头

client := &http.Client{}    url := "http://localhost:9090/tokenconfirm"        reqest, err := http.NewRequest("GET", url, nil)    reqest.Header.Set("Content-Type", "application/json")    reqest.Header.Add("AccessToken", token)    if err != nil {        panic(err)    }       res, err := client.Do(reqest)          defer res.Body.Close()        jsonStr, err := ioutil.ReadAll(res.Body)       if err != nil {        log.Fatal(err)    }

 

转载于:https://www.cnblogs.com/lucifer1997/p/9448484.html

你可能感兴趣的文章
RFC端口号定义
查看>>
Unity Technologies-提供全面的技术支持服务
查看>>
Console-算法[for,if,break]-五个好朋友分苹果
查看>>
ylb: SQL表的高级查询-子查询
查看>>
import 用法
查看>>
6月7 考试系统
查看>>
mysql 基本操作
查看>>
HTML5 and Websocket
查看>>
zTree async 动态参数处理
查看>>
Oracle学习之常见错误整理
查看>>
Android实例-处理隐藏输入法后不再显示问题(XE8+小米2)
查看>>
字符串反转(10)
查看>>
HTC Sensation G14开盒
查看>>
Buffer cache spillover: only buffers
查看>>
lock_sga引起的ksvcreate :process(m000) creation failed
查看>>
面向抽象/接口编程以及继承
查看>>
POJ 1704 Georgia and Bob
查看>>
数据库插入数据乱码问题
查看>>
Jquery属性获取——attr()与prop()
查看>>
OVER(PARTITION BY)函数用法
查看>>