create a http server on a specific port in go

Here's an example code snippet for creating an HTTP server on a specific port in Go:

main.go
package main

import (
    "fmt"
    "log"
    "net/http"
)

func main() {
    port := "8080" // set the port number
    http.HandleFunc("/", handleRequest) // set the request handler function
    fmt.Printf("Starting server on port %s...\n", port)
    err := http.ListenAndServe(":"+port, nil) // start the server
    if err != nil {
        log.Fatal("Error starting server: ", err)
    }
}

func handleRequest(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, World!") // write the response body
}
520 chars
22 lines

In this code, we set the port variable to the desired port number. We then use http.HandleFunc() to set the request handler function. This function is called for each incoming request and is responsible for generating the response. In this example, we simply write "Hello, World!" to the response body.

Finally, we start the server by calling http.ListenAndServe() with the port number and nil as arguments. If there's an error, we log it with log.Fatal().

gistlibby LogSnag