apigen/test/goapi/apigen.go

128 lines
2.6 KiB
Go
Raw Normal View History

2021-01-30 09:53:34 +00:00
package goapi
import (
"context"
"encoding/json"
"net/http"
"strings"
)
type API struct {
Mux *http.ServeMux
Perms map[string]string
}
func (a *API) GetPerm(r *http.Request) string {
return a.Perms[r.Method+"_"+strings.Split(r.RequestURI, "?")[0]]
}
func Init() API {
mux := &http.ServeMux{}
ret := API{
Mux: mux,
Perms: make(map[string]string),
}
mux.HandleFunc("/someapi", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "POST":
h_SomeAPI2(w, r)
case "PUT":
h_SomeAPI(w, r)
default:
http.Error(w, "Method not allowed", 500)
}
})
mux.HandleFunc("/someapi3", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "POST":
h_SomeAPI3(w, r)
default:
http.Error(w, "Method not allowed", 500)
}
})
return ret
}
func h_SomeAPI(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
ctx = context.WithValue(r.Context(), "REQ", r)
ctx = context.WithValue(ctx, "RES", w)
req := &Noop{}
if r.Method != http.MethodGet && r.Method != http.MethodHead {
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
}
res, err := SomeAPI(ctx, req)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
w.Header().Add("Content-Type", "Application/json")
err = json.NewEncoder(w).Encode(res)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
}
func h_SomeAPI2(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
ctx = context.WithValue(r.Context(), "REQ", r)
ctx = context.WithValue(ctx, "RES", w)
req := &AStr2{}
if r.Method != http.MethodGet && r.Method != http.MethodHead {
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
}
res, err := SomeAPI2(ctx, req)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
w.Header().Add("Content-Type", "Application/json")
err = json.NewEncoder(w).Encode(res)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
}
func h_SomeAPI3(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
ctx = context.WithValue(r.Context(), "REQ", r)
ctx = context.WithValue(ctx, "RES", w)
req := &AStr{}
if r.Method != http.MethodGet && r.Method != http.MethodHead {
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
}
res, err := SomeAPI3(ctx, req)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
w.Header().Add("Content-Type", "Application/json")
err = json.NewEncoder(w).Encode(res)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
}