Creating HTTP server in Go is as simple as:
package main
import ( "fmt"; "net/http" )
func hi(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "Oh hi!\n")
}
func main() {
http.HandleFunc("/hi", hi)
http.ListenAndServe(":8222", nil)
}
http.ListenAndServe(":8222", nil)
Here we've created simple server listening for requests on 8222
port of our machine. This is available from net/http
package.
http.HandleFunc("/hi", hi)
This asks Go to handle all /hi
requests with hi()
function.
func hi()
This function just answers to any HTTP request with Oh hi!
text. We use fmt.Fprintf
to write text to http.ResponseWriter
.
You might also want to know how to get client ip, query parameters values or work with request body.
Top comments (0)