Dup Ver Goto 📝

Web Server Running Shell Script

To
58 lines, 175 words, 1369 chars Page 'BobbinsServer_01' does not exist.

My first attempt at writing anything in golang.

Obviously this is not for something visible to the world. This is just for quick and dirty stuff on a LAN. This takes the path of a request and sends it as the sole argument to a script called bobbins in the current directory where the program is run. Usefully one can edit this script without restarting the server. It returns the stdout and stderr.

package main

import (
  "fmt"
  "log"
  "net/http"
  "strings"
  "encoding/json"
  "os/exec"
  "bytes"
)

func myfunc(w http.ResponseWriter, r *http.Request) {
  a := strings.Trim(r.URL.Path,"/")
  log.Printf("bobbins called with path %s", a)
  w.Header().Set("Content-Type", "application/json; charset=utf-8")

  data := map[string]interface{} {}
  data["bobbins"] = a

  command := "./bobbins"
  args := []string{a}
  var stdout bytes.Buffer
  var stderr bytes.Buffer
  cmd := exec.Command(command, args...)
  cmd.Stdout = &stdout
  cmd.Stderr = &stderr
  err := cmd.Run()
  data["output"] = string(stdout.Bytes())
  data["stderr"] = string(stderr.Bytes())
  data["err"] = err

  j, _ := json.Marshal(data)
  w.Write(j)
}

func main() {
  router := http.NewServeMux()
  router.HandleFunc("/", myfunc)

  server := http.Server{
    Addr: ":8901",
    Handler: router,
  }

  fmt.Println("Server listening on port :8901")
  server.ListenAndServe()
}