Skip to content

Instantly share code, notes, and snippets.

@prologic
Created December 18, 2019 12:56
Show Gist options
  • Save prologic/0a4f694dcc78e92adbb7532f7e456b02 to your computer and use it in GitHub Desktop.
Save prologic/0a4f694dcc78e92adbb7532f7e456b02 to your computer and use it in GitHub Desktop.
A quick 'n dirty MIcroPub Go (Golang) client for Micro.blog (https://micro.blog)
package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
)
var (
endpoint string
token string
)
func init() {
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: %s [options] [file]\n", os.Args[0])
flag.PrintDefaults()
}
flag.StringVar(&token, "token", "", "authentication token")
flag.StringVar(&endpoint, "endpoint", "", "micropub endpoint to post to")
}
func main() {
flag.Parse()
if token == "" {
token = os.Getenv("TOKEN")
}
if endpoint == "" {
endpoint = os.Getenv("ENDPOINT")
}
if token == "" {
log.Fatalf("no token specified, use -token or $TOKEN env var")
}
if endpoint == "" {
log.Fatalf("no micropub endpoint specified, use -endpoint or $ENDPOINT")
}
log.Printf("Enter your post's content here (^D to finish):")
content, err := ioutil.ReadAll(os.Stdin)
if err != nil {
log.Fatalf("error reading content from stdin: %s", err)
}
data := url.Values{}
data.Set("h", "entry")
data.Set("content", string(content))
cli := &http.Client{Timeout: 3 * time.Second}
req, err := http.NewRequest("POST", endpoint, strings.NewReader(data.Encode()))
if err != nil {
log.Fatalf("error creating request: %s", err)
}
req.Header.Add("User-Agent", "https://github.com/prologic/micropub v0.0.0@HEAD")
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
res, err := cli.Do(req)
if err != nil {
log.Fatalf("error sending request: %s", err)
}
defer res.Body.Close()
if res.StatusCode/100 != 2 {
log.Fatalf("failed request: %s", res.Status)
}
}
@prologic
Copy link
Author

Example:

$ TOKEN=XXX ENDPOINT=https://micro.blog/micropub go run examples/post.go
2019/12/18 22:55:29 Enter your post's content here (^D to finish):
Hello from Go (Golang) client :D
^D

Post seen here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment