Go Programming

go script: RESTful API Framework


package main

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

type Handler struct{}

func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/":
fmt.Fprintf(w, "Welcome to the homepage!")
case "/about":
fmt.Fprintf(w, "This is the about page.")
default:
http.Error(w, "Not found", http.StatusNotFound)
}
}

func main() {
handler := &Handler{}
http.Handle("/", handler)
log.Fatal(http.ListenAndServe(":8080", nil))
}

In this Go script, we are creating a lightweight API framework for building RESTful APIs. The main components of this script are:

1. We define a struct called Handler which will implement the http.Handler interface.
2. The Handler struct has a method ServeHTTP which will handle incoming HTTP requests based on the requested URL path.
3. Inside the ServeHTTP method, we use a switch statement to determine the response based on the URL path.
4. We define two routes: “/” for the homepage and “/about” for the about page.
5. If the requested URL path does not match any of the defined routes, we return a “Not found” error with a 404 status code.
6. In the main function, we create an instance of the Handler struct and register it to handle incoming requests for the “/” path.
7. Finally, we start the HTTP server on port 8080 using http.ListenAndServe, passing in nil as the handler since we have already registered our handler.

This script provides a basic structure for creating a RESTful API framework in Go, allowing you to easily define routes and handle incoming requests.