Sample Web application using Golang

Adarsha Regmi
2 min readNov 21, 2024

--

Golang holds a strong position in tech field because of its ease, speed and scalability.

1. Setup the Environment

Building a web application using Golang is an excellent choice due to its speed, scalability, and simplicity. Here’s a roadmap and key components to guide you through the process:

1. Set Up Your Environment

  • Install Go: Download and install Go from golang.org.
  • Project Structure:
myapp/
├── main.go
├── config/
├── controllers/
├── models/
├── routes/
├── middlewares/
├── static/
└── templates/

2. Choose a Web Framework

  • Standard: standard net/http can be used
  • Popular Frameworks: other frameworks can be used too::
Gin: Fast and lightweight.
Echo: Simple, high-performance, and extensible.
Fiber: Inspired by Express.js for Node.js.

3. Building a basic net/http

package main

import (
"fmt"
"net/http"
)

func homeHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome to my web application!")
}

func main() {
http.HandleFunc("/", homeHandler)
fmt.Println("Server running on http://localhost:8080")
http.ListenAndServe(":8080", nil)
}

Using Gin Framework:

package main

import (
"github.com/gin-gonic/gin"
)

func main() {
r := gin.Default()

r.GET("/", func(c *gin.Context) {
c.JSON(200, gin.H{"message": "Welcome to my web application!"})
})

r.Run(":8080")
}

4.Database Integration

Use an ORM like GORM or Ent, or directly work with database/sql.

package main

import (
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)

type User struct {
ID uint `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
}

func main() {
db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}

db.AutoMigrate(&User{})

db.Create(&User{Name: "John", Email: "john@example.com"})
}

5.Adding Middleware

Using Gin

func authMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// Authentication logic
c.Next()
}
}

6. Static Files and Templates

  • Serve static files (CSS, JS):
r.Static("/assets", "./assets")
  • use go template
r.LoadHTMLGlob("templates/*")
r.GET("/home", func(c *gin.Context) {
c.HTML(http.StatusOK, "home.html", gin.H{"title": "Home Page"})
})

7. Api Development

  • Go lang is perfect for building RESTful APIs:
  • Use JSON encoding/decoding via encoding/json or frameworks like Gin for easier handling.
r.POST("/api/user", func(c *gin.Context) {
var user User
if err := c.ShouldBindJSON(&user); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "User created", "user": user})
})

8. Deploying the application

  • Use Docker for containerization.
  • Deploy on platforms like AWS, GCP, or DigitalOcean.
FROM golang:1.20
WORKDIR /app
COPY . .
RUN go build -o main .
EXPOSE 8080
CMD ["./main"]

9. Use go testing framework

func TestHomeHandler(t *testing.T) {
req, err := http.NewRequest("GET", "/", nil)
if err != nil {
t.Fatal(err)
}

rr := httptest.NewRecorder()
handler := http.HandlerFunc(homeHandler)
handler.ServeHTTP(rr, req)

if status := rr.Code; status != http.StatusOK {
t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK)
}
}

10. Advanced Features

  • WebSocket: Use github.com/gorilla/websocket for real-time features.
  • Caching: Integrate Redis or Memcached.
  • Authentication: Use JWT with libraries like github.com/dgrijalva/jwt-go.
  • CI/CD: Use GitHub Actions or GitLab CI.

--

--

No responses yet