DEV Community

Cover image for Making a Rest API in Golang (Part-1)
code-withAshish
code-withAshish

Posted on

Making a Rest API in Golang (Part-1)

I hear you wanna give golang a try on your backend stack?
I am trusting you that you have a Code editor (Vscode,vim etc...), golang installed on your system, these two are the only prequsites for this article, Good let's get going.

What are we building?

We will build a REST API with CRUD (Create,Read,Update,Delete) functionality using a Postgres database imitating a bookstore backend (not for production lol), also we will mostly using standard go builtin modules or just small convenience packages built over it we don't need any framework for a task this simple golang is a framework in itself.

Step 1

Make a directory anywhere that you work on your machine i am gonna name it go-api on linux (What? you use windows get out)

mkdir go-api
Enter fullscreen mode Exit fullscreen mode

then open the folder in your code editor and run

# replace go-api with your folder name
go mod init go-api
Enter fullscreen mode Exit fullscreen mode

and then you should see a go.mod file created in your folder, cool now go ahead and make the main file main.go and start coding.

We will use a routing library go-chi

go get -u github.com/go-chi/chi/v5
Enter fullscreen mode Exit fullscreen mode

in your main.go file write this, it's a fairly simple code and i have explained it through inine comments and also people coming from node and expressJS land must be familiar with this kind of syntax.

// main.go
package main

import (
    "net/http"

    "github.com/go-chi/chi/v5"
    "github.com/go-chi/chi/v5/middleware"
)

func main() {
    // make a new router instance
    app := chi.NewRouter()

    // register a middleware for logging
    app.Use(middleware.Logger)

    // handler for requests to / route
    app.Get("/", func(w http.ResponseWriter, r *http.Request) {
        // writes hello world to the writer
        w.Write([]byte("hello world"))
    })

    // starts up this server instance on port 3000
    http.ListenAndServe(":3000", app)
}
Enter fullscreen mode Exit fullscreen mode

If you have written your code correctly, now when you run

go run main.go
Enter fullscreen mode Exit fullscreen mode

and go to your browser or any tool you like to test your API with curl,postman etc.. and hit the localhost:3000 you should see an output like this if you're on a browser

browser output

and the middleware will log the request on the server a.k.a console like this

console output

and voila we created our hello world server and it's up and running!!!

Comment below if you don't understand something or if you have some suggestions I would love to read them.

In next part we will setup our and database and create models, stay tuned...

Top comments (0)