I am a learner in Go and wrote example below in a day so I would like to get some suggestions to improve it. It is a simple rest api that currently just accepts request and returns a dummy message. My main aim here is to get comments and suggestions on how I structured the flow/logic. Although it currently works fine and easy to follow (at least to me), could it be done in a cleaner/scalable way?
cmd/server.go
package main
import (
"fmt"
"football-api/internal/app/route"
"log"
"net/http"
)
type server struct {}
func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
response, err := route.Handler(r)
if err != nil {
w.WriteHeader(http.StatusNotFound)
} else {
w.WriteHeader(http.StatusOK)
}
w.Write([]byte(response))
}
func main() {
fmt.Println("Server is running on port 8080 ...")
err := http.ListenAndServe(":8080", &server{})
if err != nil {
log.Fatalf("Couldn't start server on :8080. [%s]", err.Error())
}
}
internal/app/route/handler.go
package route
import (
"errors"
"net/http"
"path/filepath"
)
func Handler(r *http.Request) (response string, err error) {
switch filepath.Clean(r.URL.Path) {
case "/":
return Home(r), nil
case "/comments":
return Comments(r), nil
default:
return "", errors.New("route was not found")
}
}
internal/app/route/home.go
package route
import "net/http"
func Home(r *http.Request) string {
return "Home"
}
internal/app/route/comments.go
package route
import "net/http"
func Comments(r *http.Request) string {
return "Comments"
}