add API for aliases/ansible

This commit is contained in:
Martin Geno 2016-05-14 13:21:10 +02:00
parent d1aa7ab4d7
commit 139c94f083
4 changed files with 80 additions and 65 deletions

View File

@ -3,14 +3,17 @@ package api
import ( import (
"fmt" "fmt"
"net/http" "net/http"
"encoding/json"
"github.com/julienschmidt/httprouter" "github.com/julienschmidt/httprouter"
"github.com/FreifunkBremen/respond-collector/models" "github.com/FreifunkBremen/respond-collector/models"
) )
type ApiAliases struct { type ApiAliases struct {
aliases *models.Aliases aliases *models.Aliases
config *models.Config config *models.Config
nodes *models.Nodes nodes *models.Nodes
} }
func NewAliases (config *models.Config, router *httprouter.Router,prefix string,nodes *models.Nodes) { func NewAliases (config *models.Config, router *httprouter.Router,prefix string,nodes *models.Nodes) {
api := &ApiAliases{ api := &ApiAliases{
aliases: models.NewAliases(config), aliases: models.NewAliases(config),
@ -22,20 +25,32 @@ func NewAliases (config *models.Config, router *httprouter.Router,prefix string,
router.GET(prefix+"/alias/:nodeid", api.GetOne) router.GET(prefix+"/alias/:nodeid", api.GetOne)
router.POST(prefix+"/alias/:nodeid", api.SaveOne) router.POST(prefix+"/alias/:nodeid", api.SaveOne)
} }
func (api *ApiAliases) GetAll(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { func (api *ApiAliases) GetAll(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
jsonOutput(w,api.aliases.List) jsonOutput(w,api.aliases.List)
} }
func (api *ApiAliases) GetOne(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { func (api *ApiAliases) GetOne(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
if alias := api.aliases.List[ps.ByName("nodeid")]; alias !=nil{ if alias := api.aliases.List[ps.ByName("nodeid")]; alias !=nil{
jsonOutput(w,alias) jsonOutput(w,alias)
return
} }
fmt.Fprint(w, "Not found: ", ps.ByName("nodeid"),"\n") fmt.Fprint(w, "Not found: ", ps.ByName("nodeid"),"\n")
} }
func (api *ApiAliases) SaveOne(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { func (api *ApiAliases) SaveOne(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
alias := &models.Alias{Hostname: ps.ByName("nodeid")} var alias models.Alias
api.aliases.Update(ps.ByName("nodeid"),alias) err := json.NewDecoder(r.Body).Decode(&alias)
api.GetOne(w,r,ps)
if err != nil{
http.Error(w, err.Error(), http.StatusInternalServerError)
fmt.Fprint(w, "Decode: ", ps.ByName("nodeid"),"\n")
return
}
api.aliases.Update(ps.ByName("nodeid"),&alias)
jsonOutput(w,alias)
} }
func (api *ApiAliases) AnsibleDiff(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { func (api *ApiAliases) AnsibleDiff(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
diff := api.aliases.List diff := api.aliases.List
//TODO diff between List and api.nodes (for run not at all) //TODO diff between List and api.nodes (for run not at all)