Skip to content
Go

Servidor HTTP

Criar um servidor HTTP.

#http#server

Code

go
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)
}