2022-05-18 00:04:37 +09:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2023-06-24 09:50:21 +09:00
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
2022-05-18 00:04:37 +09:00
|
|
|
"net/http"
|
2023-06-24 09:50:21 +09:00
|
|
|
"os"
|
2022-05-18 00:04:37 +09:00
|
|
|
|
|
|
|
"github.com/syumai/workers"
|
|
|
|
)
|
|
|
|
|
2023-06-24 09:50:21 +09:00
|
|
|
type HelloRequest struct {
|
|
|
|
Name string `json:"name"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type HelloResponse struct {
|
|
|
|
Message string `json:"message"`
|
|
|
|
}
|
|
|
|
|
|
|
|
func HelloHandler(w http.ResponseWriter, req *http.Request) {
|
|
|
|
var helloReq HelloRequest
|
|
|
|
if err := json.NewDecoder(req.Body).Decode(&helloReq); err != nil {
|
|
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
|
|
w.Header().Set("Content-Type", "text/plain")
|
|
|
|
w.Write([]byte("request format is invalid"))
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
msg := fmt.Sprintf("Hello, %s!", helloReq.Name)
|
|
|
|
|
|
|
|
helloRes := HelloResponse{Message: msg}
|
|
|
|
if err := json.NewEncoder(w).Encode(helloRes); err != nil {
|
|
|
|
fmt.Fprintf(os.Stderr, "failed to encode response: %w\n", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-05-18 00:04:37 +09:00
|
|
|
func main() {
|
2023-06-24 09:50:21 +09:00
|
|
|
http.HandleFunc("/hello", HelloHandler)
|
2022-05-18 00:04:37 +09:00
|
|
|
workers.Serve(nil) // use http.DefaultServeMux
|
|
|
|
}
|