compiler.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package compiler
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "net/http"
  8. "time"
  9. )
  10. type Compiler struct {
  11. Url string
  12. }
  13. type Program struct {
  14. Main string `json:"body"`
  15. }
  16. type Event struct {
  17. Message string
  18. Kind string // "stdout" or "stderr"
  19. Delay time.Duration // time to wait before printing Message
  20. }
  21. type Result struct {
  22. Errors string
  23. Events []Event
  24. }
  25. func New(url string) *Compiler {
  26. return &Compiler{url}
  27. }
  28. func (c *Compiler) Run(program *Program) (*Result, error) {
  29. jsonRequest, err := json.Marshal(program)
  30. if err != nil {
  31. return nil, err
  32. }
  33. req, err := http.NewRequest("POST", c.Url, bytes.NewBuffer(jsonRequest))
  34. if err != nil {
  35. return nil, err
  36. }
  37. req.Header.Set("Content-Type", "application/json")
  38. client := &http.Client{}
  39. resp, err := client.Do(req)
  40. if err != nil {
  41. return nil, err
  42. }
  43. defer resp.Body.Close()
  44. body, _ := ioutil.ReadAll(resp.Body)
  45. result := &Result{}
  46. err = json.Unmarshal(body, result)
  47. if err != nil {
  48. return nil, fmt.Errorf("Error during JSON unmarshaling. The raw response body was %s. The error is %s", body, err)
  49. }
  50. return result, nil
  51. }