• 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

  • 相关阅读:
    iOS中循环引用的解除
    Block的循环引用详解
    Mac OS X下面 Node.js环境的搭建
    swift中闭包和OC的block的对比
    STL priority_queue
    优先使用map(或者unordered_map)的find函数而非algorithm里的find函数
    Insert Interval
    Integer Break
    Unique Binary Search Trees
    腾讯2016实习生笔试
  • 原文地址:https://www.cnblogs.com/taadis/p/12126228.html
Copyright © 2020-2023  润新知