buildlet: add WorkDir method on Client

Also fix the RemoveAll method by setting the request Content-Type.

Change-Id: I87ec29c5c0da06eba5eaebcd00bdbef18e6ae8ad
Reviewed-on: https://go-review.googlesource.com/3880
Reviewed-by: Andrew Gerrand <adg@golang.org>
diff --git a/buildlet/buildletclient.go b/buildlet/buildletclient.go
index 9d0e4d8..6f75506 100644
--- a/buildlet/buildletclient.go
+++ b/buildlet/buildletclient.go
@@ -232,6 +232,7 @@
 	if err != nil {
 		return err
 	}
+	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
 	return c.doOK(req)
 }
 
@@ -279,6 +280,27 @@
 	return retErr
 }
 
+// WorkDir returns the absolute path to the buildlet work directory.
+func (c *Client) WorkDir() (string, error) {
+	req, err := http.NewRequest("GET", c.URL()+"/workdir", nil)
+	if err != nil {
+		return "", err
+	}
+	resp, err := c.do(req)
+	if err != nil {
+		return "", err
+	}
+	if resp.StatusCode != http.StatusOK {
+		return "", errors.New(resp.Status)
+	}
+	b, err := ioutil.ReadAll(resp.Body)
+	resp.Body.Close()
+	if err != nil {
+		return "", err
+	}
+	return string(b), nil
+}
+
 func condRun(fn func()) {
 	if fn != nil {
 		fn()
diff --git a/cmd/buildlet/buildlet.go b/cmd/buildlet/buildlet.go
index ea4341e..53778ef 100644
--- a/cmd/buildlet/buildlet.go
+++ b/cmd/buildlet/buildlet.go
@@ -105,6 +105,7 @@
 	http.Handle("/halt", requireAuth(handleHalt))
 	http.Handle("/tgz", requireAuth(handleGetTGZ))
 	http.Handle("/removeall", requireAuth(handleRemoveAll))
+	http.Handle("/workdir", requireAuth(handleWorkDir))
 
 	tlsCert, tlsKey := metadataValue("tls-cert"), metadataValue("tls-key")
 	if (tlsCert == "") != (tlsKey == "") {
@@ -581,7 +582,10 @@
 		http.Error(w, "requires POST method", http.StatusBadRequest)
 		return
 	}
-	r.ParseForm()
+	if err := r.ParseForm(); err != nil {
+		http.Error(w, err.Error(), http.StatusBadRequest)
+		return
+	}
 	paths := r.Form["path"]
 	if len(paths) == 0 {
 		http.Error(w, "requires 'path' parameter", http.StatusBadRequest)
@@ -602,6 +606,14 @@
 	}
 }
 
+func handleWorkDir(w http.ResponseWriter, r *http.Request) {
+	if r.Method != "GET" {
+		http.Error(w, "requires GET method", http.StatusBadRequest)
+		return
+	}
+	fmt.Fprint(w, *workDir)
+}
+
 func validRelPath(p string) bool {
 	if p == "" || strings.Contains(p, `\`) || strings.HasPrefix(p, "/") || strings.Contains(p, "../") {
 		return false