code-examples/2024/07/golang_demo1/main.go

98 lines
2.0 KiB
Go

package main
import (
"encoding/json"
"flag"
"fmt"
"net/http"
"time"
)
type PersonRequest struct {
Name string
Age int
}
type PersonResponse struct {
Greeting string
Errors string
}
type StatusResponse struct {
StartDateTime string
UpTime string
Status string
}
var startTime = time.Now()
func main() {
portPtr := flag.Int("port", 8080, "port for webserver")
flag.Parse()
port := *portPtr
fmt.Printf("Server is listening on port: %d", port)
server := http.NewServeMux()
server.HandleFunc("/status", statusHandler)
server.HandleFunc("/greeting", greetingHandler)
err := http.ListenAndServe(fmt.Sprintf("localhost:%d", port), server)
if err != nil {
fmt.Println("Error:", err)
return
}
}
func greetingHandler(writer http.ResponseWriter, request *http.Request) {
decoder := json.NewDecoder(request.Body)
decoder.DisallowUnknownFields()
var p = PersonRequest{}
errDecode := decoder.Decode(&p)
if errDecode != nil {
println("Error: ", errDecode)
writer.WriteHeader(400)
_, _ = writer.Write([]byte("Bad request data"))
return
}
r := PersonResponse{
Greeting: fmt.Sprintf("Hey %s. Your age is %d", p.Name, p.Age),
Errors: "",
}
writer.Header().Add("Content-Type", "application/json")
encoder := produceEncoder(writer)
errEncode := encoder.Encode(&r)
if errEncode != nil {
writer.WriteHeader(500)
println("Error: ", errEncode)
return
}
writer.WriteHeader(200)
}
func produceEncoder(writer http.ResponseWriter) *json.Encoder {
encoder := json.NewEncoder(writer)
return encoder
}
func statusHandler(writer http.ResponseWriter, _ *http.Request) {
upTime := time.Now().Unix() - startTime.Unix()
status := StatusResponse{
Status: "Ok",
StartDateTime: startTime.Format("2006-01-02 15:04:05.000-0700"),
UpTime: fmt.Sprintf("%d", upTime),
}
writer.Header().Add("Content-Type", "application/json")
encoder := produceEncoder(writer)
errEncode := encoder.Encode(&status)
if errEncode != nil {
writer.WriteHeader(500)
println("Error: ", errEncode)
return
}
writer.WriteHeader(200)
}