To create an HTTP server in Go, you can use the net/http
library from the standard Go package. Here is an example of a basic HTTP server that handles GET requests:
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Bem-vindo ao meu servidor!")
})
http.ListenAndServe(":8080", nil)
}This code creates a server that listens on port 8080 and sends the message "Welcome to my server!" to the client in response to any GET request sent to the root path (/).
To add other functionality to your server, you can use the http library methods to register handlers for different request paths and methods, such as POST, PUT, and DELETE. You can also add support for different content formats, such as JSON and HTML, using the encoding/json and html/template packages, respectively.