github.com/cnotch/ipchub@v1.1.0/config/tls.go (about)

     1  // Copyright (c) 2019,CAOHONGJU All rights reserved.
     2  // Use of this source code is governed by a MIT-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package config
     6  
     7  import (
     8  	"crypto/tls"
     9  	"errors"
    10  	"io/ioutil"
    11  	"os"
    12  	"strings"
    13  )
    14  
    15  // TLSConfig TLS listen 配置.
    16  type TLSConfig struct {
    17  	ListenAddr  string `json:"listen"`
    18  	Certificate string `json:"cert"`
    19  	PrivateKey  string `json:"key"`
    20  }
    21  
    22  // Load loads the certificates from the cache or the configuration.
    23  func (c *TLSConfig) Load() (*tls.Config, error) {
    24  	if c.PrivateKey == "" || c.Certificate == "" {
    25  		return &tls.Config{}, errors.New("No certificate or private key configured")
    26  	}
    27  
    28  	// If the certificate provided is in plain text, write to file so we can read it.
    29  	if strings.HasPrefix(c.Certificate, "---") {
    30  		if err := ioutil.WriteFile("broker.crt", []byte(c.Certificate), os.ModePerm); err == nil {
    31  			c.Certificate = Name + ".crt"
    32  		}
    33  	}
    34  
    35  	// If the private key provided is in plain text, write to file so we can read it.
    36  	if strings.HasPrefix(c.PrivateKey, "---") {
    37  		if err := ioutil.WriteFile("broker.key", []byte(c.PrivateKey), os.ModePerm); err == nil {
    38  			c.PrivateKey = Name + ".key"
    39  		}
    40  	}
    41  
    42  	// Make sure the paths are absolute, otherwise we won't be able to read the files.
    43  	c.Certificate = resolvePath(c.Certificate)
    44  	c.PrivateKey = resolvePath(c.PrivateKey)
    45  
    46  	// Load the certificate from the cert/key files.
    47  	cer, err := tls.LoadX509KeyPair(c.Certificate, c.PrivateKey)
    48  	return &tls.Config{
    49  		Certificates: []tls.Certificate{cer},
    50  	}, err
    51  }