golang 实现https请求

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Programmer_FuQiang/article/details/85228698

首先我们先来创建一个http请求

//http.go

package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w,
     "这个是http请求")
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

执行这段代码:
$ go run http.go

打开浏览器,在地址栏输入"http://localhost:8080", 你会在此网页看到 “这个是http请求

接下来就实现一个https请求   

首先需要https请求当然离不开证书吧,我们先自己创建个证书

用openssl生成server.crt和server.key文件,供程序使用

$openssl genrsa -out server.key 2048  (第一个命令)

执行上面命令会得到如下

$openssl req -new -x509 -key server.key -out server.crt -days 365  (第二个命令)

执行上面命令会得到如下

主要我画红线的!!!一定要写上你的url 其他的随便写。。。。。。

此时你会得到两个证书  如下所示

接下来写代码了

//https.go

package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w,
        "这是一个https请求")
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServeTLS(":8081", "E:/GoWorkSpace/server.crt",
                           "E:/GoWorkSpace/server.key", nil)
}

路径哈 一定要填写好!!!!!!!!

执行程序:go run https.go
通过浏览器访问:https://localhost:8081,chrome浏览器会显示如下画面:

因为自己创建的证书会不被信任他就会提示证书风险,所以上线项目去买一个就行一年的不贵,去阿里云 或者  腾讯云,,,,,,,

猜你喜欢

转载自blog.csdn.net/Programmer_FuQiang/article/details/85228698