Skip to content

Gin Framework

Ref - https://github.com/gin-gonic/gin

package main
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
)
func hello(w http.ResponseWriter, req *http.Request) {
fmt.Fprint(w, "hello")
}
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "pong",
})
})
r.Run("127.0.0.1:3000")
}

Receiving/Sending back custom JSON

package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
// Define the input struct for incoming requests
type OrderRequest struct {
Stock string `json:"stock" binding:"required"`
Type string `json:"type" binding:"required,oneof=buy sell"` // Only allow "buy" or "sell"
Price float64 `json:"price" binding:"required"`
Quantity int `json:"quantity" binding:"required"`
}
// Define the response struct for outgoing responses
type OrderResponse struct {
FilledQty int `json:"filledQty"`
}
func processOrder(c *gin.Context) {
var order OrderRequest
// Bind incoming JSON to the OrderRequest struct
if err := c.ShouldBindJSON(&order); err != nil {
// If there is an error, return a 400 Bad Request with the error message
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// Here you would implement your business logic to calculate filledQty
// For demonstration, we'll just set it to the quantity received
filledQty := order.Quantity // This is just a placeholder
// Create the response
response := OrderResponse{
FilledQty: filledQty,
}
// Send the response as JSON
c.JSON(http.StatusOK, response)
}
func main() {
r := gin.Default()
// Endpoint for the order processing
r.POST("/order", processOrder)
// Start the server
r.Run("127.0.0.1:3000")
}

Gin Framework Example

Some more examples - https://gin-gonic.com/docs/examples/