• Golang HTTPS


    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

  • 相关阅读:
    img 的data-src 属性及懒加载
    try catch 用法
    input 的各种属性的验证 checkValidity兼容性
    表单提交的方法。
    通信原理
    计算机组成原理
    CREC 2017
    POJ 1201 Intervals
    HDU 3440 House Man
    poj 3169 Layout
  • 原文地址:https://www.cnblogs.com/taadis/p/12126228.html
Copyright © 2020-2023  润新知