golang实现get和post请求的服务端和客户端
服务端
在golang中,实现一个普通的http接口可以处理get请求和x-www-form-urlencoded类型的post请求,而如果想实现处理json数据的post请求,则需要用另外的方式实现,接收的参数要从request.Body中读取:
getpost.go
package main
import (
"net/http"
"encoding/json"
"log"
)
func main() {
http.HandleFunc("/login1", login1)
http.HandleFunc("/login2", login2)
http.ListenAndServe("0.0.0.0:8080", nil)
}
type Resp struct {
Code string `json:"code"`
Msg string `json:"msg"`
}
type Auth struct {
Username string `json:"username"`
Pwd string `json:"password"`
}
//post接口接收json数据
func login1(writer http.ResponseWriter, request *http.Request) {
var auth Auth
if err := json.NewDecoder(request.Body).Decode(&auth); err != nil {
request.Body.Close()
log.Fatal(err)
}
var result Resp
if auth.Username == "admin" && auth.Pwd == "123456" {
result.Code = "200"
result.Msg = "登录成功"
} else {
result.Code = "401"
result.Msg = "账户名或密码错误"
}
if err := json.NewEncoder(writer).Encode(result); err != nil {
log.Fatal(err)
}
}
//接收x-www-form-urlencoded类型的post请求或者普通get请求
func login2(writer http.ResponseWriter, request *http.Request) {
request.ParseForm()
username, uError := request.Form["username"]
pwd, pError := request.Form["password"]
var result Resp
if !uError || !pError {
result.Code = "401"
result.Msg = "登录失败"
} else if username[0] == "admin" && pwd[0] == "123456" {
result.Code = "200"
result.Msg = "登录成功"
} else {
result.Code = "203"
result.Msg = "账户名或密码错误"
}
if err := json.NewEncoder(writer).Encode(result); err != nil {
log.Fatal(err)
}
}
客户端
golang的标准api中用于http客户端请求的主要有三个api : http.Get,http.Post,http.PostForm,其区别如下:
| API | 特点 |
|---|---|
| http.Get | 发送get请求 |
| http.Post | post请求提交指定类型的数据 |
| http.PostForm | post请求提交application/x-www-form-urlencoded数据 |
在使用http客户端api的时候要注意一个问题:请求地址的url必须是带http://协议头的完整url,不然请求结果为空。
getpostclient.go
package main
import (
"net/http"
"fmt"
"io/ioutil"
"net/url"
"encoding/json"
"bytes"
)
type auth struct {
Username string `json:"username"`
Pwd string `json:"password"`
}
func main() {
get()
postWithJson()
postWithUrlencoded()
}
func get() {
//get请求
//http.Get的参数必须是带http://协议头的完整url,不然请求结果为空
resp, _ := http.Get("http://localhost:8080/login2?username=admin&password=123456")
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
//fmt.Println(string(body))
fmt.Printf("Get request result: %s\n", string(body))
}
func postWithJson() {
//post请求提交json数据
auths := auth{"admin","123456"}
ba, _ := json.Marshal(auths)
resp, _ := http.Post("http://localhost:8080/login1","application/json", bytes.NewBuffer([]byte(ba)))
body, _ := ioutil.ReadAll(resp.Body)
fmt.Printf("Post request with json result: %s\n", string(body))
}
func postWithUrlencoded() {
//post请求提交application/x-www-form-urlencoded数据
form := make(url.Values)
form.Set("username","admin")
form.Add("password","123456")
resp, _ := http.PostForm("http://localhost:8080/login2", form)
body, _ := ioutil.ReadAll(resp.Body)
fmt.Printf("Post request with application/x-www-form-urlencoded result: %s\n", string(body))
}
运行getpost.go后再运行getpostclient输出结果如下:
Get request result: {"code":"200","msg":"登录成功"}
Post request with json result: {"code":"200","msg":"登录成功"}
Post request with application/x-www-form-urlencoded result: {"code":"200","msg":"登录成功"}
Process finished with exit code 0
golang实现get和post请求的服务端和客户端的更多相关文章
- python服务器端、客户端的模型,客服端发送请求,服务端进行响应(web.py)
服务器端.客户端的模型,客服端发送的请求,服务端的响应 相当于启动了一个web server install web.py 接口框架用到的包 http://webpy.org/tutorial3.zh ...
- 前端发起resultUrl请求,服务端收到后做逆向处理,校验sign后,执行originUrl逻辑
originUrl=http://test.com:8080/user/alipay_phone?uid=123&amount=21.3第0步:前后端约定32位密钥KEY第一步:对参数按照ke ...
- 用http请求thrift服务端出现了内存溢出的情况
记一次内存溢出的分析经历 - Janti - 博客园 https://www.cnblogs.com/superfj/p/8474288.html 说在前面的话 朋友,你经历过部署好的服务突然内存溢出 ...
- (C#:Socket)简单的服务端与客户端通信。
要求:1.可以完成一对一的通信:2.实现服务端对客户端一对多的选择发送:3.可以实现服务端的群发功能:4.可以实现客户端文件的发送: 要点:服务器端:第一步:用指定的端口号和服务器的ip建立一个End ...
- 解决有关flask-socketio中服务端和客户端回调函数callback参数的问题(全网最全)
由于工作当中需要用的flask_socketio,所以自己学习了一下如何使用,查阅了有关文档,当看到回调函数callback的时候,发现文档里都描述的不太清楚,最后终于琢磨出来了,分享给有需要的朋友 ...
- DSAPI多功能组件编程应用-HTTP监听服务端与客户端_指令版
前面介绍了DSAPI多功能组件编程应用-HTTP监听服务端与客户端的内容,这里介绍一个适用于更高效更快速的基于HTTP监听的服务端.客户端. 在本篇,你将见到前所未有的超简化超傻瓜式的HTTP监听服务 ...
- java http post/get 服务端和客户端实现json传输
注:本文来源于<java http post/get 服务端和客户端实现json传输> 最近需要写http post接口所以学习下. 总的还是不难直接上源码! PostHttpClient ...
- DSAPI HTTP监听服务端与客户端
本文中,演示了使用DSAPI.网络相关.HTTP监听,快速建立服务端和客户端. HTTP监听服务端的作用,是监听指定计算机端口,以实现与IIS相同的解析服务,提供客户端的网页请求,当然,这不仅仅是应用 ...
- DSAPI HTTP监听服务端与客户端_指令版
前面介绍了DSAPI多功能组件编程应用-HTTP监听服务端与客户端的内容,这里介绍一个适用于更高效更快速的基于HTTP监听的服务端.客户端. 在本篇,你将见到前所未有的超简化超傻瓜式的HTTP监听服务 ...
随机推荐
- Python 学习笔记(6)— 字符串格式化
字符串格式化处理 远古写法 以前通常使用运算符号 % ,%s 插入的值 String 类型,%.3f 指插入的值为包含 3 位小数的浮点数: format1 = "%s, %s!" ...
- Java相关|Code Review Checklist(Server)
安全 所有入参均经过校验,包括验证参数数据类型.范围.长度,尽可能采用白名单形式验证所有的输入.对于非法请求,记录WARN log.参考Input Validation Cheat Sheet:前后端 ...
- Selenium Webdriver元素定位的八种常用方式【转】
在使用selenium webdriver进行元素定位时,通常使用findElement或findElements方法结合By类返回的元素句柄来定位元素.其中By类的常用定位方式共八种,现分别介绍如下 ...
- spring中的事件 applicationevent 讲的确实不错(转)
event,listener是observer模式一种体现,在spring 3.0.5中,已经可以使用annotation实现event和eventListner里. 我们以spring-webflo ...
- Spring框架完全掌握(下)
接着上一篇文章的内容Spring框架完全掌握(上),我们继续深入了解Spring框架. Spring_AOP 考虑到AOP在Spring中是非常重要的,很有必要拿出来单独说一说.所以本篇文章基本上讲述 ...
- HBase 系列(十一)—— Spring/Spring Boot + Mybatis + Phoenix 整合
一.前言 使用 Spring+Mybatis 操作 Phoenix 和操作其他的关系型数据库(如 Mysql,Oracle)在配置上是基本相同的,下面会分别给出 Spring/Spring Boot ...
- GPU服务器安装NVIDIA驱动以及CUDA
1.安装系统 系统版本: ubuntu16.04.05 LTS 分区要求: /boot 1024M swap 64G / 剩余空间
- 简易数据分析 11 | Web Scraper 抓取表格数据
这是简易数据分析系列的第 11 篇文章. 今天我们讲讲如何抓取网页表格里的数据.首先我们分析一下,网页里的经典表格是怎么构成的. First Name 所在的行比较特殊,是一个表格的表头,表示信息分类 ...
- iframe中使用模态框提交表单后,iframe加载父页面的解决方法
在iframe中使用模态框提交表单后,会出现iframe加载整个父页面的问题,如下图: 解决方法: 在form表单中添加target属性 _parent 这个属性会使目标文档载入父窗口或者包含来超链接 ...
- 并发、线程的基本概念&线程启动结束
并发.进程.可执行程序.进程.线程的基本概念 1.并发 并发当有多个线程在操作时,如果系统只有一个CPU,则它根本不可能真正同时进行一个以上的线程,它只能把CPU运行时间划分成若干个时间段,再将时间段 ...