Guest User

Untitled

a guest
Apr 15th, 2024
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 2.41 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "encoding/json"
  5.     "fmt"
  6.     "net/http"
  7.     "os"
  8.     "os/exec"
  9.     "path/filepath"
  10.  
  11.     "github.com/go-chi/chi/v5"
  12.     "github.com/go-chi/chi/v5/middleware"
  13.     "github.com/go-chi/cors"
  14. )
  15.  
  16. type CompileRequest struct {
  17.     Code string `json:"code"`
  18. }
  19.  
  20. type CompileResult struct {
  21.     Result string `json:"result"`
  22. }
  23.  
  24. func main() {
  25.     r := chi.NewRouter()
  26.     r.Use(middleware.Logger)
  27.     r.Use(cors.Handler(cors.Options{
  28.         // AllowedOrigins:   []string{"https://foo.com"}, // Use this to allow specific origin hosts
  29.         AllowedOrigins: []string{"https://*", "http://*"},
  30.         // AllowOriginFunc:  func(r *http.Request, origin string) bool { return true },
  31.         AllowedMethods:   []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
  32.         AllowedHeaders:   []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
  33.         ExposedHeaders:   []string{"Link"},
  34.         AllowCredentials: false,
  35.         MaxAge:           300, // Maximum value not ignored by any of major browsers
  36.     }))
  37.  
  38.     r.Get("/", func(w http.ResponseWriter, r *http.Request) {
  39.         w.Write([]byte("Hello World!"))
  40.     })
  41.  
  42.     r.Post("/compile", compileHandler)
  43.  
  44.     http.ListenAndServe(":3000", r)
  45. }
  46.  
  47. func compileHandler(w http.ResponseWriter, r *http.Request) {
  48.     var req CompileRequest
  49.     defer r.Body.Close() // Close the request body at the end of the handler
  50.     if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  51.         http.Error(w, "Failed to parse JSON request body", http.StatusBadRequest)
  52.         return
  53.     }
  54.  
  55.     // Write code to a temporary file
  56.     tempFile, err := os.CreateTemp("", "source*.go")
  57.     if err != nil {
  58.         http.Error(w, "Failed to create temporary file", http.StatusInternalServerError)
  59.         return
  60.     }
  61.     defer os.Remove(tempFile.Name())
  62.     defer tempFile.Close()
  63.  
  64.     if _, err := tempFile.WriteString(req.Code); err != nil {
  65.         http.Error(w, "Failed to write code to temporary file", http.StatusInternalServerError)
  66.         return
  67.     }
  68.  
  69.     output, err := compileCode(tempFile.Name())
  70.     if err != nil {
  71.         http.Error(w, fmt.Sprintf("Compilation failed: %s", err), http.StatusInternalServerError)
  72.         return
  73.     }
  74.  
  75.     // Return compilation output as JSON response
  76.     res := CompileResult{Result: output}
  77.     json.NewEncoder(w).Encode(res)
  78. }
  79.  
  80. func compileCode(filePath string) (string, error) {
  81.     dir := filepath.Dir(filePath)
  82.  
  83.     cmd := exec.Command("go", "run", filePath)
  84.     cmd.Dir = dir
  85.     out, err := cmd.CombinedOutput()
  86.     if err != nil {
  87.         return "", err
  88.     }
  89.  
  90.     return string(out), nil
Advertisement
Add Comment
Please, Sign In to add comment