simple-webserver example
Using the standard net/http
package to build a simple webserver.
Lets add REST to this example
simple-webserver-with-REST.
GitHub Webpage
HOW IT WORKS
The /net/http
package lets us map request paths to functions.
-
Set which IP and port you would like to listen on,
log.Fatal(http.ListenAndServe("127.0.0.1:1234", nil))
-
When a request is made for a particular URL kick off your function,
http.HandleFunc("/jeff", jeffHandler)
-
Create your handler function jeffHandler
,
func jeffHandler(res http.ResponseWriter, req *http.Request) {
fmt.Printf("req is %+v\n\n", req.URL)
io.WriteString(res, "hello, Jeff!\n")
}
This illustration may help,
RUN
go run simple-webserver.go
Press return to exit.
You can interact with the web server many different ways.
USING A BROWSER
http://127.0.0.1:1234/
http://127.0.0.1:1234/jeff
http://127.0.0.1:1234/monkey
USING HTTPIE
In another terminal, use a CLI http client like
httpie and you can do the following,
http localhost:1234
http localhost:1234/jeff
http localhost:1234/monkey
Or you can use the IP Address,
http 127.0.0.1:1234
http 127.0.0.1:1234/jeff
http 127.0.0.1:1234/monkey
USING CURL
Or you can use curl,
curl 127.0.0.1:1234
curl 127.0.0.1:1234/jeff
curl 127.0.0.1:1234/monkey