Initial commit

This commit is contained in:
Ian Gulliver
2022-11-16 17:43:14 +00:00
parent 066e176448
commit 20f84a6fcd
3 changed files with 134 additions and 0 deletions

84
asana.go Normal file
View File

@@ -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))
}

3
go.mod Normal file
View File

@@ -0,0 +1,3 @@
module github.com/firestuff/http2asana
go 1.18

47
main.go Normal file
View File

@@ -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, "<body></body>", r.Form.Get("assignee"))
if err != nil {
log.Print(err)
return
}
}