In this section, we're going to see how to create a simple web server in Go. It is really easy to create a simple web server in Go due to the built-in API. To begin, we are going to use the net/http
package. A net/http
package has the HandleFunc()
method, which means that it will accept two things. The first is the path of the URL, and the second is the function that you want to handle incoming requests with. Check the following code:
package main import "net/http" func sayHello(w http.ResponseWriter, r *http.Request){ w.Write([]byte("Hello, world")) } func main(){ http.HandleFunc("/", sayHello) err := http.ListenAndServe(":5050", nil) if(err != nil){ panic(err) } }
As long as your method signature satisfies the func sayHello(w http.ResponseWriter, r *http.Request){}
type of method, it will be accepted by our HandleFunc()
. We will use sayHello
as our function and it'll return two things, firstly, http.ResponseWriter
, while the second thing is the...