duanbi7247 2017-12-17 17:17
浏览 106
已采纳

将证书和密钥作为字符串传递给ListenAndServeTLS

I am creating an app using Go and I am trying to start a https server using the ListenAndServeTLS function. Here is my code:

func StartServer() {
    defer config.CapturePanic()
    c := config.GetInstance()

    serverAddress := fmt.Sprintf(":%s", c.GetConfig().ServerPort)
    server := http.Server{Addr: serverAddress}

    log.Info("Starting local server")
    http.HandleFunc("/", login.Handler)
    http.HandleFunc("/login", login.Handler)
    http.HandleFunc("/settings", settings.Handler)

    //cert, _ := data.Asset("my-cert.pem")
    //key, _ := data.Asset("my-key.pem")
    err := server.ListenAndServeTLS("my-cert.crt", "my-cert.key")
    if err != nil {
        log.WithError(err).Fatal("Error stopping local server")
    }
}

The thing is that I would like to embed my certificate and its key inside my executable file and then pass them to the the server.ListeAndServeTLS function as a string or a byte array. However this function does not take these types of arguments. Is there another way to do this?

Note: I am aware that it is a bad practice to embed a private key inside a client application, however what I am trying to do here is just to create a config webpage that will be hosted as https://localhost:8080.

  • 写回答

1条回答 默认 最新

  • douba4275 2017-12-17 17:41
    关注

    You can build your own server object and still call ListenAndServeTLS. Since your tls config has certificates, it will ignore the passed-in filenames. I'm omitting the return on error for conciseness, please do not:

    // Generate a key pair from your pem-encoded cert and key ([]byte).
    cert, err := tls.X509KeyPair(<cert contents>, <key contents>)
    
    // Construct a tls.config
    tlsConfig := &tls.Config{
      Certificates: []tls.Certificate{cert}
      // Other options
    }
    
    // Build a server:
    server := http.Server{
        // Other options
        TLSConfig: tlsConfig,
    }
    
    // Finally: serve.
    err = server.ListenAndServeTLS("", "")
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥15 QT6颜色选择对话框显示不完整
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥15 DS18B20内部ADC模数转换器