The example in this article describes the Golang simple TLS protocol usage. Share to everyone for your reference, specific as follows:
Generate private key:
OpenSSL genrsa-out Key.pem 2048
To generate a certificate:
OpenSSL req-new-x509-key key.pem-out cert.pem-days 3650
Https
Copy Code code as follows:
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)
}
}
Tip: Visit do not forget to use HTTPS to start, or Chrome will download a file as follows:
Dotcoo-air:tls dotcoo$ Cat/users/dotcoo/downloads/hello | Xxd
0000000:1503 0100 0202 0a .....
TLS Server:
Copy Code code as follows:
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:
Copy Code code as follows:
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]))
}
I hope this article will help you with your go language program.