学无先后,达者为师

网站首页 编程语言 正文

Golang实现http重定向https_Golang

作者:taadis   更新时间: 2022-09-06 编程语言

用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, r *http.Request) {
	io.WriteString(w, "<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。

原文链接:https://www.cnblogs.com/taadis/p/12126228.html

栏目分类
最近更新