github.com/abemedia/go-don@v0.2.2-0.20240329015135-be88e32bb73b/examples/simple/main.go (about)

     1  package main
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"log"
     7  	"net/http"
     8  
     9  	"github.com/abemedia/go-don"
    10  	_ "github.com/abemedia/go-don/encoding/json"
    11  	_ "github.com/abemedia/go-don/encoding/text"
    12  	_ "github.com/abemedia/go-don/encoding/yaml"
    13  )
    14  
    15  // Returns 204 - No Content
    16  func Empty(context.Context, any) (any, error) {
    17  	return nil, nil
    18  }
    19  
    20  func Ping(context.Context, any) (string, error) {
    21  	return "pong", nil
    22  }
    23  
    24  type GreetRequest struct {
    25  	Name string `json:"name"`         // Get name from JSON body.
    26  	Age  int    `header:"X-User-Age"` // Get age from HTTP header.
    27  }
    28  
    29  type GreetResponse struct {
    30  	Greeting string `json:"data"`
    31  }
    32  
    33  // Set a custom HTTP response code.
    34  func (gr *GreetResponse) StatusCode() int {
    35  	return http.StatusTeapot
    36  }
    37  
    38  // Add custom headers to the response.
    39  func (gr *GreetResponse) Header() http.Header {
    40  	header := http.Header{}
    41  	header.Set("foo", "bar")
    42  	return header
    43  }
    44  
    45  func Greet(ctx context.Context, req *GreetRequest) (*GreetResponse, error) {
    46  	if req.Name == "" {
    47  		return nil, don.ErrBadRequest
    48  	}
    49  
    50  	res := &GreetResponse{
    51  		Greeting: fmt.Sprintf("Hello %s, you're %d years old.", req.Name, req.Age),
    52  	}
    53  
    54  	return res, nil
    55  }
    56  
    57  func main() {
    58  	r := don.New(nil)
    59  	r.Get("/", don.H(Empty))
    60  
    61  	g := r.Group("/api")
    62  	g.Get("/ping", don.H(Ping))
    63  	g.Post("/greet", don.H(Greet))
    64  
    65  	log.Fatal(r.ListenAndServe(":8080"))
    66  }