Move examples to examples directory

This commit is contained in:
Elara 2023-01-08 00:47:32 -08:00
parent d7ad5f9f94
commit 31aa7361ec
3 changed files with 101 additions and 24 deletions

View File

@ -4,31 +4,10 @@
Go bindings to the [Lemmy](https://join-lemmy.org) API, automatically generated directly from Lemmy's source code using the generator in [cmd/gen](cmd/gen).
Example:
Examples:
```go
ctx := context.Background()
c, err := lemmy.New("https://lemmygrad.ml")
if err != nil {
panic(err)
}
err = c.ClientLogin(ctx, types.Login{
UsernameOrEmail: "user@example.com",
Password: `TestPwd`,
})
if err != nil {
panic(err)
}
_, err = c.SaveUserSettings(ctx, types.SaveUserSettings{
BotAccount: types.NewOptional(true),
})
if err != nil {
panic(err)
}
```
- HTTP: [examples/http](examples/http)
- WebSocket: [examples/websocket](examples/websocket)
### How to generate

32
examples/http/main.go Normal file
View File

@ -0,0 +1,32 @@
package main
import (
"context"
"go.arsenm.dev/go-lemmy"
"go.arsenm.dev/go-lemmy/types"
)
func main() {
ctx := context.Background()
c, err := lemmy.New("https://lemmygrad.ml")
if err != nil {
panic(err)
}
err = c.ClientLogin(ctx, types.Login{
UsernameOrEmail: "user@example.com",
Password: `TestPwd`,
})
if err != nil {
panic(err)
}
_, err = c.SaveUserSettings(ctx, types.SaveUserSettings{
BotAccount: types.NewOptional(true),
})
if err != nil {
panic(err)
}
}

View File

@ -0,0 +1,66 @@
package main
import (
"context"
"log"
"go.arsenm.dev/go-lemmy"
"go.arsenm.dev/go-lemmy/types"
)
func main() {
ctx := context.Background()
c, err := lemmy.NewWebSocket("https://lemmygrad.ml")
if err != nil {
panic(err)
}
err = c.ClientLogin(ctx, types.Login{
UsernameOrEmail: "user@example.com",
Password: `TestPwd`,
})
if err != nil {
panic(err)
}
// If nil is passed as data, go-lemmy will just send
// the auth token, which is all that's needed for
// the UserJoin operation.
c.Request(types.UserOperationUserJoin, nil)
// Subscribe to all communities
c.Request(types.UserOperationCommunityJoin, types.CommunityJoin{
CommunityID: 0,
})
go handleErrors(c)
handleResponses(c)
}
func handleResponses(c *lemmy.WSClient) {
for res := range c.Responses() {
if res.IsOneOf(types.UserOperationCRUDCreateComment) {
var data types.CommentResponse
err := lemmy.DecodeResponse(res.Data, &data)
if err != nil {
log.Println("Error decoding response:", err)
continue
}
err = c.Request(types.UserOperationCreateCommentLike, types.CreateCommentLike{
CommentID: data.CommentView.Comment.ID,
})
if err != nil {
log.Println("Error decoding response:", err)
continue
}
}
}
}
func handleErrors(c *lemmy.WSClient) {
for err := range c.Errors() {
log.Println("Error decoding response:", err)
}
}