package pay import ( "encoding/json" "fmt" "io" "net/http" "os" "strconv" "strings" "git.sr.ht/~sircmpwn/getopt" ) func usage() { fmt.Fprintf(os.Stderr, "usage: %s pay [-h host] user amount\n", os.Args[0]) os.Exit(1) } func Main(args []string) { host := "https://usualsuspect:freundschaft@kasse.z1.ccchb.de" getopt.Usage = usage opts, optind, err := getopt.Getopts(args, "h:") 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) } amount = -amount 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 can’t 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) } }