- read

Implement REST API in Golang using Net/http

Aman lalwani 1

Net/http is one of the most popular standard libraries in Go, which provides a set of functions and structures for building HTTP services. This package makes it easy to build HTTP clients and servers in Go.
The net/http package provides several useful features for HTTP clients and servers, such as HTTP request/response handling, URL routing, cookie handling, and much more.

Implementation

Step 1:- Create a project

go init module_name

Step 2:- Create main.go and write the below code to populate.

// main.go

package main

import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
)
// It creates an Article struct type and an Articles array type to hold the data.
type Article struct{
ID string `json:"ID"`
Title string `json:"Title"`
Desc string `json:"desc"`
Content string `json:"Content"`
}
type Articles []Article

func allArticles(w http.ResponseWriter, r *http.Request){
articles:=Articles {
Article{ID:"1" ,Title:"Test Atricle",Desc:"test description", Content:"Hello World"},
Article{ID:"2" ,Title:"Test Atricle",Desc:"test description", Content:"Hello World"},
}
fmt.Println("Endpoint Hit: All Articles Endpoint")
json.NewEncoder(w).Encode(articles)
}
// singleArticle is used to return a single article with a specific ID from the Articles array and accepts a http.ResponseWriter and *http.Request as arguments.
func singleArticle(w http.ResponseWriter, r *http.Request){
params:=mux.Vars(r)
log.Print(params)
articles:=Articles {
Article{ID:"1" ,Title:"Test Atricle",Desc:"test description", Content:"Hello World"},
Article{ID:"2" ,Title:"Test Atricle",Desc:"test description", Content:"Hello World"},
}
for _, article := range articles{
if article.ID == params["id"]{
json.NewEncoder(w).Encode(article)
return
}}
json.NewEncoder(w).Encode(&Article{})


}

func PostArticles(w http.ResponseWriter, r *http.Request){
fmt.Fprintf(w, "post endpoint worked")
}
// It creates an Article struct type and an Articles array type to hold the data.
func homepage(w http.ResponseWriter, r *http.Request){
fmt.Fprintf(w,"Homepage endpint hit" )
}
func handleRequests(){
// It handles all the requests using the Gorilla Mux router.
myRouter := mux.NewRouter().StrictSlash(true)
// It handles different requests using the HandleFunc method of the router, pairing a specific url and the appropriate handler function.
myRouter.HandleFunc("/",homepage)
myRouter.HandleFunc("/articles",allArticles).Methods("GET")
myRouter.HandleFunc("/articles",PostArticles).Methods("POST")
myRouter.HandleFunc("/article/{id}",singleArticle).Methods("GET")
// It also starts the server using the ListenAndServe method of the httppackage.
log.Fatal(http.ListenAndServe(":8081",myRouter))
}
// main is the main entrypoint of the application and is responsible for creating and initializing the server.
func main(){
handleRequests()
}

Step 3:- Run the server

go run main.go

Testing