Building a Simple REST API in Go with Gin
In this post, we'll explore building a basic REST API using Go and the Gin framework. We'll walk through the code, understand the concepts, and see how to store and retrieve key-value pairs.
Prerequisites:
- Basic understanding of Go programming
- Familiarity with HTTP concepts
What you'll learn:
- Creating a REST API with Gin
- Storing and retrieving data using key-value pairs
- JSON data formatting
Code Snippet:
package main import ( "encoding/json" "fmt" "github.com/gin-gonic/gin" ) var store map[string]string func main() { store = make(map[string]string) router := gin.Default() router.POST("/key", func(c *gin.Context) { key := c.Param("key") value := c.PostForm("value") store[key] = value c.JSON(200, gin.H{"message": "Stored"}) }) router.GET("/key/:key", func(c *gin.Context) { key := c.Param("key") value, ok := store[key] if !ok { c.JSON(404, gin.H{"message": "Not found"}) return } var unmarshaledValue map[string]interface{} err := json.Unmarshal([]byte(value), &unmarshaledValue) if err != nil { c.JSON(500, gin.H{"message": "Error unmarshaling value"}) return } c.JSON(200, unmarshaledValue) }) router.Run() }
Explanation:
Import Libraries:
-
encoding/json
: For JSON data encoding and decoding. -
fmt
: For output formatting. -
github.com/gin-gonic/gin
: The Gin framework for web applications.
Define Map:
-
store
: Amap[string]string
to store key-value pairs.
Create Gin Router:
-
router
: A Gin router instance to handle HTTP requests.
Store Key-Value Pairs:
-
POST /key
: Handles POST requests to store data. - It retrieves the
key
from the URL path andvalue
from the request body. - Stores the pair in the
store
map and returns a "Stored" message.
Retrieve Key-Value Pairs:
-
GET /key/:key
: Handles GET requests to retrieve data. - The
:key
part captures the key from the URL path. - Retrieves the value for the specified key from the
store
map. - Returns a 404 Not Found if the key isn't found.
- Otherwise, unmarshals the JSON-encoded value and returns it.
Run the Server:
-
router.Run()
: Starts the Gin server and listens for requests.
Summary:
This code demonstrates building a simple REST API in Go with Gin. It allows storing and retrieving key-value pairs in JSON format.
I hope this helps! Feel free to ask any questions you may have.
Some of my youtube videos
Top comments (1)
Original video for this blog is web-dev-cody
I just used google gemini to summarise the video and create a blog out of it!