Chapter 15: HTTP Servers

Introduksyon

Ang Go net/http package kay dali ra gamiton para maghimo ug HTTP servers. Pipila lang ka linya, pwede ka mag-serve ug web pages, REST APIs, ug static files. Anhi nga chapter: routing, handlers, templating, static resources, JSON APIs — kompleto na.

How to Build a Basic Server

Ang minimal HTTP server nagamit ug http.HandleFunc para mag-register ug routes ug http.ListenAndServe para mag-start ug listening. Dali ra kaayo:

package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello, World!")
    })

    http.ListenAndServe(":8080", nil)
}

HTTP Handler

Ang HTTP handler kay bisan unsa na type basta nag-implementar sa http.Handler interface:

type Handler interface {
    ServeHTTP(w http.ResponseWriter, r *http.Request)
}

http.HandleFunc nag-convert ug ordinary function into handler. Ang w (ResponseWriter) kay para magpadala ug response, ang r kay may request data gikan sa client.

Exercise 15.01: Creating a Hello World Server

Goal: Paghimo ug HTTP server nga mu-respond ug "Hello, World!" sa root path.

package main

import (
    "fmt"
    "net/http"
)

func helloHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, World!")
}

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

Simple Routing

Gamit ug http.HandleFunc na may lain-laing paths. Ang default mux mu-match sa longest prefix — automatic na:

http.HandleFunc("/", homePage)        // matches everything
http.HandleFunc("/about", aboutPage)   // matches /about
http.HandleFunc("/api/", apiHandler)   // matches /api/*

Exercise 15.02: Routing Our Server

Goal: Paghimo ug server naay /, /about, ug /contact routes — tagsa-tagsa ug lain nga content ang i-return.

package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Home Page")
    })
    http.HandleFunc("/about", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "About Us")
    })
    http.HandleFunc("/contact", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Contact Page")
    })

    fmt.Println("Server on :8080")
    http.ListenAndServe(":8080", nil)
}

Handler versus Handler Function

http.Handler kay interface naay ServeHTTP. http.HandlerFunc kay function type na mu-adapt ug regular function into http.Handler. Parehas ra ang effect:

// Handler (struct)
type home struct{}
func (h home) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Home")
}

// HandlerFunc (function)
func homePage(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Home")
}

// Both work:
http.Handle("/", home{})
http.HandleFunc("/", homePage)

Activity 15.01: Adding a Page Counter to an HTML Page

Goal: Paghimo ug server nga mu-count kung pila ka beses na-visit ang page ug i-display ang count.

package main

import (
    "fmt"
    "net/http"
    "sync"
)

type Counter struct {
    mu    sync.Mutex
    count int
}

func (c *Counter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    c.mu.Lock()
    c.count++
    c.mu.Unlock()
    fmt.Fprintf(w, "Visits: %d", c.count)
}

func main() {
    http.Handle("/", &Counter{})
    http.ListenAndServe(":8080", nil)
}

Returning Complex Structures

I-return ang JSON gikan sa imong API pinaagi sa pag-set ug Content-Type header ug pag-encode ug data:

type User struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func userHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(User{"Alice", 30})
}

Activity 15.02: Serving a Request with a JSON Payload

Goal: Paghimo ug endpoint /api/time nga mu-return ug current time as JSON.

package main

import (
    "encoding/json"
    "net/http"
    "time"
)

type TimeResponse struct {
    Time    string `json:"time"`
    Unix    int64  `json:"unix"`
}

func timeHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    now := time.Now()
    json.NewEncoder(w).Encode(TimeResponse{
        Time: now.Format(time.RFC3339),
        Unix: now.Unix(),
    })
}

func main() {
    http.HandleFunc("/api/time", timeHandler)
    http.ListenAndServe(":8080", nil)
}

Dynamic Content

Basaha ang values gikan sa URL or query string para mag-generate ug dynamic responses — depende sa gusto sa user:

func greetHandler(w http.ResponseWriter, r *http.Request) {
    name := r.URL.Query().Get("name")
    if name == "" {
        name = "World"
    }
    fmt.Fprintf(w, "Hello, %s!", name)
}

// Visit: http://localhost:8080/greet?name=Alice

Exercise 15.03: Personalized Welcome

Goal: Paghimo ug /welcome endpoint nga magbasa ug "name" query parameter ug mu-respond ug personalized greeting.

package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/welcome", func(w http.ResponseWriter, r *http.Request) {
        name := r.URL.Query().Get("name")
        if name == "" {
            name = "Guest"
        }
        fmt.Fprintf(w, "Welcome, %s!", name)
    })
    http.ListenAndServe(":8080", nil)
}

Templating

Ang Go html/template package nagprovide ug safe HTML templating na may automatic escaping — di ka ma-XSS:

import "html/template"

// Template file (template.html):
// 

Hello, {{.Name}}!

//

You are {{.Age}} years old.

type PageData struct { Name string Age int } func handler(w http.ResponseWriter, r *http.Request) { tmpl := template.Must(template.ParseFiles("template.html")) tmpl.Execute(w, PageData{"Alice", 30}) }

Exercise 15.04: Templating Our Pages

Goal: Gamit ug html/template para mag-serve ug dynamic HTML page nga naay user's name ug list sa hobbies.

package main

import (
    "html/template"
    "net/http"
)

