Created
August 8, 2018 15:29
-
-
Save dillonhafer/e7ef76c1c716a7ae209be157057f8aaa to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"crypto" | |
"crypto/ecdsa" | |
"crypto/rsa" | |
"crypto/tls" | |
"crypto/x509" | |
"encoding/pem" | |
"fmt" | |
"io/ioutil" | |
"log" | |
"net/http" | |
"time" | |
"actions" | |
"github.com/gobuffalo/buffalo/servers" | |
) | |
func parsePrivateKey(der []byte) (crypto.PrivateKey, error) { | |
if key, err := x509.ParsePKCS1PrivateKey(der); err == nil { | |
return key, nil | |
} | |
if key, err := x509.ParsePKCS8PrivateKey(der); err == nil { | |
switch key := key.(type) { | |
case *rsa.PrivateKey, *ecdsa.PrivateKey: | |
return key, nil | |
default: | |
return nil, fmt.Errorf("Found unknown private key type in PKCS#8 wrapping") | |
} | |
} | |
if key, err := x509.ParseECPrivateKey(der); err == nil { | |
return key, nil | |
} | |
return nil, fmt.Errorf("Failed to parse private key") | |
} | |
func loadCertficateAndKeyFromFile(path string) (*tls.Certificate, error) { | |
raw, err := ioutil.ReadFile(path) | |
if err != nil { | |
return nil, err | |
} | |
var cert tls.Certificate | |
for { | |
block, rest := pem.Decode(raw) | |
if block == nil { | |
break | |
} | |
if block.Type == "CERTIFICATE" { | |
cert.Certificate = append(cert.Certificate, block.Bytes) | |
} else { | |
cert.PrivateKey, err = parsePrivateKey(block.Bytes) | |
if err != nil { | |
return nil, fmt.Errorf("Failure reading private key from \"%s\": %s", path, err) | |
} | |
} | |
raw = rest | |
} | |
if len(cert.Certificate) == 0 { | |
return nil, fmt.Errorf("No certificate found in \"%s\"", path) | |
} else if cert.PrivateKey == nil { | |
return nil, fmt.Errorf("No private key found in \"%s\"", path) | |
} | |
return &cert, nil | |
} | |
func main() { | |
pemFile := "../frontend/node_modules/webpack-dev-server/ssl/server.pem" | |
cert, err := loadCertficateAndKeyFromFile(pemFile) | |
if err != nil { | |
log.Fatalf("server: loadkeys: %s", err) | |
} | |
config := &tls.Config{Certificates: []tls.Certificate{*cert}} | |
srv := &http.Server{ | |
ReadTimeout: 5 * time.Second, | |
WriteTimeout: 10 * time.Second, | |
IdleTimeout: 120 * time.Second, | |
TLSConfig: config, | |
} | |
app := actions.App() | |
if err := app.Serve(servers.WrapTLS(srv, "", "")); err != nil { | |
log.Fatal(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment