How to create rest api with golang

Learn how to create a simple REST API with Go by setting up your development environment, importing necessary packages, defining a request handler function, registering the handler with the HTTP server, and testing the API with a tool such as curl or Postman. Follow these easy steps to get started with building your own REST API in Go.

To create a simple REST API with Go, you can follow these steps:

  1. Set up your development environment:
    • Install the Go programming language.
    • Set up your workspace by creating a directory structure as follows:
    • $GOPATH/



  1. Create a new Go file for your server. For example, you can create a file called main.go in the myproject directory.
  2. Import the necessary packages. You will need to import the net/http package, which provides functions for handling HTTP requests and responses.
  3. Define a function to handle HTTP requests. This function will take an http.ResponseWriter and an http.Request as arguments, and will be responsible for writing the response to the client.
  4. Use the http.HandleFunc function to register your request handler function as a handler for a specific URL pattern.
  5. Start the HTTP server using the http.ListenAndServe function, passing in the port number and an optional handler.
  6. Test your API by sending HTTP requests to the server using a tool such as curl or Postman.

Here is an example of a simple REST API that listens on port 8080 and responds to GET requests with a message:

package main

import (

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello, World!")

	http.ListenAndServe(":8080", nil)

This example creates a simple server that listens on port 8080 and responds to requests with a message "Hello, World!". You can test this API by sending a GET request to http://localhost:8080 using a tool such as curl or Postman.

I hope this helps! Let me know if you have any questions.

  • Mradul Mishra
  • 9¬†months ago

Add a comment: