apigen/lib/processGoServerOutput.go

124 lines
2.4 KiB
Go
Raw Normal View History

2021-09-06 12:54:09 +00:00
package lib
import (
"bytes"
_ "embed"
"fmt"
"os"
)
func processGoServerOutput(f string) error {
buf := &bytes.Buffer{}
2021-09-07 16:15:32 +00:00
//W := func(s string, p ...interface{}) {
// buf.WriteString(fmt.Sprintf(s, p...))
//}
2021-09-06 12:54:09 +00:00
WNL := func(s string, p ...interface{}) {
buf.WriteString(fmt.Sprintf(s+"\n", p...))
}
2021-09-07 16:15:32 +00:00
ResImplType := func(v *APIParamType) string {
ret := ""
if !v.IsArray || v.Ispointer {
ret = ret + "&"
}
ret += v.Typename + "{}"
return ret
}
2021-09-06 12:54:09 +00:00
WNL("package %s", api.Namespace)
WNL(`import (
"context"
"encoding/json"
"strings"
"net/http"
)`)
for k := range api.UsedImportsFunctions {
2021-09-07 16:15:32 +00:00
WNL(`import "%s"`, k)
2021-09-06 12:54:09 +00:00
}
WNL(`type API struct {
2021-09-07 16:15:32 +00:00
Mux *http.ServeMux
Perms map[string]string
}
2021-09-06 12:54:09 +00:00
2021-09-07 16:15:32 +00:00
func (a *API) GetPerm(r *http.Request) string {
return a.Perms[r.Method+"_"+strings.Split(r.RequestURI, "?")[0]]
}
2021-09-06 12:54:09 +00:00
`)
WNL(`func Init() *API{
mux := &http.ServeMux{}
ret := &API{
Mux: mux,
Perms: make(map[string]string),
}`)
for _, v := range api.Methods {
if v.Perm != "" {
WNL(` ret.Perms["%s_%s"]="%s"`, v.Verb, v.Path, v.Perm)
}
}
for _, v := range api.SortedPaths {
WNL(` mux.HandleFunc("%s",func(w http.ResponseWriter, r *http.Request) {
switch r.Method {`, v.Path)
for _, v1 := range v.SortedVerbs {
WNL(` case "%s":`, v1.Method.Verb)
if v1.Method.Raw {
WNL(` %s(w,r)`, v1.Method.Name)
} else {
WNL(` h_%s(w,r)`, v1.Method.Name)
}
2021-09-06 13:31:56 +00:00
}
2021-09-07 16:15:32 +00:00
WNL(` default:
http.Error(w,"Method not allowed",500)
}`)
2021-09-06 12:54:09 +00:00
}
2021-09-07 16:15:32 +00:00
WNL(` })`)
2021-09-06 13:31:56 +00:00
WNL(` return ret
2021-09-07 16:15:32 +00:00
}`)
2021-09-06 12:54:09 +00:00
for _, v := range api.Methods {
WNL(`func h_%s(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
ctx = context.WithValue(r.Context(), "REQ", r)
ctx = context.WithValue(ctx, "RES", w)`, v.Name)
2021-09-07 16:15:32 +00:00
WNL(" req := %s", ResImplType(v.ReqType))
2021-09-06 12:54:09 +00:00
WNL(` if r.Method!=http.MethodGet && r.Method!=http.MethodHead {`)
if v.ReqType.Ispointer || v.ReqType.IsArray {
WNL(" err := json.NewDecoder(r.Body).Decode(req)")
} else {
WNL(" err := json.NewDecoder(r.Body).Decode(&req)")
}
WNL(` if err != nil {
http.Error(w, err.Error(), 500)
return
}
}`)
WNL(` res, err := %s(ctx,req)`, v.Name)
WNL(` 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
}
}`)
}
return os.WriteFile(f, buf.Bytes(), 0600)
}