服务端

在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

最新文章

  1. Python 日志模块 logging通过配置文件方式使用
  2. XObject.java 对象还没写完,希望电脑不会丢失。坏笑,早点见。
  3. [转]backbone.js template()函数
  4. iOS - CAEmitterLayer 学习笔记一
  5. 算法:comparable比较器的排序原理实现(二叉树中序排序)
  6. PL/SQL 记录集合IS TABLE OF的使用
  7. bat处理文件
  8. sqlite3使用事务处理[zz]
  9. 记录Django学习1
  10. 【SRM-05 B】无题?
  11. Android开发中常见的设计模式(四)——策略模式
  12. windbg获取打印
  13. Base64图片编码原理,base64图片工具介绍,图片在线转换Base64
  14. Java线程安全容器
  15. 压缩文件破解rarcrack-支持格式zip,rar和7z
  16. 【刷题】BZOJ 1823 [JSOI2010]满汉全席
  17. Sublime Es6教程2-基本语法
  18. Python3 数字保留后几位
  19. iOS 基础类解析 - NSDate
  20. (第二场)A Run 【动态规划】

热门文章

  1. RuntimeError: one of the variables needed for gradient computation has been modified by an inplace
  2. 自定义genericUDF demo
  3. Mina各组件介绍
  4. native-echarts 问题总结
  5. wordcloud库基本介绍和使用方法
  6. 线上ZK问题排查
  7. 简析 Golang net/http 包
  8. textRNN & textCNN的网络结构与代码实现!
  9. 编程题及解题思路(1,String)
  10. Spring数据库连接