用go语言模拟客户端对服务端发送get和post请求

client.go

package main


import (

// "bytes"

"fmt"

"io/ioutil"

"net/http"

"net/url"

)


var client = &http.Client{}


func Get() {

//向服务端发送get请求

request, _ := http.NewRequest("GET", "http://192.168.1.35:9091/?publicKey=-----BEGIN+PUBLIC+KEY-----%0D%0AMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDZsfv1qscqYdy4vY%2BP4e3cAtmv%0D%0AppXQcRvrF1cB4drkv0haU24Y7m5qYtT52Kr539RdbKKdLAM6s20lWy7%2B5C0Dgacd%0D%0AwYWd%2F7PeCELyEipZJL07Vro7Ate8Bfjya%2BwltGK9%2BXNUIHiumUKULW4KDx21%2B1NL%0D%0AAUeJ6PeW%2BDAkmJWF6QIDAQAB%0D%0A-----END+PUBLIC+KEY-----&privateKey=&info=sad&message=", nil)

response, _ := client.Do(request)


defer response.Body.Close()


if response.StatusCode == 200 {

str, _ := ioutil.ReadAll(response.Body)

bodystr := string(str)

fmt.Println(bodystr)

}

}


func Post() {

//post请求

postValues := url.Values{}

postValues.Add("publicKey", `-----BEGIN PUBLIC KEY-----

MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDZsfv1qscqYdy4vY+P4e3cAtmv

ppXQcRvrF1cB4drkv0haU24Y7m5qYtT52Kr539RdbKKdLAM6s20lWy7+5C0Dgacd

wYWd/7PeCELyEipZJL07Vro7Ate8Bfjya+wltGK9+XNUIHiumUKULW4KDx21+1NL

AUeJ6PeW+DAkmJWF6QIDAQAB

-----END PUBLIC KEY-----`)

postValues.Add("privateKey", `-----BEGIN RSA PRIVATE KEY-----

MIICXQIBAAKBgQDZsfv1qscqYdy4vY+P4e3cAtmvppXQcRvrF1cB4drkv0haU24Y

7m5qYtT52Kr539RdbKKdLAM6s20lWy7+5C0DgacdwYWd/7PeCELyEipZJL07Vro7

Ate8Bfjya+wltGK9+XNUIHiumUKULW4KDx21+1NLAUeJ6PeW+DAkmJWF6QIDAQAB

AoGBAJlNxenTQj6OfCl9FMR2jlMJjtMrtQT9InQEE7m3m7bLHeC+MCJOhmNVBjaM

ZpthDORdxIZ6oCuOf6Z2+Dl35lntGFh5J7S34UP2BWzF1IyyQfySCNexGNHKT1G1

XKQtHmtc2gWWthEg+S6ciIyw2IGrrP2Rke81vYHExPrexf0hAkEA9Izb0MiYsMCB

/jemLJB0Lb3Y/B8xjGjQFFBQT7bmwBVjvZWZVpnMnXi9sWGdgUpxsCuAIROXjZ40

IRZ2C9EouwJBAOPjPvV8Sgw4vaseOqlJvSq/C/pIFx6RVznDGlc8bRg7SgTPpjHG

4G+M3mVgpCX1a/EU1mB+fhiJ2LAZ/pTtY6sCQGaW9NwIWu3DRIVGCSMm0mYh/3X9

DAcwLSJoctiODQ1Fq9rreDE5QfpJnaJdJfsIJNtX1F+L3YceeBXtW0Ynz2MCQBI8

9KP274Is5FkWkUFNKnuKUK4WKOuEXEO+LpR+vIhs7k6WQ8nGDd4/mujoJBr5mkrw

DPwqA3N5TMNDQVGv8gMCQQCaKGJgWYgvo3/milFfImbp+m7/Y3vCptarldXrYQWO

AQjxwc71ZGBFDITYvdgJM1MTqc8xQek1FXn1vfpy2c6O

-----END RSA PRIVATE KEY-----`)

postValues.Add("info", "hello")

postValues.Add("message", "")


resp, err := client.PostForm("http://192.168.1.35:9091", postValues)


if err != nil {

fmt.Println(err.Error())

}

defer resp.Body.Close()

if resp.StatusCode == 200 {

body, _ := ioutil.ReadAll(resp.Body)

fmt.Println(string(body))

}

}


func main() {

Get()

Post()

}

index.go

package controllers


import (

"crypto/rand"

"crypto/rsa"

"crypto/x509"

"encoding/base64"

"encoding/pem"

"errors"

"fmt"

"net/http"

)


//处理数据的加密,解密或者单独的对数据进行或者解密


//用base64进行编码

func base64Encode(src []byte) []byte {

return []byte(base64.StdEncoding.EncodeToString(src))

}


//用base64进行解码

func base64Decode(src []byte) ([]byte, error) {

return base64.StdEncoding.DecodeString(string(src))

}


