In this article, we will explore the world of REST by creating a simple REST API in the Go programming language.

Golang Rest

For the sake of simplicity, we will create a simple REST server that receives a request to a specific endpoint and returns the list of products in JSON format.

Start by creating a rest.go file which will contain the code for the API:

Handle HTTP Request Function

In the rest.go file, import the required packages:

import (


    “fmt”


    “log”


    “net/http”

)

The previous code imports the fmt, log, and net HTTP package to handle errors, I/O, and HTTP requests using the net/http. We will need the encoding/JSON package later in the code.

For now, the previous imports will work.

The next step is to create a function that will handle the request to a specific endpoint. For testing, we will create a /welcome endpoint that will return the message “Hi, Welcome to RESTful APIs.”

We can do this by defining a function which takes http.ResponseWriter and http.Request.

A code example is shown below:

func welcome(w http.ResponseWriter, r *http.Request) {


    fmt.Fprintf(w, “Hi, Welcome to RESTful APIs.”)

}

The function returns the message to the user when the specified endpoint is hit.

Now, let us define the endpoint available on our server and what function to execute when the client hits that endpoint.

In the main function, add the code as shown below:

func main() {


    http.HandleFunc(“https://linuxhint.com/welcome”, welcome) // create endpoint


    http.ListenAndServe(“:8080”, nil) // listen and serve

}

The previous code uses the http.HandleFunc() method and takes the endpoint and function to execute as the parameters.

The ListenAndServe method will listen on the specified port and then handle all the incoming requests to the server.

Next, run the previous code to ensure everything works correctly. Open your browser and access, http://localhost:8080/welcome

This should return the message as defined in our previous code.

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2022/02/echo/Golang-REST-API-1.png" data-lazy- height="220" src="data:image/svg xml,” width=”1648″>

With the basics out of the way, we can proceed to create a more interesting API. For the next section, you will need to import the encoding/JSON package to encode the JSON data.

We will create a struct that holds the products in our stock. A struct example is provided below:

type Product struct {


    Id int `json:“id”`


    Product_name string `json:“name”`


    Price int `json:“price”`


    Instock bool `json:“stock”`

}

Next, we can define a type Products of type Product that will hold an array:

The next step is to set up an endpoint to return the products in JSON format. For that, we can define a simple function called getProducts as shown:

func getProducts(w http.ResponseWriter, r  *http.Request) {


    products := Products{


        Product{


            Id: 1,


            Product_name: “Macbook Pro”,


            Price: 5999,


            Instock: true,


        },


        {


            Id: 2,


            Product_name: “Amazon Echo”,


            Price: 299,


            Instock: false,


        },


    }


    json.NewEncoder(w).Encode(products)

}

The previous function takes the products information and encodes it.

Finally, we can add an HTTP handler when the client hits the /products endpoint in the main function:

http.HandleFunc(“https://linuxhint.com/products”, getProducts)

And with that, we have our API ready to go. To test it, run the rest.go file and open your browser to the address:

http://localhost:8080/products

This should return JSON information with the product information:

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2022/02/echo/Golang-REST-API-2.png" data-lazy- height="90" src="data:image/svg xml,” width=”1658″>

Conclusion

This concludes this tutorial on setting up a simple REST API in Go. Although simplistic, it serves as a foundation for building faster and more complex APIs. We hope you found this article helpful. Check out other Linux Hint articles for more tips and articles.

About the author

<img data-del="avatar" data-lazy-src="https://kirelos.com/wp-content/uploads/2022/02/echo/john-150×150.png6215f5f8d5484.jpg" height="112" src="data:image/svg xml,” width=”112″>

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list