aboutsummaryrefslogtreecommitdiff
path: root/src/pkg/http
diff options
context:
space:
mode:
authorAdam Langley <agl@golang.org>2010-07-02 13:00:18 -0400
committerAdam Langley <agl@golang.org>2010-07-02 13:00:18 -0400
commitfc23def67f4c24fe295c4e389e584d244eee1530 (patch)
treeeda6752193f2a64b6b67c3ac43a655ccfce6b237 /src/pkg/http
parent44eaaaaa78ae0e716018b203bebd9821c52ba05d (diff)
downloadgo-fc23def67f4c24fe295c4e389e584d244eee1530.tar.xz
crypto/tls, http: Make HTTPS servers easier.
R=r, adg, rsc CC=golang-dev https://golang.org/cl/1684051
Diffstat (limited to 'src/pkg/http')
-rw-r--r--src/pkg/http/server.go52
1 files changed, 52 insertions, 0 deletions
diff --git a/src/pkg/http/server.go b/src/pkg/http/server.go
index 81ce98229a..75896af302 100644
--- a/src/pkg/http/server.go
+++ b/src/pkg/http/server.go
@@ -13,6 +13,8 @@ package http
import (
"bufio"
+ "crypto/rand"
+ "crypto/tls"
"fmt"
"io"
"log"
@@ -21,6 +23,7 @@ import (
"path"
"strconv"
"strings"
+ "time"
)
// Errors introduced by the HTTP server.
@@ -638,3 +641,52 @@ func ListenAndServe(addr string, handler Handler) os.Error {
l.Close()
return e
}
+
+// ListenAndServeTLS acts identically to ListenAndServe, expect that it
+// except HTTPS connections. Additionally, files containing a certificate and
+// matching private key for the server must be provided.
+//
+// A trivial example server is:
+//
+// import (
+// "http"
+// "log"
+// )
+//
+// func handler(conn *http.Conn, req *http.Request) {
+// conn.SetHeader("Content-Type", "text/plain")
+// conn.Write([]byte("This is an example server.\n"))
+// }
+//
+// func main() {
+// http.HandleFunc("/", handler)
+// log.Stdoutf("About to listen on 10443. Go to https://127.0.0.1:10443/")
+// err := http.ListenAndServe(":10443", "cert.pem", "key.pem", nil)
+// if err != nil {
+// log.Exit(err)
+// }
+// }
+//
+// One can use generate_cert.go in crypto/tls to generate cert.pem and key.pem.
+func ListenAndServeTLS(addr string, certFile string, keyFile string, handler Handler) os.Error {
+ config := &tls.Config{
+ Rand: rand.Reader,
+ Time: time.Seconds,
+ NextProtos: []string{"http/1.1"},
+ }
+
+ var err os.Error
+ config.Certificates = make([]tls.Certificate, 1)
+ config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
+ if err != nil {
+ return err
+ }
+
+ conn, err := net.Listen("tcp", addr)
+ if err != nil {
+ return err
+ }
+
+ tlsListener := tls.NewListener(conn, config)
+ return Serve(tlsListener, handler)
+}