Go is an excellent choice for writing your next http service. It supports multithreaded request handling with the standard library and many other convenient features that makes creating a new application a breeze. Here is an example of a http service that returns the current time as json.
Playground: https://go.dev/play/p/gZGKLEhHkPR
package main
import (
"encoding/json"
"log"
"net/http"
"time"
)
// Response is a simple json response
// that will be returned by the http server
// the json tags are used to specify the
// json keys
type Response struct {
Status string `json:"status"` // json key is "status"
Time string `json:"time"` // json key is "time"
}
// this is a simple http server that returns a json response
func main() {
// create a new http serve mux
// the serve mux is used to register http handlers
// for different paths
mux := http.NewServeMux()
// register a handler for the "/" path
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// create a response
res := Response{
Status: "OK",
Time: time.Now().Format(time.RFC3339),
}
// marshal the response to json
// the json will be indented with 2 spaces
// bytes contains the json bytes that will be written to the response
bytes, err := json.MarshalIndent(res, "", " ")
if err != nil {
// if there is an error marshaling the response
// write a 500 internal server error to the response
// and return
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// set the content type to application/json
w.Header().Set("Content-Type", "application/json")
// write the json bytes to the response
_, err = w.Write(bytes)
if err != nil {
// if there is an error writing the response
// log the error
log.Println("errror writing response:", err)
}
})
// start the http server
// the server will listen on port 8080
// and use the serve mux to handle requests
// if there is an error starting the server
// log the error and exit
log.Println("starting server at :8080")
if err := http.ListenAndServe(":8080", mux); err != nil {
log.Fatal(err)
}
}