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("", "")
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 这个公式写进SIMULINK中的function模块的代码中应该是什么样的
  • ¥15 javaweb登陆的网页为什么不能正确连接查询数据库
  • ¥15 数学建模数学建模需要
  • ¥15 已知许多点位,想通过高斯分布来随机选择固定数量的点位怎么改
  • ¥20 nao机器人语音识别问题
  • ¥15 怎么生成确定数目的泊松点过程
  • ¥15 layui数据表格多次重载的数据覆盖问题
  • ¥15 python点云生成mesh精度不够怎么办
  • ¥15 QT C++ 鼠标键盘通信
  • ¥15 改进Yolov8时添加的注意力模块在task.py里检测不到