Created
December 18, 2019 12:56
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example:
Post seen here