Go Language REST API Part -1

Play this article

In this article, we'll build a simple REST API using Go Language. The API will be a HelloWorld application that responds with "Hello, World!" when accessed.

Setting up the Project

Before we start, make sure you have Go installed on your system. You can download the latest version of Go from the official website golang.org/dl.

To create a new Go project, create a new directory for your project and navigate to it in the terminal. We'll call our project hello-api. Inside the hello-api directory, create a new file called main.go.

Writing the Code

In the main.go file, we'll define a handler function that will respond to HTTP requests. The handler function will write "Hello, World!" to the response.

package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, World!")
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

The handler function takes two arguments: a ResponseWriter and a Request. The ResponseWriter is used to write the response to the client, while the Request contains information about the incoming request.

We register the handler function with the http.HandleFunc function, which tells the http package to call the handler function whenever a request is made to the root path /.

The http.ListenAndServe the function starts the server and listens on port 8080 for incoming requests.

Testing the API

To test our API, run the following command in the terminal:

go run main.go

This will start the server and listen on port 8080. Now open a web browser and go to http://localhost:8080. You should see the message "Hello, World!" displayed in the browser.

Alternatively, you can use a tool like curl to make a request to the API:

curl http://localhost:8080

This should return the message "Hello, World!" in the terminal.

Conclusion

In this article, we've created a simple REST API using Go Language. We've defined a handler function that responds to HTTP requests with the message "Hello, World!". We've also seen how to start the server and test the API using a web browser or curl.

This is just a starting point for building more complex APIs with Go. With this basic knowledge, you can start building APIs that respond to different HTTP methods, handle different types of requests, and store and retrieve data from a database.

I hope this helps, you!!

More such articles:

https://medium.com/techwasti

https://www.youtube.com/channel/UCiTaHm1AYqMS4F4L9zyO7qA

https://www.techwasti.com/

\==========================**=========================

If this article adds any value to you then please clap and comment.

Let’s connect on Stackoverflow, LinkedIn, & Twitter.

Did you find this article valuable?

Support techwasti by becoming a sponsor. Any amount is appreciated!