Ever wanted to build an API but felt overwhelmed? Fear not! In this tutorial, we'll create a simple REST API using Go (Golang) that serves JSON like a pro. Let’s get coding!
Why Build an API in Go? (Because Speed Matters!)
- Blazing Fast – Go is optimized for performance.
- Minimal Dependencies – Standard library covers most needs.
- Scalability – Handles concurrency like a champ.
Setting Up Your Go Project (Get Your Hands Dirty!)
First, make sure Go is installed. Then create a new project:
mkdir go-api && cd go-api
go mod init github.com/yourusername/go-api
Install the gorilla/mux package for routing:
go get -u github.com/gorilla/mux
Writing Your First API in Go (It’s Easier Than You Think)
Create a new file main.go
and add:
package main
import (
"encoding/json"
"fmt"
"net/http"
"github.com/gorilla/mux"
)
type Response struct {
Message string `json:"message"`
}
func homeHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(Response{Message: "Welcome to your first Go API!"})
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/", homeHandler).Methods("GET")
fmt.Println("Server running on port 8080")
http.ListenAndServe(":8080", r)
}
Run it:
go run main.go
Visit http://localhost:8080
in your browser and see your first API response!
Adding More Endpoints (Because One is Never Enough!)
Fetching Data:
var users = []string{"Alice", "Bob", "Charlie"}
func getUsers(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(users)
}
Add this to your router:
r.HandleFunc("/users", getUsers).Methods("GET")
Visit http://localhost:8080/users
and see the magic!
You just built your first Go API! Keep improving it by adding CRUD operations, database integration, and even JWT authentication. The backend world is yours!
0 Comments