github.com/gocaveman/caveman@v0.0.0-20191211162744-0ddf99dbdf6e/regions/regionctrl/regionctrl.go (about)

     1  // Region controller for administrative edits to regions.  Not required for rendering.
     2  package regionctrl
     3  
     4  import (
     5  	"log"
     6  	"net/http"
     7  
     8  	"github.com/gocaveman/caveman/httpapi"
     9  	"github.com/gocaveman/caveman/regions"
    10  )
    11  
    12  func NewRegionController(store regions.Store) *RegionController {
    13  	return &RegionController{
    14  		Prefix: "/api/region",
    15  		Store:  store,
    16  	}
    17  }
    18  
    19  // RegionController provides an editing API on top of a regions.Store.
    20  // (It is not used as part of normal page rendering.)
    21  type RegionController struct {
    22  	// FIXME: Should we break this down into a prefix and suffix?
    23  	// It would allow us to autowire all of the default caveman stuff to a different prefix -
    24  	// some people might find this very useful for integrating into existing sites/apps.
    25  	Prefix string
    26  	Store  regions.Store `autowire:""`
    27  
    28  	// TODO: JSONRPC2, mind as well support it also, we can... although we still have to
    29  	// debug the multiple body parsing issue... possibly each controller gets it's own endpoint??
    30  }
    31  
    32  func (h *RegionController) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    33  
    34  	log.Printf("FIXME: RegionController needs security (auth/perms)")
    35  
    36  	ar := httpapi.NewRequest(r)
    37  
    38  	var def regions.Definition
    39  
    40  	// TODO: we'll also want to load page data for the admin page
    41  	// TODO: we should also provide the endpoint path/url here to the page, so
    42  	// this page and anything else that needs it will track with a change to the API endpoint
    43  
    44  	switch {
    45  
    46  	// write
    47  	case ar.ParseRESTObj("POST", &def, h.Prefix):
    48  		if err := def.IsValid(); err != nil {
    49  			ar.WriteError(w, 400, err)
    50  			return
    51  		}
    52  		err := h.Store.WriteDefinition(def)
    53  		if err != nil {
    54  			ar.WriteError(w, 500, err)
    55  			return
    56  		}
    57  		ar.WriteResult(w, 200, def)
    58  		return
    59  
    60  	// delete
    61  	case ar.ParseRESTPath("DELETE", h.Prefix+"/%s", &def.DefinitionID):
    62  		err := h.Store.DeleteDefinition(def.DefinitionID)
    63  		if err != nil {
    64  			ar.WriteError(w, 500, err)
    65  			return
    66  		}
    67  		ar.WriteResult(w, 200, def.DefinitionID)
    68  		return
    69  
    70  	// list
    71  	case ar.ParseRESTPath("GET", h.Prefix):
    72  		defs, err := h.Store.AllDefinitions()
    73  		if err != nil {
    74  			ar.WriteError(w, 500, err)
    75  			return
    76  		}
    77  		ar.WriteResult(w, 200, defs)
    78  		return
    79  
    80  	}
    81  
    82  }