golang简单tls协议用法完整示例
本文实例讲述了golang简单tls协议用法。分享给大家供大家参考,具体如下:
生成私钥:
openssl genrsa -out key.pem 2048
生成证书:
openssl req -new -x509 -key key.pem -out cert.pem -days 3650
https:
代码如下:
package main import ( "io" "net/http" "log" ) func HelloServer(w http.ResponseWriter, req *http.Request) { io.WriteString(w, "hello, world!\n") } func main() { http.HandleFunc("/hello", HelloServer) err := http.ListenAndServeTLS(":8080", "cert.pem", "key.pem", nil) if err != nil { log.Fatal("ListenAndServe: ", err) } }
提示: 访问请勿忘记使用https开头,否则chrome会下载一个文件如下:
dotcoo-air:tls dotcoo$ cat /Users/dotcoo/Downloads/hello | xxd
0000000: 1503 0100 0202 0a .......
TLS Server:
代码如下:
package main import ( "log" "crypto/tls" "net" "bufio" ) func main() { log.SetFlags(log.Lshortfile) cer, err := tls.LoadX509KeyPair("cert.pem", "key.pem") if err != nil { log.Println(err) return } config := &tls.Config{Certificates: []tls.Certificate{cer}} ln, err := tls.Listen("tcp", ":8000", config) if err != nil { log.Println(err) return } defer ln.Close() for { conn, err := ln.Accept() if err != nil { log.Println(err) continue } go handleConnection(conn) } } func handleConnection(conn net.Conn) { defer conn.Close() r := bufio.NewReader(conn) for { msg, err := r.ReadString('\n') if err != nil { log.Println(err) return } println(msg) n, err := conn.Write([]byte("world\n")) if err != nil { log.Println(n, err) return } } }
TLS Client:
代码如下:
package main import ( "log" "crypto/tls" ) func main() { log.SetFlags(log.Lshortfile) conf := &tls.Config{ InsecureSkipVerify: true, } conn, err := tls.Dial("tcp", "127.0.0.1:8000", conf) if err != nil { log.Println(err) return } defer conn.Close() n, err := conn.Write([]byte("hello\n")) if err != nil { log.Println(n, err) return } buf := make([]byte, 100) n, err = conn.Read(buf) if err != nil { log.Println(n, err) return } println(string(buf[:n])) }
希望本文所述对大家Go语言程序设计有所帮助。
相关推荐
安全小站 2020-08-05
微微一笑 2020-06-14
zhuyonge 2020-06-02
yznkaixin 2020-05-14
wzg0wzg 2020-04-30
agjirowjtg 2015-05-13
旷古的寂寞 2019-06-28
homehttp 2015-10-27
cocleon 2019-06-25
slyoy 2019-06-21
carolAnn 2016-12-15
ibinbinb 2013-05-16
onikyoo 2018-08-15
Bellboy 2018-11-29
woshilikuo 2018-03-26
一世为白 2020-06-27
yangliuhbhd 2020-04-29
zuoliangzhu 2020-03-06
夜雨倚琴 2020-02-14