cert.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "os"
  8. "path/filepath"
  9. "imuslab.com/arozos/ReverseProxy/mod/utils"
  10. )
  11. func handleListCertificate(w http.ResponseWriter, r *http.Request) {
  12. filenames, err := tlsCertManager.ListCertDomains()
  13. if err != nil {
  14. http.Error(w, err.Error(), http.StatusInternalServerError)
  15. return
  16. }
  17. response, err := json.Marshal(filenames)
  18. if err != nil {
  19. http.Error(w, err.Error(), http.StatusInternalServerError)
  20. return
  21. }
  22. w.Header().Set("Content-Type", "application/json")
  23. w.Write(response)
  24. }
  25. //Handle upload of the certificate
  26. func handleCertUpload(w http.ResponseWriter, r *http.Request) {
  27. // check if request method is POST
  28. if r.Method != "POST" {
  29. http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
  30. return
  31. }
  32. // get the key type
  33. keytype, err := utils.GetPara(r, "ktype")
  34. overWriteFilename := ""
  35. if err != nil {
  36. http.Error(w, "Not defined key type (pub / pri)", http.StatusBadRequest)
  37. return
  38. }
  39. // get the domain
  40. domain, err := utils.GetPara(r, "domain")
  41. if err != nil {
  42. //Assume localhost
  43. domain = "localhost"
  44. }
  45. if keytype == "pub" {
  46. overWriteFilename = domain + ".crt"
  47. } else if keytype == "pri" {
  48. overWriteFilename = domain + ".key"
  49. } else {
  50. http.Error(w, "Not supported keytype: "+keytype, http.StatusBadRequest)
  51. return
  52. }
  53. // parse multipart form data
  54. err = r.ParseMultipartForm(10 << 20) // 10 MB
  55. if err != nil {
  56. http.Error(w, "Failed to parse form data", http.StatusBadRequest)
  57. return
  58. }
  59. // get file from form data
  60. file, _, err := r.FormFile("file")
  61. if err != nil {
  62. http.Error(w, "Failed to get file", http.StatusBadRequest)
  63. return
  64. }
  65. defer file.Close()
  66. // create file in upload directory
  67. os.MkdirAll("./certs", 0775)
  68. f, err := os.Create(filepath.Join("./certs", overWriteFilename))
  69. if err != nil {
  70. http.Error(w, "Failed to create file", http.StatusInternalServerError)
  71. return
  72. }
  73. defer f.Close()
  74. // copy file contents to destination file
  75. _, err = io.Copy(f, file)
  76. if err != nil {
  77. http.Error(w, "Failed to save file", http.StatusInternalServerError)
  78. return
  79. }
  80. // send response
  81. fmt.Fprintln(w, "File upload successful!")
  82. }