All Downloads are FREE. Search and download functionalities are using the official Maven repository.

go-server.controller-api.mustache Maven / Gradle / Ivy

{{>partial_header}}
package {{packageName}}

import (
	"encoding/json"
	"net/http"
	"strings"

	"github.com/gorilla/mux"
)

// A {{classname}}Controller binds http requests to an api service and writes the service results to the http response
type {{classname}}Controller struct {
	service {{classname}}Servicer
}

// New{{classname}}Controller creates a default api controller
func New{{classname}}Controller(s {{classname}}Servicer) Router {
	return &{{classname}}Controller{ service: s }
}

// Routes returns all of the api route for the {{classname}}Controller
func (c *{{classname}}Controller) Routes() Routes {
	return Routes{ {{#operations}}{{#operation}}
		{
			"{{operationId}}",
			strings.ToUpper("{{httpMethod}}"),
			"{{{basePathWithoutHost}}}{{{path}}}",
			c.{{operationId}},
		},{{/operation}}{{/operations}}
	}
}{{#operations}}{{#operation}}

// {{nickname}} - {{{summary}}}
func (c *{{classname}}Controller) {{nickname}}(w http.ResponseWriter, r *http.Request) { {{#hasFormParams}}
	err := r.ParseForm()
	if err != nil {
		w.WriteHeader(500)
		return
	}
	{{/hasFormParams}}{{#hasPathParams}}
	params := mux.Vars(r){{/hasPathParams}}{{#hasQueryParams}}
	query := r.URL.Query(){{/hasQueryParams}}{{#allParams}}{{#isPathParam}}{{#isLong}}
	{{paramName}}, err := parseIntParameter(params["{{paramName}}"])
	if err != nil {
		w.WriteHeader(500)
		return
	}
	{{/isLong}}{{^isLong}}
	{{paramName}} := params["{{paramName}}"]{{/isLong}}{{/isPathParam}}{{#isQueryParam}}{{#isLong}}
	{{paramName}}, err := parseIntParameter(query.Get("{{paramName}}"))
	if err != nil {
		w.WriteHeader(500)
		return
	}
	{{/isLong}}{{^isLong}}
	{{paramName}} := {{#isListContainer}}strings.Split({{/isListContainer}}query.Get("{{paramName}}"){{#isListContainer}}, ","){{/isListContainer}}{{/isLong}}{{/isQueryParam}}{{#isFormParam}}{{#isFile}}
	{{paramName}}, err := ReadFormFileToTempFile(r, "{{paramName}}")
	if err != nil {
		w.WriteHeader(500)
		return
	}
	{{/isFile}}{{#isLong}}
	{{paramName}}, err := parseIntParameter( r.FormValue("{{paramName}}"))
	if err != nil {
		w.WriteHeader(500)
		return
	}
	{{/isLong}}{{^isFile}}{{^isLong}}
	{{paramName}} := r.FormValue("{{paramName}}"){{/isLong}}{{/isFile}}{{/isFormParam}}{{#isHeaderParam}}
	{{paramName}} := r.Header.Get("{{paramName}}"){{/isHeaderParam}}{{#isBodyParam}}
	{{paramName}} := &{{dataType}}{}
	if err := json.NewDecoder(r.Body).Decode(&{{paramName}}); err != nil {
		w.WriteHeader(500)
		return
	}
	{{/isBodyParam}}{{/allParams}}
	result, err := c.service.{{nickname}}({{#allParams}}{{#isBodyParam}}*{{/isBodyParam}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}})
	if err != nil {
		w.WriteHeader(500)
		return
	}
	
	EncodeJSONResponse(result, nil, w)
}{{/operation}}{{/operations}}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy