cert.go 1.7 KB

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