Creating a Simple HTTP Server
Go has a powerful net/http
package to build web servers.
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello, World!")
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
Create routes with http.HandleFunc
and start the server with ListenAndServe
. Handlers take http.ResponseWriter
and *http.Request
.