Go implementation of pdsadmin cli
1package cmd
2
3import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "io"
8 "net/http"
9 "os"
10
11 "github.com/spf13/cobra"
12 "github.com/spf13/viper"
13)
14
15type ServerCreateInviteCode_Input struct {
16 UseCount int `json:"useCount"`
17}
18
19type ServerCreateInviteCode_Output struct {
20 Code string `json:"code"`
21}
22
23var number *int
24
25// createInviteCodeCmd represents the createInviteCode command
26var createInviteCodeCmd = &cobra.Command{
27 Use: "create-invite-code",
28 Short: "Create a new invite code",
29 Example: "pdsadmin create-invite-code",
30 Args: cobra.NoArgs,
31 Run: func(cmd *cobra.Command, args []string) {
32 if *number < 1 {
33 fmt.Println("number must be >=1")
34 os.Exit(1)
35 }
36 body := ServerCreateInviteCode_Input{
37 UseCount: *number,
38 }
39 jsonBody, err := json.Marshal(body)
40 if err != nil {
41 fmt.Printf("could not create json body: %s\n", err)
42 os.Exit(1)
43 }
44 bodyReader := bytes.NewReader(jsonBody)
45
46 req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("https://%s/xrpc/com.atproto.server.createInviteCode", viper.GetString("hostname")), bodyReader)
47 if err != nil {
48 fmt.Printf("could not create request: %s\n", err)
49 os.Exit(1)
50 }
51 req.Header.Add("Content-Type", "application/json")
52 req.SetBasicAuth("admin", viper.GetString("admin_password"))
53
54 client := &http.Client{}
55 res, err := client.Do(req)
56 if err != nil {
57 fmt.Printf("error making http request: %s\n", err)
58 os.Exit(1)
59 }
60 resBody, err := io.ReadAll(res.Body)
61 if err != nil {
62 fmt.Printf("could not read response body: %s\n", err)
63 os.Exit(1)
64 }
65
66 var inviteCode ServerCreateInviteCode_Output
67 if err := json.Unmarshal(resBody, &inviteCode); err != nil {
68 fmt.Printf("could not get invite code: %s\n", err)
69 os.Exit(1)
70 }
71 fmt.Println(inviteCode.Code)
72 },
73}
74
75func init() {
76 rootCmd.AddCommand(createInviteCodeCmd)
77 number = createInviteCodeCmd.Flags().IntP("number", "n", 1, "number of times the code can be used")
78}