github.com/ixpectus/declarate@v0.0.0-20240422152255-708027d7c068/tests/server.go (about)

     1  package tests
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"net/http"
     7  	"sync/atomic"
     8  )
     9  
    10  var pollCounter atomic.Int32
    11  
    12  // The `json:"whatever"` bit is a way to tell the JSON
    13  // encoder and decoder to use those names instead of the
    14  // capitalised names
    15  type person struct {
    16  	Name  string `json:"name"`
    17  	Age   int    `json:"age"`
    18  	Items []int  `json:"items"`
    19  }
    20  
    21  var tom *person = &person{
    22  	Name: "Tom",
    23  	Age:  28,
    24  	Items: []int{
    25  		1, 2, 3, 4,
    26  	},
    27  }
    28  
    29  var pollPerson *person = &person{
    30  	Name: "Tommy",
    31  	Age:  31,
    32  	Items: []int{
    33  		1, 2, 4,
    34  	},
    35  }
    36  
    37  func tomHandler(w http.ResponseWriter, r *http.Request) {
    38  	w.Header().Add("Date", defaultDate)
    39  	switch r.Method {
    40  	case "GET":
    41  		// Just send out the JSON version of 'tom'
    42  		j, _ := json.Marshal(tom)
    43  		w.Write(j)
    44  	case "POST":
    45  		// Decode the JSON in the body and overwrite 'tom' with it
    46  		d := json.NewDecoder(r.Body)
    47  		p := &person{}
    48  		err := d.Decode(p)
    49  		if err != nil {
    50  			http.Error(w, err.Error(), http.StatusInternalServerError)
    51  		}
    52  		tom = p
    53  	default:
    54  		w.WriteHeader(http.StatusMethodNotAllowed)
    55  		fmt.Fprintf(w, "I can't do that.")
    56  	}
    57  }
    58  
    59  const defaultDate = "Sun, 16 Apr 2023 08:42:05 GMT"
    60  
    61  func pollHandler(w http.ResponseWriter, r *http.Request) {
    62  	w.Header().Add("Date", defaultDate)
    63  	switch r.Method {
    64  	case "GET":
    65  		// Just send out the JSON version of 'tom'
    66  		v := pollCounter.Add(1)
    67  		if v == 5 {
    68  			j, _ := json.Marshal(pollPerson)
    69  			w.Write(j)
    70  			pollCounter.Store(0)
    71  		} else {
    72  			j, _ := json.Marshal(tom)
    73  			w.Write(j)
    74  		}
    75  	case "POST":
    76  		// Decode the JSON in the body and overwrite 'tom' with it
    77  		d := json.NewDecoder(r.Body)
    78  		p := &person{}
    79  		err := d.Decode(p)
    80  		if err != nil {
    81  			http.Error(w, err.Error(), http.StatusInternalServerError)
    82  		}
    83  		tom = p
    84  	default:
    85  		w.WriteHeader(http.StatusMethodNotAllowed)
    86  		fmt.Fprintf(w, "I can't do that.")
    87  	}
    88  }
    89  
    90  func Handle() {
    91  	http.HandleFunc("/tom", tomHandler)
    92  	http.HandleFunc("/poll", pollHandler)
    93  	http.ListenAndServe("127.0.0.1:8181", nil)
    94  }