add https server

This commit is contained in:
AJ ONeal 2015-07-13 19:30:27 -06:00
parent 07155fee6d
commit 7c17629841
2 changed files with 53 additions and 1 deletions

View File

@ -25,7 +25,9 @@ Run the server
```bash
# Run the Code
go run serve.go --port 8443 --letsencrypt-dir=./etc/letsencrypt/live/
go run serve.go \
--port 8443 \
--letsencrypt-path=./etc/letsencrypt/live/
```
View it in your browser

View File

@ -1,9 +1,14 @@
package main
import (
"crypto/tls"
"flag"
"fmt"
"net"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
)
@ -15,6 +20,23 @@ func usage() {
os.Exit(2)
}
type myHandler struct{}
func (m *myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Print debug info
fmt.Println(r.Host)
fmt.Println(r.Method)
fmt.Println(r.RequestURI)
fmt.Println(r.URL) // has many keys, such as Query
for k, v := range r.Header {
fmt.Println(k, v)
}
fmt.Println(r.Body)
// End the request
fmt.Fprintf(w, "Hi there, %s %q? Wow!\n\nWith Love,\n\t%s", r.Method, r.URL.Path[1:], r.Host)
}
func main() {
flag.Usage = usage
@ -34,5 +56,33 @@ func main() {
*/
fmt.Printf("Loading Certificates %s/%s/{privkey.pem,fullchain.pem}\n", *certsPath, *defaultHost)
privkeyPath := filepath.Join(*certsPath, *defaultHost, "privkey.pem")
certPath := filepath.Join(*certsPath, *defaultHost, "fullchain.pem")
cert, err := tls.LoadX509KeyPair(certPath, privkeyPath)
if err != nil {
fmt.Fprintf(os.Stderr, "Couldn't load default certificates: %s\n", err)
os.Exit(1)
}
addr := ":" + strconv.Itoa(int(*port))
conn, err := net.Listen("tcp", addr)
if nil != err {
fmt.Fprintf(os.Stderr, "Couldn't bind to TCP socket %q: %s\n", addr, err)
os.Exit(1)
}
tlsConfig := new(tls.Config)
tlsConfig.Certificates = []tls.Certificate{cert}
tlsConfig.GetCertificate = func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
return &cert, nil
}
tlsListener := tls.NewListener(conn, tlsConfig)
server := &http.Server{
Addr: addr,
Handler: &myHandler{},
}
fmt.Printf("Listening on https://%s:%d\n", host, *port)
server.Serve(tlsListener)
}