Go, also known as Golang, is an open-source programming language created by Google. Its simple syntax, speed of execution, and native support for networking make it ideal for developing web applications. In this article, well explore how to create an HTTP client and server using Go, providing code examples to help you get started.
Create the HTTP Server
Lets start by creating a basic HTTP server using Go.
package main
import (
"fmt"
"net/http"
)
func helloHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Ciao, benvenuto sul nostro server HTTP in Go!")
}
func main() {
http.HandleFunc("/", helloHandler)
httpPort := ":8080"
fmt.Printf("Server in ascolto su http://localhost%s\n", httpPort)
err := http.ListenAndServe(httpPort, nil)
if err != nil {
panic(err)
}
}
In this example, weve created a simple handler called
helloHandler
, which will respond with a welcome message when the client makes a request to the root ("/") of the server. Next, we registered the handler using
http.HandleFunc("/", helloHandler)
, which binds the handler to the specified URL. Finally, we start the server by calling
http.ListenAndServe
.
Create the HTTP Client
Now that we have a working HTTP server, lets see how to create an HTTP client in Go to interact with the server.
package main
import (
"fmt"
"net/http"
"io/ioutil"
)
func main() {
serverAddr := "http://localhost:8080"
response, err := http.Get(serverAddr)
if err != nil {
panic(err)
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
panic(err)
}
fmt.Println("Risposta dal server:")
fmt.Println(string(body))
}
In this example, we used
http.Get
to make a GET request to the server specified by
serverAddr
. Next, we read the response body and printed the content obtained from the server.
Conclusion
In this article, you learned how to create an HTTP client and server in Go. This guide has given you a solid foundation to start developing web applications in Go. You can further explore the vast ecosystem of libraries and tools that Go offers to improve and scale your web applications.