惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

The Hacker News
The Hacker News
Google Online Security Blog
Google Online Security Blog
K
Kaspersky official blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
S
Schneier on Security
C
Cybersecurity and Infrastructure Security Agency CISA
Security Archives - TechRepublic
Security Archives - TechRepublic
Hacker News - Newest:
Hacker News - Newest: "LLM"
Cisco Talos Blog
Cisco Talos Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Cyberwarzone
Cyberwarzone
L
LINUX DO - 最新话题
PCI Perspectives
PCI Perspectives
酷 壳 – CoolShell
酷 壳 – CoolShell
云风的 BLOG
云风的 BLOG
N
News and Events Feed by Topic
N
News and Events Feed by Topic
V
Vulnerabilities – Threatpost
T
Troy Hunt's Blog
GbyAI
GbyAI
C
CERT Recently Published Vulnerability Notes
G
Google Developers Blog
Microsoft Azure Blog
Microsoft Azure Blog
量子位
Scott Helme
Scott Helme
月光博客
月光博客
Attack and Defense Labs
Attack and Defense Labs
aimingoo的专栏
aimingoo的专栏
博客园 - 聂微东
Project Zero
Project Zero
G
GRAHAM CLULEY
博客园 - 【当耐特】
Recorded Future
Recorded Future
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
小众软件
小众软件
D
DataBreaches.Net
T
The Blog of Author Tim Ferriss
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
O
OpenAI News
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
V
V2EX
Stack Overflow Blog
Stack Overflow Blog
爱范儿
爱范儿
S
Security @ Cisco Blogs
The Last Watchdog
The Last Watchdog
MongoDB | Blog
MongoDB | Blog
H
Hacker News: Front Page
Latest news
Latest news
P
Proofpoint News Feed

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Go types explained: the foundation you need before writing HTTP handlers
Fer Rios · 2026-06-22 · via DEV Community

A quick introduction to Go types

According to https://go.dev/ref/spec#Types, in Go, a type specifies a set of values, along with operations and methods specific to those values.

This is something fundamental about Go: you can define your own types based on existing ones, and those types can have methods attached to them.

You've probably seen this with structs:

// A struct type — groups fields together
type User struct {
    Name  string
    Email string
}

// A method attached to the User type
func (u User) Greet() string {
    return "Hello, " + u.Name
}

But Go lets you do the same thing with any type, including functions.

Function types

In Go, functions are values. You can assign them to variables, pass them as arguments, and — most importantly here, define a named type based on a function signature:

// This defines a new type called "Greeter"
// whose underlying type is a function that takes a string and returns a string.
type Greeter func(name string) string

Now Greeter is a type, just like int or string or User. Any function with the right signature (func(string) string) is automatically a Greeter.

// This function matches the Greeter signature
func sayHello(name string) string {
    return "Hello, " + name
}

// So we can assign it to a Greeter variable
var g Greeter = sayHello

fmt.Println(g("Alice")) // Hello, Alice

Attaching methods to a function type

Here's where it gets interesting. Because Greeter is now a named type, you can attach methods to it, exactly like you would with a struct:

// A method on a function type — this is valid Go
func (g Greeter) Shout(name string) string {
    return strings.ToUpper(g(name)) // call the function, then shout it
}

fmt.Println(g.Shout("Alice")) // HELLO, ALICE

This might look strange at first. A function with a method? But it makes perfect sense in Go. Greeter is just a type, and any type can have methods.


Why this matters for HTTP handlers

Now that you understand function types, let's look at how Go's HTTP package uses this exact pattern to make your life easier.

Go's HTTP package has two things that are easy to confuse at first: http.Handler and http.HandlerFunc. They sound almost identical, but they play different roles: one is an interface, and one is a type.

http.Handler — the interface

An HTTP handler in GO is an object or function responsible for processing an incoming HTTP request and constructing an HTTP response.

http.Handler is the interface that represents anything that can handle an HTTP request. It has exactly one method:

// http.Handler is an interface — a contract.
// It says: "I don't care what you are.
// As long as you have a ServeHTTP method, you can handle HTTP requests."
type Handler interface {
    ServeHTTP(ResponseWriter, *Request)
}

  • http.ResponseWriter: An interface used to construct and send the HTTP response (setting headers, status codes, and writing the body).

  • *http.Request: A pointer to a struct containing all incoming data (headers, query parameters, URL path, and request body).

