To create an HTTP server on a specific port and host in Go, you can use the ListenAndServe()
function from the net/http
package.
Here's an example code snippet that creates a HTTP server listening on port 8080, and the host being any IP address that the machine running the Go program has:
main.go382 chars24 lines
In the code snippet above:
net/http
and fmt
packages.port
with the value "8080"
and a variable host
with the value ""
.fmt.Printf()
to print the message "Server started on %s:%s\n", where %s
is replaced with host
and port
.http.ListenAndServe()
function to create the server listening on host+":"+port
. If there is any error, it will be printed to the console.gistlibby LogSnag