美文网首页golang
golang&echo 开启HTTPS 服务

golang&echo 开启HTTPS 服务

作者: 撑伞的猫先生 | 来源:发表于2020-11-07 16:47 被阅读0次

一.使用openssl 生成SSL自签证书

第一步:生成私钥

使用openssl工具生成一个RSA私钥

openssl genrsa -des3 -out server.key 2048

说明:生成rsa私钥,des3算法,2048位强度,server.key是秘钥文件名。

第二步:生成CSR(证书签名请求)

openssl req -new -key server.key -out server.csr

说明:需要依次输入国家,地区,城市,组织,组织单位,Common Name和Email。其中Common Name,可以写自己的名字或者域名, 如果要支持https,Common Name应该与域名保持一致,否则会引起浏览器警告。

第三步:删除私钥中的密码

openssl rsa -in server.key -out server.key

Go提供的tls库中的LoadX509KeyPair并没有传入密码的选项,只能传入对应的证书和私钥,所以需要删除私钥中的密码.

第四步:生成自签名证书

openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

二. 使用echo开启https服务

1. 创建echodemo项目

新建go项目:

mkdir echodemo
cd echodemo
go mod init echodemo

创建 crt文件夹 ,将上面生成的server.crtserver.key文件复制到crt文件夹下,最终项目目录结构:

    echodemo
        ├─main.go
        ├─go.mod
        └─crt
            ├─server.crt
            └─server.key

2. 安装echo

go get github.com/labstack/echo/v4

3.开启HTTPS 服务

  • main.go 中代码:
package main

import (
    "github.com/labstack/echo"
    "github.com/labstack/echo/middleware"
    "net/http"
)

func main() {
    e := echo.New()
    //使用重定向中间件将http连接重定向到https
    e.Pre(middleware.HTTPSRedirect())
    e.Use(middleware.Recover())
    e.Use(middleware.Logger())
    e.GET("/", func(c echo.Context) error {
        return c.HTML(http.StatusOK, `
            <h1>Welcome to Echo!</h1>
            <h3>TLS certificates automatically installed from Let's Encrypt :)</h3>
        `)
    })
    
    go func() {
        e.Logger.Fatal(e.Start(":80"))
    }()
    e.Logger.Fatal(e.StartTLS(":443", "crt/server.crt", "crt/server.key"))
}

相关文章

  • golang&echo 开启HTTPS 服务

    一.使用openssl 生成SSL自签证书 第一步:生成私钥 使用openssl工具生成一个RSA私钥 说明:生成...

  • Apache上开启https服务

    Apache上开启https服务 使能ssl模块 创建私钥和证书请求(CSR) (-des3) 创建密钥口令, 不...

  • http-serve 开启https服务

    mac上 http-serve 开启一个https服务 Http-server是一个轻量级的基于nodejs的ht...

  • 阿里云服务器开启https

    前言 我的服务器环境是 CentOS 7.4 64位,安装的 lnmp 环境。由于个人需要,需要开启https。 ...

  • 第4回 django开启https服务

    生成https证书,网上很多收费的,下载的。其实可以用jdk自带的参考:https://www.cnblogs.c...

  • CentOS下httpd开启https

    注意:本例为本地测试服务器的https开启,非正式服务器证书的https。过程不同请勿混淆 1.基本要求 检查确认...

  • oracle ohs修改https端口

    oracle ohs默认是开启https服务,证书使用自签名证书,端口是4443不是https默认的443。关于如...

  • **mac**下开启**redis**服务

    mac下开启redis服务 1.下载 https://blog.csdn.net/resilient/articl...

  • nginx 开启https

    nginx 开启https 一、使用openssl 生成CA 创建用于认证的CA(这里叫做Root CA)首先要安...

  • Laravel开启HTTPS

    为什么要开启https这片老文章里面已经写了一些了,https有很多我用的是通配符的证书,阿里云上GeoTrust...

网友评论

    本文标题:golang&echo 开启HTTPS 服务

    本文链接:https://www.haomeiwen.com/subject/hkubvktx.html