So, to be recognized as a handler, a type must implement the http.Handler interface by defining a ServeHTTP.

This is what Go's HTTP server actually works with internally. When you call http.ListenAndServe, the second argument must be an http.Handler:

// The second argument is an http.Handler —
// Go's server calls ServeHTTP on it for every incoming request.
http.ListenAndServe(":8080", myHandler)

Any type that has a ServeHTTP method satisfies this interface automatically. A struct, a function type, anything, as long as it has that one method.

http.HandlerFunc — the type

Here's the problem: writing a full struct with a ServeHTTP method for every single handler in your app is verbose. Most of the time, you just want to write a plain function:

// This is clean and simple, just a function.
// But it's NOT an http.Handler because it has no ServeHTTP method.
func greetUser(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Hello!")
}

This function can't be passed to http.ListenAndServe directly, it's not an http.Handler. It has no ServeHTTP method.

This is exactly the problem http.HandlerFunc solves. It's a named function type with a ServeHTTP method attached, which makes it an http.Handler:

// HandlerFunc is a named type based on a function signature.
// Any function that matches func(ResponseWriter, *Request)
// is automatically compatible with this type.
type HandlerFunc func(ResponseWriter, *Request)

// ServeHTTP is attached to HandlerFunc.
// It just calls the function itself — f is the function, so f(w, r) runs it.
// This single method is what makes HandlerFunc satisfy http.Handler.
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
    f(w, r)
}

Now Go can convert your plain function into an http.HandlerFunc, which has ServeHTTP, which satisfies http.Handler.

You can imagine that this is what Go does under the hood:

var fn http.HandlerFunc = greetUser  // convert the function to HandlerFunc
var h  http.Handler    = fn          // HandlerFunc satisfies http.Handler

But, in practice, you never write these steps manually; you use the http.HandleFunc function.

http.HandleFunc

// Registers the "/hello" route on the default mux.
// http.HandleFunc converts greetUser to HandlerFunc internally —
// you never see that conversion happen.
http.HandleFunc("/hello", greetUser)

http.HandleFunc register a route on the default server mux. It takes a path and a handler function, converts the function to a HandlerFunc internally, and registers it.

http.HandleFunc actually uses http.HandlerFunc internally, it's just hiding it from you:

// This is roughly what http.HandleFunc does under the hood:
func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
    // converts your function to HandlerFunc, then registers it
    DefaultServeMux.Handle(pattern, HandlerFunc(handler))
    //                                ^^^^^^^^^^^^^
    //                                HandlerFunc TYPE doing the conversion
}

So http.HandleFunc is convenience on top of http.HandlerFunc. When you call http.HandleFunc("/hello", greetUser), Go silently wraps greetUser in an http.HandlerFunc and registers it. You only need to use http.HandlerFunc directly when you're building something lower-level, like middleware, where you need to return an http.Handler explicitly.


Putting it all together

Here's the full picture in one example:

// A plain function — clean and simple to write
func greetUser(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Hello!")
}

// A struct handler — useful when you need to hold state like a DB client
type UserHandler struct {
    db *sql.DB // injected dependency
}

func (h *UserHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    // can use h.db here
    fmt.Fprintln(w, "Hello from UserHandler!")
}

func main() {
    mux := http.NewServeMux()

    // http.HandleFunc converts greetUser → HandlerFunc → Handler automatically
    mux.HandleFunc("/hello", greetUser)

    // UserHandler already has ServeHTTP — it satisfies http.Handler directly
    mux.Handle("/user", &UserHandler{db: myDB})

    // Both routes are registered on the same mux —
    // the server calls ServeHTTP on whichever one matches the request path.
    http.ListenAndServe(":8080", mux)
}

TIP: Use a plain function (via HandlerFunc) for simple handlers. Use a struct for handlers that need dependencies like a database client or a config object. The server doesn't care which one you chose — it just calls ServeHTTP.


Summary

Think of it this way:

  • http.Handler is the job description: "must be able to handle HTTP requests"

  • http.HandlerFunc is one way to fulfill that job description: "a plain function that handles HTTP requests"

  • Your struct with a ServeHTTP method is another way to fulfill it

The server only knows about http.Handler. It never knows whether you used a struct or a HandlerFunc — and it doesn't need to. That's the power of the interface.