func main() {
    tmpl := template.Must(template.New("page").Parse(`
        

Hello, {{.Name}}!

Hobbies

    {{range .Hobbies}}
  • {{.}}
  • {{end}}
`)) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { data := struct { Name string Hobbies []string }{ Name: "Alice", Hobbies: []string{"Coding", "Reading", "Hiking"}, } tmpl.Execute(w, data) }) http.ListenAndServe(":8080", nil) }

Static Resources

I-serve ang static files (CSS, JS, images) gamit http.FileServer — built-in na:

fs := http.FileServer(http.Dir("./static"))
http.Handle("/static/", http.StripPrefix("/static/", fs))

// Directory structure:
// static/
//   style.css
//   script.js
//   images/logo.png

Exercise 15.05: Creating a Hello World Server Using a Static File

Goal: I-serve ang index.html file gikan sa static directory. Simple.

// Create static/index.html:
// 
// 

Hello from static file!

// main.go: package main import "net/http" func main() { fs := http.FileServer(http.Dir("./static")) http.Handle("/", fs) http.ListenAndServe(":8080", nil) }

Getting Some Style

I-add ang CSS pinaagi sa pag-serve ug static files kauban ang templates. I-reference ang CSS file sa imong HTML:

// static/style.css:
// body { font-family: sans-serif; background: #f0f0f0; }

// Serve it:
http.Handle("/static/", http.StripPrefix("/static/",
    http.FileServer(http.Dir("./static"))))

Exercise 15.06: A Stylish Welcome

Goal: I-serve ang styled HTML page nga may CSS file.

// static/style.css:
body { background: #1b1c24; color: #d4d4dc; font-family: sans-serif; }
h1 { color: #e94560; }

// main.go:
package main

import (
    "html/template"
    "net/http"
)

func main() {
    tmpl := template.Must(template.New("page").Parse(`
        
        

Stylish Welcome

Hello, {{.Name}}!

`)) http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static")))) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { tmpl.Execute(w, struct{ Name string }{"Alice"}) }) http.ListenAndServe(":8080", nil) }

Getting Dynamic

Process form submissions ug mag-interact sa user input. Basaha ang form values gamit r.FormValue or r.ParseForm — diretso na:

func formHandler(w http.ResponseWriter, r *http.Request) {
    if r.Method == "POST" {
        name := r.FormValue("name")
        email := r.FormValue("email")
        fmt.Fprintf(w, "Received: %s (%s)", name, email)
    } else {
        // Serve the form HTML
    }
}

Activity 15.03: External Template

Goal: Load ug HTML template gikan sa external file ug i-render nga may dynamic data.

// Create templates/profile.html:
// 

{{.Name}}'s Profile

//

Email: {{.Email}}

//

Member since: {{.Joined}}

// main.go: package main import ( "html/template" "net/http" "time" ) func main() { tmpl := template.Must(template.ParseFiles("templates/profile.html")) http.HandleFunc("/profile", func(w http.ResponseWriter, r *http.Request) { data := struct { Name string Email string Joined string }{ Name: "Alice", Email: "alice@example.com", Joined: time.Now().Format("2006-01-02"), } tmpl.Execute(w, data) }) http.ListenAndServe(":8080", nil) }

HTTP Methods

Handle lain-laing HTTP methods (GET, POST, PUT, DELETE) sa parehas nga handler — flexible:

func apiHandler(w http.ResponseWriter, r *http.Request) {
    switch r.Method {
    case http.MethodGet:
        fmt.Fprintf(w, "GET request")
    case http.MethodPost:
        fmt.Fprintf(w, "POST request")
    case http.MethodPut:
        fmt.Fprintf(w, "PUT request")
    case http.MethodDelete:
        fmt.Fprintf(w, "DELETE request")
    default:
        http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
    }
}

Exercise 15.07: Completing a Questionnaire

Goal: Paghimo ug form nga mu-accept ug GET para display form ug POST para i-process.

package main

import (
    "fmt"
    "html/template"
    "net/http"
)

var formTmpl = template.Must(template.New("form").Parse(`
    
Name:
Age:
`)) func main() { http.HandleFunc("/survey", func(w http.ResponseWriter, r *http.Request) { if r.Method == "POST" { name := r.FormValue("name") age := r.FormValue("age") fmt.Fprintf(w, "Thank you, %s (age %s)!", name, age) return } formTmpl.Execute(w, nil) }) http.ListenAndServe(":8080", nil) }

JSON loads

I-parse ang incoming JSON request bodies gamit json.Decoder — diretso ug limpyo:

func jsonHandler(w http.ResponseWriter, r *http.Request) {
    var data map[string]any
    err := json.NewDecoder(r.Body).Decode(&data)
    if err != nil {
        http.Error(w, "Invalid JSON", http.StatusBadRequest)
        return
    }
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(map[string]string{
        "received": fmt.Sprintf("%v", data),
    })
}

Exercise 15.08: Building a Server That Accepts JSON Requests

Goal: Paghimo ug server nga naay /api/echo endpoint — mu-accept ug JSON ug i-return balik.

package main

import (
    "encoding/json"
    "net/http"
)

func echoHandler(w http.ResponseWriter, r *http.Request) {
    if r.Method != http.MethodPost {
        http.Error(w, "POST required", http.StatusMethodNotAllowed)
        return
    }

    var data any
    err := json.NewDecoder(r.Body).Decode(&data)
    if err != nil {
        http.Error(w, "Bad JSON", http.StatusBadRequest)
        return
    }

    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(data)
}

func main() {
    http.HandleFunc("/api/echo", echoHandler)
    http.ListenAndServe(":8080", nil)
}

Summary