Skip to content

Instantly share code, notes, and snippets.

@eldondev
Last active August 29, 2015 14:28
Show Gist options
  • Save eldondev/83c8591fc4929ae51bb0 to your computer and use it in GitHub Desktop.
Save eldondev/83c8591fc4929ae51bb0 to your computer and use it in GitHub Desktop.
Write nginx configs from combined cert/pem files
package main
import (
"crypto/md5"
"crypto/x509"
"encoding/pem"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
)
func main() {
for _, certificate := range os.Args[1:] {
const nginx_template = `
server {
listen 443;
server_name %s;
root /usr/share/nginx/www;
index index.html index.htm;
ssl on;
ssl_certificate %s;
ssl_certificate_key %s;
location / {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_pass http://localhost:8000;
}
}
`
txt, err := ioutil.ReadFile(certificate)
if err != nil {
log.Fatal(err)
}
key_data, rest := pem.Decode(txt)
cert_data, rest := pem.Decode(rest)
cert, err := x509.ParseCertificate(cert_data.Bytes)
domain := cert.DNSNames[0]
basename := fmt.Sprintf("%x", md5.Sum([]byte(domain)))
if err != nil {
log.Fatal(err)
}
if err != nil {
log.Fatal(err)
}
config_name := basename + ".conf"
cert_name := basename + ".crt"
key_name := basename + ".key"
ioutil.WriteFile(cert_name, pem.EncodeToMemory(cert_data), 0600)
ioutil.WriteFile(key_name, pem.EncodeToMemory(key_data), 0600)
cert_name, err = filepath.Abs(cert_name)
key_name, err = filepath.Abs(key_name)
ioutil.WriteFile(config_name, []byte(fmt.Sprintf(nginx_template, domain, cert_name, key_name)), 0600)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment