create a http server with a specific route in go

To create an http server with a specific route in Go, you need to follow these steps:

  1. First, import the necessary packages:
main.go
import (
    "fmt"
    "log"
    "net/http"
)
46 chars
6 lines
  1. Next, define your route and handler function:
main.go
func myHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Welcome to my website!")
}
104 chars
4 lines
  1. Finally, start the http server and listen for connections on the desired port and route:
main.go
func main() {
    http.HandleFunc("/my-route", myHandler)

    log.Fatal(http.ListenAndServe(":8080", nil))
}
110 chars
6 lines

Here, we've defined a route of "/my-route" and associated it with the myHandler function. Whenever a request is made to this route, the myHandler function will be called and the response "Welcome to my website!" will be written to the response writer.

Note that we're using log.Fatal to log any errors that might occur while starting the server. You could also use log.Println or another logger if you prefer.

related categories

gistlibby LogSnag