服务端

在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请求的服务端和客户端的更多相关文章

  1. python服务器端、客户端的模型,客服端发送请求,服务端进行响应(web.py)

    服务器端.客户端的模型,客服端发送的请求,服务端的响应 相当于启动了一个web server install web.py 接口框架用到的包 http://webpy.org/tutorial3.zh ...

  2. 前端发起resultUrl请求,服务端收到后做逆向处理,校验sign后,执行originUrl逻辑

    originUrl=http://test.com:8080/user/alipay_phone?uid=123&amount=21.3第0步:前后端约定32位密钥KEY第一步:对参数按照ke ...

  3. 用http请求thrift服务端出现了内存溢出的情况

    记一次内存溢出的分析经历 - Janti - 博客园 https://www.cnblogs.com/superfj/p/8474288.html 说在前面的话 朋友,你经历过部署好的服务突然内存溢出 ...

  4. (C#:Socket)简单的服务端与客户端通信。

    要求:1.可以完成一对一的通信:2.实现服务端对客户端一对多的选择发送:3.可以实现服务端的群发功能:4.可以实现客户端文件的发送: 要点:服务器端:第一步:用指定的端口号和服务器的ip建立一个End ...

  5. 解决有关flask-socketio中服务端和客户端回调函数callback参数的问题(全网最全)

    由于工作当中需要用的flask_socketio,所以自己学习了一下如何使用,查阅了有关文档,当看到回调函数callback的时候,发现文档里都描述的不太清楚,最后终于琢磨出来了,分享给有需要的朋友 ...

  6. DSAPI多功能组件编程应用-HTTP监听服务端与客户端_指令版

    前面介绍了DSAPI多功能组件编程应用-HTTP监听服务端与客户端的内容,这里介绍一个适用于更高效更快速的基于HTTP监听的服务端.客户端. 在本篇,你将见到前所未有的超简化超傻瓜式的HTTP监听服务 ...

  7. java http post/get 服务端和客户端实现json传输

    注:本文来源于<java http post/get 服务端和客户端实现json传输> 最近需要写http post接口所以学习下. 总的还是不难直接上源码! PostHttpClient ...

  8. DSAPI HTTP监听服务端与客户端

    本文中,演示了使用DSAPI.网络相关.HTTP监听,快速建立服务端和客户端. HTTP监听服务端的作用,是监听指定计算机端口,以实现与IIS相同的解析服务,提供客户端的网页请求,当然,这不仅仅是应用 ...

  9. DSAPI HTTP监听服务端与客户端_指令版

    前面介绍了DSAPI多功能组件编程应用-HTTP监听服务端与客户端的内容,这里介绍一个适用于更高效更快速的基于HTTP监听的服务端.客户端. 在本篇,你将见到前所未有的超简化超傻瓜式的HTTP监听服务 ...

随机推荐

  1. eclipse项目导入idea jdk版本不一致😵

    在导入eclipse项目到idea过程中遇到 Imported project refers to unkonwn jdks JavaSE-1.8 解决方法: file --> Project ...

  2. 洛谷 P4344 [SHOI2015]脑洞治疗仪

    题意简述 维护序列,支持以下操作: 0 l r:将l~r赋为0 1 l1 r1 l2 r2:将l1~r1中的1替换l2~r2中的0,多余舍弃 2 l r:询问l~r中最大连续1的长度 题解思路 珂朵莉 ...

  3. 获取n月后的当前时间

    例如用户计算会员的到期日期时间 public static Date getMonthNextOrBeforeDate(int monthNum) { Date dNow = new Date(); ...

  4. 三角函数与JavaScript

     1. 三角函数 sin&(求对边与斜边的比值) cos&(邻边与斜边的比值) tan&(对边与邻边的比值) 2.JavaScript的函数的使用 Math.sin() Mat ...

  5. print,cat打印格式及字符串引号格式,去掉字符串空格 in R

    print 函数的打印格式: ##no quote print out > x <- letters[1:5] > print(x,quote=F,);print(x,quote=T ...

  6. GLFW+GLAD OpenGL Mac开发环境搭建

    前言 OpenGL 是什么?The Industry Standard for High Performance Graphics 这是官方解释.说白了他就是一套标准接口.对,是接口,并没有实现具体的 ...

  7. spring security中@PreAuthorize注解的使用

    添加依赖<!-- oauth --><dependency> <groupId>org.springframework.cloud</groupId> ...

  8. Linux Capabilities 简介

    为了执行权限检查,Linux 区分两类进程:特权进程(其有效用户标识为 0,也就是超级用户 root)和非特权进程(其有效用户标识为非零). 特权进程绕过所有内核权限检查,而非特权进程则根据进程凭证( ...

  9. 单页面应用的History路由模式express后端中间件配合

    这篇文章主要分享一下通过HTML5的history API的时候,使用NodeJS后端应该如何配置,来避免产生404的问题,这里是使用的express的框架,主要是通过connect-history- ...

  10. 防盗链测试01 - Jwplayer+Tengine2.3.1 mp4模块打造流媒体测试服务器

    最近有个想法,想做类似下面的视频URL验证: 1.URL Tag Validation 2.Special format of URL for preventing unauthorized usag ...