controller.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package httpserver
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "github.com/gin-gonic/gin"
  7. )
  8. type Controller struct {
  9. Config *HttpServerConfig
  10. }
  11. /*
  12. Returns a new Controller struct to register routes to the gin router
  13. :param cfg: A pointer to an HttpServerConfig struct
  14. */
  15. func NewController(cfg *HttpServerConfig) *Controller {
  16. return &Controller{Config: cfg}
  17. }
  18. /*
  19. This handler will be responsible for proxying out the GET requests that the server recieves
  20. */
  21. func (c *Controller) Get(ctx *gin.Context) {
  22. url := fmt.Sprintf("https://%s%s", c.Config.RevProxySite, ctx.Param("ProxiedPath"))
  23. req, err := http.NewRequest("GET", url, nil)
  24. if err != nil {
  25. ctx.JSON(500, map[string]string{
  26. "Error": "Error creating the request.",
  27. "Msg:": err.Error(),
  28. })
  29. return
  30. }
  31. req.URL.Path = ctx.Param("ProxiedPath")
  32. req.Header.Add("user-agent", c.Config.UserAgent)
  33. req.Header.Add("Referer", c.Config.AllowedDomain)
  34. // fmt.Printf("%+v\n", req)
  35. client := &http.Client{}
  36. resp, err := client.Do(req)
  37. if err != nil {
  38. ctx.JSON(500, map[string]string{
  39. "Error": "Error creating the request.",
  40. "Msg:": err.Error(),
  41. })
  42. return
  43. }
  44. defer resp.Body.Close()
  45. b, err := io.ReadAll(resp.Body)
  46. if err != nil {
  47. ctx.JSON(500, map[string]string{
  48. "Error": "Error creating the request.",
  49. "Msg:": err.Error(),
  50. })
  51. return
  52. }
  53. ctx.Data(200, "text/html", b)
  54. }
  55. /*
  56. This handler will be responsible for proxying any POST requests
  57. */
  58. func (c *Controller) Post(ctx *gin.Context) {
  59. url := fmt.Sprintf("%s/%s", c.Config.RevProxySite, ctx.FullPath())
  60. req, err := http.NewRequest("POST", url, ctx.Request.Body)
  61. if err != nil {
  62. ctx.JSON(500, map[string]string{
  63. "Error": "Error creating the request.",
  64. "Msg:": err.Error(),
  65. })
  66. return
  67. }
  68. req.Header.Add("user-agent", c.Config.UserAgent)
  69. req.Header.Add("Referer", c.Config.AllowedDomain)
  70. fmt.Printf("%+v\n", req)
  71. }