func toString(value []string) string {

length := len(value)

var sum string

for i := 0; i < length; i++ {

sum = sum + value[i]

}

return sum

}


var publicKey []byte

var privateKey []byte


//获得表单中的原文信息,明文是解密的结果

var cont []string


//得到原文字符串

var info string


//获得密文信息,密文是加密的结果

var meg []string


//得到密文字符串

var message string


func Get(w http.ResponseWriter, r *http.Request) {

//得到表单上的信息

Display(r)

//调用deal方法

Deal(info, message, publicKey, privateKey, w, r)

}


func Post(w http.ResponseWriter, r *http.Request) {

//得到客户端的数据

Display(r)

//调用deal方法

Deal(info, message, publicKey, privateKey, w, r)

}


//得到表单上的信息

func Display(r *http.Request) {

r.ParseForm() //解析参数,默认是不会解析的,如果没有写这句话的话,就无法得到请求的表单上面的数据


//得到私钥

var pri []string = r.Form["privateKey"]


//得到私钥字节类型的切片

privateKey = []byte(toString(pri))

// fmt.Fprintf(w, "私钥:\n"+string(privateKey)+"\n")


//得到公钥

var pub []string = r.Form["publicKey"]


//得到公钥字节类型的切片

publicKey = []byte(toString(pub))


//获得表单中的原文信息,明文是解密的结果

cont = r.Form["info"]


//得到原文字符串

info = toString(cont)


//获得密文信息,密文是加密的结果

meg = r.Form["message"]


//得到密文字符串

message = toString(meg)


}


//处理客户端的需求到底是什么

func Deal(info, message string, publicKey, privateKey []byte, w http.ResponseWriter, r *http.Request) {

//解密:密文, 私钥

//加密:明文, 共钥


//让我加解密

if info != "" && string(publicKey) != "" && string(privateKey) != "" && message == "" {

data, err := RsaEncrypt([]byte(info))

if err != nil {

panic(err)

}

// fmt.Fprintf(w, "公钥为:\n"+string(publicKey)+"\n")

debyte := base64Encode(data)

// fmt.Fprintf(w, "密文:\n"+string(debyte)+"\n")


origData, err := RsaDecrypt(data)

if err != nil {

panic(err)

}

// fmt.Fprintf(w, "私钥为:\n"+string(privateKey)+"\n")

fmt.Fprintf(w, "明文:\n%s", string(origData)+"\n")

fmt.Fprintf(w, "密文:\n"+string(debyte)+"\n")


//让我解密

} else if message != "" && string(privateKey) != "" && info == "" && string(publicKey) == "" {

//利用私钥解析密文得到明文

conte, err := base64Decode([]byte(message))

if err != nil {

panic(err)

}

conte, err = RsaDecrypt(conte)

if err != nil {

panic(err)

}

info = string(conte)


fmt.Fprintf(w, "明文:\n%s", info+"\n")

fmt.Fprintf(w, "密文:\n"+message+"\n")

} else if string(publicKey) != "" && info != "" && message == "" && string(privateKey) == "" { //让我加密


data, err := RsaEncrypt([]byte(info))

if err != nil {

panic(err)

}

message = string(base64Encode(data))


// fmt.Println("明文:", content)


fmt.Fprintf(w, "明文:\n%s", info+"\n")

fmt.Fprintf(w, "密文:\n"+message+"\n")

} else {

fmt.Fprintf(w, "请重新输入,不支持该种输入方式")

return

}

}


// 加密

func RsaEncrypt(origData []byte) ([]byte, error) {

block, _ := pem.Decode(publicKey)

if block == nil {

return nil, errors.New("public key error")

}

pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)

if err != nil {

return nil, err

}

pub := pubInterface.(*rsa.PublicKey)

return rsa.EncryptPKCS1v15(rand.Reader, pub, origData)

}


// 解密

func RsaDecrypt(ciphertext []byte) ([]byte, error) {

block, _ := pem.Decode(privateKey)

if block == nil {

return nil, errors.New("private key error!")

}

priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)

if err != nil {

return nil, err

}

return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)

}

httpweb.go

package main


import (

// "fmt"

"log"

"net/http"

"testRSA2/controllers"

)


//设置服务端处理请求


//判断请求方式是get还是post请求

func indexHandle(w http.ResponseWriter, r *http.Request) {

m := r.Method

if m == "GET" {

controllers.Get(w, r)

} else {

controllers.Post(w, r)

}

}


func main() {

http.HandleFunc("/", indexHandle) //设置访问的路由


err := http.ListenAndServe(":9091", nil) //设置监听的端口

if err != nil {

log.Fatal("listenAndServe:", err)

}

}


本文来自:开源中国博客

感谢作者:秦思_li

查看原文:用go语言模拟客户端对服务端发送get和post请求

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。