Skip to content

Latest commit

 

History

History
166 lines (140 loc) · 11 KB

File metadata and controls

166 lines (140 loc) · 11 KB

Using golang / Go As A PHP Developer

Disclaimer: This is a personal summary and interpretation based on a YouTube video. It is not official material and not endorsed by the original creator. All rights remain with the respective creators.

This document summarizes the key takeaways from the video. I highly recommend watching the full video for visual context and coding demonstrations.

Before You Get Started

  • I summarize key points to help you learn and review quickly.
  • Simply click on Ask AI links to dive into any topic you want.

AI-Powered buttons

Teach Me: 5 Years Old | Beginner | Intermediate | Advanced | (reset auto redirect)

Learn Differently: Analogy | Storytelling | Cheatsheet | Mindmap | Flashcards | Practical Projects | Code Examples | Common Mistakes

Check Understanding: Generate Quiz | Interview Me | Refactor Challenge | Assessment Rubric | Next Steps

Developer Loop and Hot Reloading

Go offers a fast iteration cycle similar to PHP, where changes reflect immediately without waiting for compilation. Tools like 'air' enable hot reloading, including live reload via proxy without extra setup. For templating systems like Temple, it handles recompilation and server restarts seamlessly. Key takeaway: On slower machines, there might be a slight delay, but overall, it mimics PHP's quick refresh in the browser. Ask AI: Go Developer Loop

Handling Legacy Versions and Built-in Features

Unlike PHP, where upgrading from old versions like 5.6 involves major jumps and framework dependencies, Go builds web features directly into the language. No need for monolithic frameworks like Laravel or Symfony; everything ships with the runtime. Key takeaway: This reduces ecosystem fragmentation, as you avoid dealing with outdated PHP sites or diverse CMS like WordPress. Ask AI: Go vs PHP Legacy Handling

Deployment on Shared Hosting

Go apps compile to a single binary, making deployment portable across platforms like shared hosting via CGI or FastCGI. Build on any OS, target Linux/AMD64, and upload—no runtime version worries. Disable CGO for static builds to avoid external dependencies. Key takeaway: Supports database connections, JWT, encryption, and image processing without C libraries. Source code is protected in the binary, unlike PHP's need for encoders like IonCube.

// Example: Building without CGO
GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o main

Ask AI: Go Deployment on Shared Hosting

Language Differences: Procedural vs OOP

Go favors procedural, imperative code with composition over encapsulation, unlike PHP's interfaces, traits, and OOP. It's not fully functional but has some OO properties. Adapt by using structs and methods instead of classes. Key takeaway: For custom types like handling nulls in databases, implement interfaces like Scanner directly on structs for seamless integration.

type NullTime struct {
    Time  time.Time
    Valid bool
}

func (nt *NullTime) Scan(value interface{}) error {
    // Implementation for scanning from database
}

Ask AI: Go Language Paradigms

Function Composition for Optional Parameters

Go lacks optional parameters, so use composition: wrap functions to provide defaults or extensions. This avoids global namespaces while keeping things statically typed. Key takeaway: Attach handlers to structs for context passing, like database connections, without global availability.

type AppContext struct {
    DB *sql.DB
}

func (app *AppContext) RegisterHandler(w http.ResponseWriter, r *http.Request) {
    // Handler logic using app.DB
}

Ask AI: Go Function Composition

Switching Between HTTP and FastCGI

Easily toggle between dedicated HTTP servers and FastCGI for shared hosting using environment variables. Load configs from .env files and serve accordingly. Key takeaway: Use .htaccess for routing, similar to PHP's mod_rewrite, to hide script names in URLs and protect sensitive files.

AddHandler fcgid-script .fcgi
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ main.fcgi/$1 [QSA,L]

Ask AI: Go HTTP vs FastCGI

Database Migrations and Seeding

Use Goose for SQL-based migrations with up/down commands. Embed migrations in the binary for automatic runs on deployment. Seeding can pull data from external sources like GitHub CSVs. Key takeaway: Call migrations from the main function with relative paths for seamless setup on new servers.

goose.Up(db, "migrations")

Ask AI: Go Database Migrations

Asynchronous Work with Goroutines

Go's goroutines enable built-in async without PHP's hacks like curl to self or cron jobs. Run parallel tasks, like waiting 5 seconds each, completing in total time of the longest. Key takeaway: Channels collect results; avoids overhead of extra connections in PHP.

ch := make(chan string)
for i := 0; i < 5; i++ {
    go func() {
        time.Sleep(5 * time.Second)
        ch <- "result"
    }()
}

Ask AI: Go Goroutines

Background Tasks and Limitations

Start non-blocking background jobs that run independently, like writing to files every 10 seconds. In FastCGI, processes have timeouts (e.g., 1 hour default). Key takeaway: CGI waits for completion before responding, limiting early outputs. Buffers in Apache affect flushing. Ask AI: Go Background Tasks

Server-Side Events and WebSockets in Go

SSE works in HTTP mode but not in FastCGI due to buffers (e.g., 64KB default). WebSockets and gRPC are unavailable in shared hosting's FastCGI. Key takeaway: Proxy modes in 'air' may conflict with SSE; use direct HTTP for testing. Ask AI: Go SSE and WebSockets

Templating with Temple

Temple provides Go-like syntax in templates, similar to Blade in Laravel, with JSX-style embedding. Supports HTMX for partial responses in SPA-like experiences. Key takeaway: Lacks full IDE support (e.g., no auto-formatting), but simplifies logic hiding, like conditional full/partial renders.

templ Layout(req *http.Request) {
    if !htmx.IsHTMX(req) {
        // Full HTML
    }
    { children... }
}

Ask AI: Go Templating with Temple

Debugging and Deployment Tools

Use Delve for debugging, integrable with 'air' for auto-reconnect on reloads. Ansible or custom SSH scripts handle deployments quickly (2-3 seconds for simple updates). Key takeaway: GoLand offers remote browsing and database inspection, akin to PHPStorm. Ask AI: Go Debugging Tools

Productivity and Customization

Productivity matches PHP once familiar; build core functions without monolithic frameworks. Easily customize features like JWT signing, avoiding layers in frameworks like Laravel. Key takeaway: Simplifies overrides for edge cases, like ignoring expirations based on token subjects. Ask AI: Go Productivity for PHP Devs


About the summarizer

I'm Ali Sol, a Backend Developer. Learn more: