resource:
https://www.digitalocean.com/community/tutorials/how-to-make-an-http-server-in-go
curl : https://www.youtube.com/watch?v=Xy7fDxz39FM
we can use http package from go standard library to create servers and do things related to http
creating a simple server
package main
import (
"fmt"
"net/http"
)
func Hello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "hello")
}
func main() {
http.HandleFunc("/", Hello)
http.ListenAndServe(":8080", nil)
}
if you build and run this application and open the web page you can see “hello” in it
how does this work:
http.HandlerFunc
here, Hello function is known and http handler which takes the http request and and writes the repose to the http response writer, http.HandlerFunc can turn any function into an http handler without implementing http.Handler, http.Handler is an interface which implements function ServeHTTP , we can call any function which has a signature of
func ( w http.ResponceWrtier, r *http.Request) as a http handler and can be used as one
http.HandleFunc
here, http.HandleFunc links the http handler with the specified url, here Hello is called as an handler function, and http.HandleFunc converts the handler function into an handler
http.Handle