Introducing devtogo: A wrapper for the dev.to api written in Go
Shiraaz Moollatjie
Posted on October 28, 2019
This post will introduce you to devtogo and will show you some usage examples.
I've been using Go as my main programming language for about six months at work. It's been very enjoyable and I always learn something new every day.
I wrote devtogo as a means for me to learn how to write some good opensource Go code. It's also my very first opensource project that I am publishing. Much of my work is sitting in private repositories, so I thought that I may as well expose this for the world to use.
Try it out and contribute/interact with the Github repo.
Devtogo is an rest api wrapper for the dev.to api. It can be used to publish articles or even search for articles of a specific tag. There are many usecases for using the dev.to api.
It's possible to retrieve either a list of articles or a single article. For this post, we are going to retrieve all the articles that are tagged with go
If we are an authenticated user, we can retrieve our own list of published or unpublished articles. This is useful for obtaining a list of our drafts that we want to publish later.
To create an article, we use the CreateArticle function. This will create a new article on the dev.to platform.
np,err:=cl.CreateArticle(devtogo.CreateArticle{Title:"My new dev.to post",Tags:[]string{"go"},BodyMarkdown:"my long markdown article that is preferably read from a file",})
In the above example, we create an article that is in a draft state with a title, some tags and some markdown.
To publish this article on create, we set the Published property to true.
Supposed we want to update this article by publishing it, we simply use the UpdateArticle function.
ua,err:=cl.UpdateArticle(np.ID,devtogo.CreateArticle{Title:"My updates dev.to post using the API",BodyMarkdown:"my new updated content",Published:true,})
Conclusion
In this article, we learnt how to use the devtogo to interact with the dev.to platform using the Go programming language. We also about how to use devtogo.
Full example
This is a full working example that retrieves the latest Go articles.
packagemainimport("fmt""github.com/ShiraazMoollatjie/devtogo""log""os")funcmain(){apiToken:=os.Getenv("DEVTO_TOKEN")ifapiToken==""{log.Fatalf("Set the DEVTO_TOKEN")}dtgc:=devtogo.NewClient(devtogo.WithApiKey(apiToken))al,err:=dtgc.GetArticles(devtogo.Arguments{"tag":"go",})iferr!=nil{log.Fatalf("Cannot retrieve articles: %+v",err)}for_,a:=rangeal{fmt.Printf("Title: %s, Url: %s\n",a.Title,a.URL)}}