Skip to content
Go

HTTP Server

Create an HTTP server.

By EZ4Code Team
httpserver

Code

package main

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

func main() {
    http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello, %s!", r.URL.Query().Get("name"))
    })

    http.HandleFunc("/api/user", func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json")
        json.NewEncoder(w).Encode(map[string]any{
            "name": "Alice",
            "age":  30,
        })
    })

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

Explanation

net/http provides a built-in HTTP server; routes are registered via HandleFunc.

More Go Snippets