Certainly! Below is a simple but well-structured backend for a journal app in Go where users can:
Post journal entries (thoughts)
Other users can comment on entries
Users can like entries
Users can share entries (we'll simulate sharing by generating a shareable link)
Key features:
REST API
Basic in-memory storage (for simplicity; you can replace with DB)
Proper project structure
Basic user authentication (mocked for simplicity)
JSON API
Project Structure
code Copy code
journal-app/
├── cmd/
│ └── server/
│ └── main.go
├── internal/
│ ├── handlers/
│ │ └── handlers.go
│ ├── models/
│ │ └── models.go
│ ├── storage/
│ │ └── storage.go
│ └── middleware/
│ └── auth.go
├── go.mod
└── go.sum
Step 1: go.mod
bash Copy code
go mod init journal-app
go get github.com/gorilla/mux
Step 2: Define models (internal/models/models.go)
go Copy code
package models
import "time"
type User struct {
ID string `json:"id"`
Name string `json:"name"`
}
type JournalEntry struct {
ID string `json:"id"`
AuthorID string `json:"author_id"`
Content string `json:"content"`
CreatedAt time.Time `json:"created_at"`
Likes int `json:"likes"`
Comments []Comment `json:"comments"`
}
type Comment struct {
ID string `json:"id"`
AuthorID string `json:"author_id"`
Content string `json:"content"`
CreatedAt time.Time `json:"created_at"`
}
Step 3: Storage layer (internal/storage/storage.go)
go Copy code
package storage
import (
"errors"
"sync"
"time"
"journal-app/internal/models"
"github.com/google/uuid"
)
type Storage struct {
mu sync.RWMutex
users map[string]models.User
entries map[string]models.JournalEntry
}
func New() *Storage {
return &Storage{
users: make(map[string]models.User),
entries: make(map[string]models.JournalEntry),
}
}
// User operations
func (s *Storage) AddUser(user models.User) {
s.mu.Lock()
defer s.mu.Unlock()
s.users[user.ID] = user
}
func (s *Storage) GetUser(id string) (models.User, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
user, ok := s.users[id]
return user, ok
}
// JournalEntry operations
func (s *Storage) AddEntry(authorID, content string) models.JournalEntry {
s.mu.Lock()
defer s.mu.Unlock()
entry := models.JournalEntry{
ID: uuid.NewString(),
AuthorID: authorID,
Content: content,
CreatedAt: time.Now(),
Likes: 0,
Comments: []models.Comment{},
}
s.entries[entry.ID] = entry
return entry
}
func (s *Storage) GetEntry(id string) (models.JournalEntry, error) {
s.mu.RLock()
defer s.mu.RUnlock()
entry, ok := s.entries[id]
if !ok {
return models.JournalEntry{}, errors.New("entry not found")
}
return entry, nil
}
func (s *Storage) ListEntries() []models.JournalEntry {
s.mu.RLock()
defer s.mu.RUnlock()
entries := make([]models.JournalEntry, 0, len(s.entries))
for _, e := range s.entries {
entries = append(entries, e)
}
return entries
}
func (s *Storage) AddComment(entryID, authorID, content string) (models.Comment, error) {
s.mu.Lock()
defer s.mu.Unlock()
entry, ok := s.entries[entryID]
if !ok {
return models.Comment{}, errors.New("entry not found")
}
comment := models.Comment{
ID: uuid.NewString(),
AuthorID: authorID,
Content: content,
CreatedAt: time.Now(),
}
entry.Comments = append(entry.Comments, comment)
s.entries[entryID] = entry
return comment, nil
}
func (s *Storage) LikeEntry(entryID string) error {
s.mu.Lock()
defer s.mu.Unlock()
entry, ok := s.entries[entryID]
if !ok {
return errors.New("entry not found")
}
entry.Likes++
s.entries[entryID] = entry
return nil
}
Step 4: Middleware for simple auth (internal/middleware/auth.go)
For simplicity, we will mock user authentication by passing a header X-User-ID.
go Copy code
package middleware
import (
"context"
"net/http"
)
type contextKey string
const UserIDKey contextKey = "userID"
func AuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
userID := r.Header.Get("X-User-ID")
if userID == "" {
http.Error(w, "Unauthorized: missing X-User-ID header", http.StatusUnauthorized)
return
}
ctx := context.WithValue(r.Context(), UserIDKey, userID)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func GetUserID(r *http.Request) string {
if val := r.Context().Value(UserIDKey); val != nil {
if userID, ok := val.(string); ok {
return userID
}
}
return ""
}
Step 5: Handlers (internal/handlers/handlers.go)
go Copy code
package handlers
import (
"encoding/json"
"journal-app/internal/middleware"
"journal-app/internal/models"
"journal-app/internal/storage"
"net/http"
"github.com/gorilla/mux"
)
type Handler struct {
store *storage.Storage
}
func NewHandler(store *storage.Storage) *Handler {
return &Handler{store: store}
}
func (h *Handler) CreateEntry(w http.ResponseWriter, r *http.Request) {
userID := middleware.GetUserID(r)
var req struct {
Content string `json:"content"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
entry := h.store.AddEntry(userID, req.Content)
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(entry)
}
func (h *Handler) ListEntries(w http.ResponseWriter, r *http.Request) {
entries := h.store.ListEntries()
json.NewEncoder(w).Encode(entries)
}
func (h *Handler) GetEntry(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
entry, err := h.store.GetEntry(id)
if err != nil {
http.Error(w, "Entry not found", http.StatusNotFound)
return
}
json.NewEncoder(w).Encode(entry)
}
func (h *Handler) AddComment(w http.ResponseWriter, r *http.Request) {
userID := middleware.GetUserID(r)
vars := mux.Vars(r)
entryID := vars["id"]
var req struct {
Content string `json:"content"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
comment, err := h.store.AddComment(entryID, userID, req.Content)
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(comment)
}
func (h *Handler) LikeEntry(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
entryID := vars["id"]
err := h.store.LikeEntry(entryID)
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"message":"liked"}`))
}
func (h *Handler) ShareEntry(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
entryID := vars["id"]
// For demo, just return a fake shareable URL
shareURL := "http://localhost:8080/entries/" + entryID
json.NewEncoder(w).Encode(map[string]string{"share_url": shareURL})
}
Step 6: Main server (cmd/server/main.go)
go Copy code
package main
import (
"journal-app/internal/handlers"
"journal-app/internal/middleware"
"journal-app/internal/storage"
"log"
"net/http"
"github.com/gorilla/mux"
)
func main() {
store := storage.New()
// Add some mock users
store.AddUser(storage.User{ID: "user1", Name: "Alice"})
store.AddUser(storage.User{ID: "user2", Name: "Bob"})
h := handlers.NewHandler(store)
r := mux.NewRouter()
api := r.PathPrefix("/api").Subrouter()
api.Use(middleware.AuthMiddleware)
api.HandleFunc("/entries", h.CreateEntry).Methods("POST")
api.HandleFunc("/entries", h.ListEntries).Methods("GET")
api.HandleFunc("/entries/{id}", h.GetEntry).Methods("GET")
api.HandleFunc("/entries/{id}/comments", h.AddComment).Methods("POST")
api.HandleFunc("/entries/{id}/like", h.LikeEntry).Methods("POST")
api.HandleFunc("/entries/{id}/share", h.ShareEntry).Methods("GET")
log.Println("Server started at :8080")
log.Fatal(http.ListenAndServe(":8080", r))
}
How to run
go mod tidy
go run ./cmd/server
Example requests
bash Copy code
curl -X POST http://localhost:8080/api/entries -H "X-User-ID: user1" -d '{"content":"My first thought"}' -H "Content-Type: application/json"
bash Copy code
curl http://localhost:8080/api/entries -H "X-User-ID: user1"
bash Copy code
curl -X POST http://localhost:8080/api/entries/{entryID}/comments -H "X-User-ID: user2" -d '{"content":"Nice thought!"}' -H "Content-Type: application/json"
bash Copy code
curl -X POST http://localhost:8080/api/entries/{entryID}/like -H "X-User-ID: user2"
bash Copy code
curl http://localhost:8080/api/entries/{entryID}/share -H "X-User-ID: user1"
This is a minimal but extendable backend. You can add persistent storage (Postgres, Mongo), real authentication, and more features as needed.
If you want, I can help you with frontend or database integration next!