From aa5e5d5ff12b14e8956c441b41662e7436091e21 Mon Sep 17 00:00:00 2001 From: serr Date: Mon, 11 Nov 2024 20:20:53 +0300 Subject: [PATCH] start --- go.mod | 3 +++ main.go | 76 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 go.mod create mode 100644 main.go diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..e9de56c --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module mastodongolangtest + +go 1.23.2 diff --git a/main.go b/main.go new file mode 100644 index 0000000..64825ba --- /dev/null +++ b/main.go @@ -0,0 +1,76 @@ +package main + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net/http" +) + +func main() { + // Your access token + accessToken := "YOUR TOKEN" + + // URL for verifying the account + verifyURL := "https://mastodon.ml/api/v1/accounts/verify_credentials" + // URL for creating a new status + postURL := "https://mastodon.ml/api/v1/statuses" + + // Headers with access token + client := &http.Client{} + req, err := http.NewRequest("GET", verifyURL, nil) + if err != nil { + fmt.Println("Error creating request:", err) + return + } + req.Header.Set("Authorization", "Bearer "+accessToken) + + // Verify the account + resp, err := client.Do(req) + if err != nil { + fmt.Println("Error executing request:", err) + return + } + defer resp.Body.Close() + + if resp.StatusCode == 200 { + body, _ := io.ReadAll(resp.Body) + fmt.Println("Successful login:", string(body)) + + // The text message you want to post + statusText := "test post using golang and mastodon api" + + // Data for the POST request + data := map[string]string{"status": statusText} + jsonData, _ := json.Marshal(data) + + // Sending POST request to create a new status + postReq, err := http.NewRequest("POST", postURL, bytes.NewBuffer(jsonData)) + if err != nil { + fmt.Println("Error creating request:", err) + return + } + postReq.Header.Set("Authorization", "Bearer "+accessToken) + postReq.Header.Set("Content-Type", "application/json") + + postResp, err := client.Do(postReq) + if err != nil { + fmt.Println("Error executing request:", err) + return + } + defer postResp.Body.Close() + + if postResp.StatusCode == 200 { + postBody, _ := io.ReadAll(postResp.Body) + fmt.Println("Post successfully created:", string(postBody)) + } else { + postBody, _ := io.ReadAll(postResp.Body) + fmt.Println("Error creating post:", postResp.StatusCode, string(postBody)) + } + + } else { + body, _ := io.ReadAll(resp.Body) + fmt.Println("Error verifying account:", resp.StatusCode, string(body)) + } +}