加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Golang HTTPS

发布时间:2020-12-16 19:13:52 所属栏目:大数据 来源:网络整理
导读:用 golang 来实现的 webserver 通常是是这样的 //main.gopackage mainimport ("fmt""io""net/http")func defaultHandler(w http.ResponseWriter,r *http.Request) {io.WriteString(w,"h1Golang HTTP/h1")}func main() {mux := http.NewServeMux()mux.HandleF

golang来实现的webserver通常是是这样的

//main.go
package main

import (
	"fmt"
	"io"
	"net/http"
)

func defaultHandler(w http.ResponseWriter,r *http.Request) {
	io.WriteString(w,"<h1>Golang HTTP</h1>")
}

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/",defaultHandler)
	err := http.ListenAndServe(":80",mux)
	if err != nil {
		fmt.Println(err.Error())
	}
}

服务运行后,我们通常通过http://localhost的形式来访问,
而我们要实现的是通过https://localhost的形式来访问.

那么如何用golang来实现HTTPS呢?

//main.go
package main

import (
	"fmt"
	"io"
	"net/http"
)

func defaultHandler(w http.ResponseWriter,"<h1>Golang HTTPS</h1>")
}

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/",defaultHandler)
	certFile := "/etc/letsencrypt/live/www.taadis.com/cert.pem"
	keyFile := "/etc/letsencrypt/live/www.taadis.com/privkey.pem"
	err := http.ListenAndServeTLS(":443",certFile,keyFile,mux)
	if err != nil {
		fmt.Println(err.Error())
	}
}

源码比较简单,
主要是把http.ListenAndServe()替换成ListenAndServeTLS(),
其次注意下端口号的区别,
还有就是CA证书的问题,这里我采用了Let's Encrypt

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读