z1/pay/pay.go

70 lines
1.4 KiB
Go
Raw Normal View History

2022-09-06 14:25:11 -05:00
package pay
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strconv"
"strings"
"git.sr.ht/~sircmpwn/getopt"
)
func usage() {
2022-09-06 14:50:42 -05:00
fmt.Fprintf(os.Stderr, "usage: %s pay [-h host] user amount\n", os.Args[0])
2022-09-06 14:25:11 -05:00
os.Exit(1)
}
func Main(args []string) {
host := "https://usualsuspect:freundschaft@kasse.z1.ccchb.de"
getopt.Usage = usage
2022-09-06 14:50:42 -05:00
opts, optind, err := getopt.Getopts(args, "h:")
2022-09-06 14:25:11 -05:00
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
for _, opt := range opts {
switch opt.Option {
case 'h':
host = opt.Value
}
}
if len(args) != optind+2 {
usage()
}
args = args[optind:]
user := args[0]
amount, err := strconv.Atoi(args[1])
if err != nil {
fmt.Fprintf(os.Stderr, "%s: amount: %v\n", os.Args[0], err)
os.Exit(1)
}
2022-09-06 14:50:42 -05:00
amount = -amount
2022-09-06 14:25:11 -05:00
req := struct {
Amount int `json:"amount"`
}{amount}
json, err := json.Marshal(req)
if err != nil {
fmt.Fprintf(os.Stderr, "%s: generating JSON: %v\n", os.Args[0], err)
os.Exit(1)
}
// BUG: user is not URI encoded
// BUG: user cant be the name
resp, err := http.Post(host+"/api/user/"+user+"/transaction", "application/json", strings.NewReader(string(json)))
if err != nil {
fmt.Fprintf(os.Stderr, "%s: HTTP: %v\n", os.Args[0], err)
os.Exit(1)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
fmt.Fprintf(os.Stderr, "%s: unexpected status code: %d\n", os.Args[0], resp.StatusCode)
io.Copy(os.Stderr, resp.Body)
}
}