Automation

Publish an Article To DEV.to With GO

Photo by Nate Grant on Unsplash

Requirements

Getting Started

mkdir devAutomation && cd devAutomation

touch .env
touch main.go

go mod init devAutomation

echo "# Hello Dev.To
Lorem ipsum dolor sit amet, consectetur adipiscing elit." >> example.md
DEV_TO_API_KEY='your-api-key'
func main() {
file, err := ioutil.ReadFile("./example.md")
if err != nil {
fmt.Println(err)
}

fmt.Println(string(file))
}
# Hello Dev.To
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
type DevTo struct {
Article Article `json:"article"`
}

type Article struct {
Title string `json:"title"`
Published bool `json:"published"`
Series string `json:"series"`
MainImage string `json:"main_image"`
Canonical string `json:"canonical_url"`
Description string `json:"description"`
Tags []string `json:"tags"`
BodyMarkdown string `json:"body_markdown"`
}
func request(body string) {
url := "https://dev.to/api/articles"
content := strings.Split(body, "\n")
responseBody := DevTo{
Article: Article{
Published: false, // this will ensure it's a draft
Title: content[0],
BodyMarkdown: content[1],
},
}

payload, _ := json.Marshal(responseBody)
request, err := http.NewRequest("POST", url, bytes.NewBuffer(payload))

request.Header.Add("api-key", apikey)
request.Header.Add("Content-Type", "application/json")

client := &http.Client{}
response, err := client.Do(request)

if err != nil {
log.Fatalln(err)
}
defer response.Body.Close()

if response.StatusCode == 200 || response.StatusCode == 201 {
log.Println("Created new article on Dev.To")
}

if response.StatusCode != 200 && response.StatusCode != 201 {
responseMessage, _ := ioutil.ReadAll(response.Body)
log.Fatalln(string(responseMessage))
}
}
go get github.com/joho/godotenv
func env(key string) string {
err := godotenv.Load("./.env")
if err != nil {
log.Fatalf("Error loading .env file")
}

log.Println("Loaded the .env file")

return os.Getenv(key)
}
// ... other code
func request(body string) {
apikey := env("DEV_TO_API_KEY") // <-- this line
url := "https://dev.to/api/articles"
content := strings.Split(body, "\n")

// ...rest of the function
}
func main() {
file, err := ioutil.ReadFile("./example.md")
if err != nil {
fmt.Println(err)
}

request(string(file)) // <-- this line
}
18:51:36 Loaded the .env file
18:51:37 Created new article on Dev.To

Wrapping it up.

--

--

Software Engineer based in Rotterdam — Photographer, Art Enthusiast, Dreamer, and thinker.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Koen Verburg

Software Engineer based in Rotterdam — Photographer, Art Enthusiast, Dreamer, and thinker.