package memos import ( "fmt" "strings" "github.com/imroc/req/v3" "github.com/pkg/errors" ) type Resource struct { Content []byte `json:"content,omitempty"` // req Filename string `json:"filename,omitempty"` // req Type string `json:"type,omitempty"` // req resp Name string `json:"name,omitempty"` // resp Uid string `json:"uid,omitempty"` // resp } type Memo struct { Content string `json:"content,omitempty"` // req Visibility string `json:"visibility,omitempty"` // req Name string `json:"name,omitempty"` // resp Uid string `json:"uid,omitempty"` // resp } // Host string // Token string type PostData struct { Content string ChannelID int64 ChannelTitle string Resources []Resource } var client *req.Client func InitClient(host, token string) { client = req.C().EnableInsecureSkipVerify().SetBaseURL(host).SetCommonBearerAuthToken(token) } func Post(pd PostData) error { var createMemoResp Memo content := fmt.Sprintf("#%s #%d \n\n%s", pd.ChannelTitle, pd.ChannelID, pd.Content) content = strings.ReplaceAll(content, "http://", " http://") content = strings.ReplaceAll(content, "https://", " https://") resp, err := client.R(). SetSuccessResult(&createMemoResp). SetBodyJsonMarshal(Memo{ Content: content, Visibility: "PUBLIC", }). Post("api/v1/memos") if err != nil { return errors.Wrap(err, "post memo failed") } if !resp.IsSuccessState() { return errors.New("post memo failed, body: " + resp.String()) } if len(pd.Resources) == 0 { return nil } type Resources struct { Resources []Resource `json:"resources"` } resp, err = client.R(). SetBodyJsonMarshal(Resources{Resources: pd.Resources}). Patch(fmt.Sprintf("/api/v1/%s/resources", createMemoResp.Name)) if err != nil { return errors.Wrap(err, "patch resources failed") } if !resp.IsSuccessState() { return errors.New("post memo failed, body: " + resp.String()) } return nil } func Upload(res Resource) (Resource, error) { var result Resource resp, err := client.R().SetSuccessResult(&result).SetBodyJsonMarshal(res).Post("/api/v1/resources") if err != nil { return Resource{}, errors.Wrap(err, "post resource failed") } if !resp.IsSuccessState() { return Resource{}, errors.New("post memo failed, body: " + resp.String()) } return result, nil }