Home  Golang   Code to lau ...

code to launch web server using golang

Here's a basic example of how to create a simple web server in Go:

package main

import (
    "fmt"
    "net/http"
)

func main() {
    // Define a route handler
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello, World!")
    })

    // Start the server on port 8080
    fmt.Println("Server listening on port 8080...")
    if err := http.ListenAndServe(":8080", nil); err != nil {
        fmt.Println(err)
    }
}

Explanation:

  1. Package Declaration and Imports:

    • package main: Indicates that this Go file is part of the main package, which is required for an executable program.
    • import "net/http": Imports the standard library net/http package, which provides HTTP client and server implementations.
  2. Main Function (main()):

    • This is the entry point of any Go program.
    • Inside main(), a route handler is defined using http.HandleFunc().
  3. Route Handler (http.HandleFunc()):

    • http.HandleFunc("/", handler) registers a handler function (handler) for the root URL path ("/").
    • The handler function is a simple anonymous function that writes "Hello, World!" to the HTTP response (w).
  4. Starting the Server (http.ListenAndServe()):

    • http.ListenAndServe(":8080", nil) starts an HTTP server listening on port 8080.
    • The second parameter (nil) specifies that the server should use the default ServeMux (multiplexer) provided by http package, which is sufficient for most simple cases.
  5. Server Startup Message:

    • fmt.Println("Server listening on port 8080...") prints a message to indicate that the server has started and is listening on port 8080.
  6. Error Handling:

    • if err := http.ListenAndServe(":8080", nil); err != nil { fmt.Println(err) }: Checks if there's any error starting the server and prints it if there's an error.

Running the Program:

To run this Go program:

  1. Save the code to a file named main.go (or any name ending with .go).

  2. Open a terminal or command prompt.

  3. Navigate to the directory where you saved main.go.

  4. Run the program by typing:

    go run main.go
    
  5. Open a web browser and navigate to http://localhost:8080/. You should see "Hello, World!" displayed in the browser.

Additional Notes:

This example provides a basic foundation for creating web servers in Go. You can expand upon this by adding more routes, middleware, or integrating with databases as per your application's requirements.

Published on: Jun 19, 2024, 11:25 PM  
 

Comments

Add your comment