Golang is a programming language developed by Google. It can used to create cloud services, web , CLI tools etc. The first step to use Go is download and install the SDK.
Basic setup
To build basic API in Golang we need two packages
- http
- mux
go get github.com/gorilla/mux
Mux help us to build API routes . In the main.go file add the following
package main
import
("github.com/gorilla/mux"
"net/http"
"fmt")
// album represents data about a record album.
type album struct {
ID string `json:"id"`
Title string `json:"title"`
Artist string `json:"artist"`
Price float64 `json:"price"`
}
// albums slice to seed record album data.
var albums = []album{
{ID: "1", Title: "Blue Train", Artist: "John Coltrane", Price: 56.99},
{ID: "2", Title: "Jeru", Artist: "Gerry Mulligan", Price: 17.99},
{ID: "3", Title: "Sarah Vaughan and Clifford Brown", Artist: "Sarah Vaughan", Price: 39.99},
}
func index(w http.ResponseWriter, r *http.Request){
fmt.Fprint(w,"Hello world!")
}
func getAlbums(w http.ResponseWriter, r *http.Request){
fmt.Fprint(w,albums)
}
func main(){
r:=mux.NewRouter()
r.HandleFunc("/",index).Methods("GET")
r.HandleFunc("/albums",getAlbums)
fmt.Println("Server starting")
http.ListenAndServe(":8080",r)
}
Here we create a mux router instance which can be used to create API route. We also define handler function for the API too.
:= is the short hand in Golang for creating variables
Run the project
By using go run . or go run main.go can execute the program.
- How to add packages in Golang
- Create REST API using gin in Golang
- How to Containerize Golang app with Docker
- How to create API using mux in Golang
- How to create API using gin in Golang
- How to create API using Fiber in Golang
- Set up golang project
- How to use GORM packages in Golang
- How to solve gcc error in Golang -Windows