diff --git a/asana.go b/asana.go new file mode 100644 index 0000000..0c743eb --- /dev/null +++ b/asana.go @@ -0,0 +1,84 @@ +package main + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net/http" + "os" +) + +type AsanaClient struct { + cli *http.Client + token string + workspace string + assignee string +} + +type addTaskRequest struct { + Data *addTaskRequestInt `json:"data"` +} + +type addTaskRequestInt struct { + Name string `json:"name"` + HtmlNotes string `json:"html_notes"` + Workspace string `json:"workspace"` + Assignee string `json:"assignee"` + Followers []string `json:"followers"` +} + +func NewAsanaClient() *AsanaClient { + return &AsanaClient{ + cli: &http.Client{}, + token: os.Getenv("ASANA_TOKEN"), + workspace: os.Getenv("ASANA_WORKSPACE"), + assignee: os.Getenv("ASANA_ASSIGNEE"), + } +} + +func (ac *AsanaClient) CreateTask(name, notes, assignee string) error { + body := &addTaskRequest{ + Data: &addTaskRequestInt{ + Name: name, + HtmlNotes: notes, + Workspace: ac.workspace, + Assignee: ac.assignee, + }, + } + + if assignee != "" { + body.Data.Assignee = assignee + } + + body.Data.Followers = []string{body.Data.Assignee} + + js, err := json.Marshal(body) + if err != nil { + return err + } + + req, err := http.NewRequest("POST", "https://app.asana.com/api/1.0/tasks", bytes.NewReader(js)) + if err != nil { + return err + } + + ac.addAuth(req) + req.Header.Add("Content-Type", "application/json") + + resp, err := ac.cli.Do(req) + if err != nil { + return err + } + + if resp.StatusCode != 201 { + msg, _ := io.ReadAll(resp.Body) + return fmt.Errorf("%s: %s", resp.Status, msg) + } + + return nil +} + +func (ac *AsanaClient) addAuth(req *http.Request) { + req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", ac.token)) +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..de39684 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module github.com/firestuff/http2asana + +go 1.18 diff --git a/main.go b/main.go new file mode 100644 index 0000000..5f52447 --- /dev/null +++ b/main.go @@ -0,0 +1,47 @@ +package main + +import ( + "flag" + "log" + "net/http" +) + +func main() { + bindFlag := flag.String("bind", ":8200", "host:port to listen on") + flag.Parse() + + ac := NewAsanaClient() + + http.HandleFunc( + "/", + func(w http.ResponseWriter, r *http.Request) { + handleRequest(ac, w, r) + }, + ) + + srv := http.Server{ + Addr: *bindFlag, + } + + err := srv.ListenAndServe() + if err != nil { + log.Fatal(err) + } +} + +func handleRequest(ac *AsanaClient, w http.ResponseWriter, r *http.Request) { + err := r.ParseForm() + if err != nil { + log.Print(err) + return + } + + name := r.Form.Get("name") + log.Print(name) + + err = ac.CreateTask(name, "", r.Form.Get("assignee")) + if err != nil { + log.Print(err) + return + } +}