main.go 565 B

12345678910111213141516171819202122232425262728
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. )
  7. type PingResponse struct {
  8. Message string `json:"message"`
  9. }
  10. func main() {
  11. //根路由
  12. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  13. fmt.Fprintf(w, "Hello, World!")
  14. })
  15. // /ping路由
  16. http.HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) {
  17. w.Header().Set("Content-Type", "application/json")
  18. resp := PingResponse{Message: "pong"}
  19. json.NewEncoder(w).Encode(resp)
  20. })
  21. fmt.Println("Server is running on port 8080")
  22. http.ListenAndServe(":8080", nil)
  23. }