|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "net/http" |
| 8 | + |
| 9 | + "github.com/Bananenpro/cli" |
| 10 | + "github.com/code-game-project/go-utils/server" |
| 11 | + "github.com/mattn/go-colorable" |
| 12 | + "github.com/spf13/cobra" |
| 13 | +) |
| 14 | + |
| 15 | +// gameCreateCmd represents the game create command |
| 16 | +var gameCreateCmd = &cobra.Command{ |
| 17 | + Use: "create", |
| 18 | + Short: "Create a new game on the a server.", |
| 19 | + Args: cobra.MaximumNArgs(1), |
| 20 | + Run: func(cmd *cobra.Command, args []string) { |
| 21 | + var gameURL string |
| 22 | + var err error |
| 23 | + if len(args) > 0 { |
| 24 | + gameURL = args[0] |
| 25 | + } else if gameURL = findGameURL(); gameURL == "" { |
| 26 | + gameURL, err = cli.Input("Game URL:") |
| 27 | + abort(err) |
| 28 | + } |
| 29 | + api, err := server.NewAPI(gameURL) |
| 30 | + abort(err) |
| 31 | + |
| 32 | + type request struct { |
| 33 | + Public bool `json:"public"` |
| 34 | + Protected bool `json:"protected"` |
| 35 | + Config any `json:"config,omitempty"` |
| 36 | + } |
| 37 | + public, err := cmd.Flags().GetBool("public") |
| 38 | + abort(err) |
| 39 | + protected, err := cmd.Flags().GetBool("protected") |
| 40 | + abort(err) |
| 41 | + |
| 42 | + data, err := json.Marshal(request{ |
| 43 | + Public: public, |
| 44 | + Protected: protected, |
| 45 | + }) |
| 46 | + abort(err) |
| 47 | + |
| 48 | + body := bytes.NewBuffer(data) |
| 49 | + resp, err := http.Post(api.BaseURL()+"/games", "application/json", body) |
| 50 | + abort(err) |
| 51 | + defer resp.Body.Close() |
| 52 | + if resp.StatusCode != http.StatusCreated { |
| 53 | + abort(fmt.Errorf("invalid response code: expected: %d, got: %d", http.StatusCreated, resp.StatusCode)) |
| 54 | + } |
| 55 | + |
| 56 | + type response struct { |
| 57 | + GameId string `json:"game_id"` |
| 58 | + JoinSecret string `json:"join_secret"` |
| 59 | + } |
| 60 | + var r response |
| 61 | + err = json.NewDecoder(resp.Body).Decode(&r) |
| 62 | + |
| 63 | + out := colorable.NewColorableStdout() |
| 64 | + fmt.Fprintf(out, "%sGame ID:%s %s\n", cli.Cyan, cli.Reset, r.GameId) |
| 65 | + if r.JoinSecret != "" { |
| 66 | + fmt.Fprintf(out, "%sJoin secret:%s %s\n", cli.Cyan, cli.Reset, r.JoinSecret) |
| 67 | + } |
| 68 | + }, |
| 69 | +} |
| 70 | + |
| 71 | +func init() { |
| 72 | + gameCmd.AddCommand(gameCreateCmd) |
| 73 | + gameCreateCmd.Flags().Bool("public", false, "The game is displayed on a public game list.") |
| 74 | + gameCreateCmd.Flags().Bool("protected", false, "You can only join the game with the returned join secret.") |
| 75 | +} |
0 commit comments