1 // Copyright (c) 2020 Cisco and/or its affiliates.
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at:
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
23 RegisterPlugin("http", GenerateHTTP)
26 // library dependencies
28 httpPkg = GoImportPath("net/http")
29 ioutilPkg = GoImportPath("io/ioutil")
30 jsonPkg = GoImportPath("encoding/json")
33 func GenerateHTTP(gen *Generator, file *File) *GenFile {
34 if file.Service == nil {
38 logf("----------------------------")
39 logf(" Generate HTTP - %s", file.Desc.Name)
40 logf("----------------------------")
42 filename := path.Join(file.FilenamePrefix, file.Desc.Name+"_http.ba.go")
43 g := gen.NewGenFile(filename, file.GoImportPath)
46 // generate file header
47 g.P("// Code generated by GoVPP's binapi-generator. DO NOT EDIT.")
49 g.P("package ", file.PackageName)
52 // generate RPC service
53 if len(file.Service.RPCs) > 0 {
54 genHTTPHandler(g, file.Service)
60 func genHTTPHandler(g *GenFile, svc *Service) {
61 // generate handler constructor
62 g.P("func HTTPHandler(rpc ", serviceApiName, ") ", httpPkg.Ident("Handler"), " {")
63 g.P(" mux := ", httpPkg.Ident("NewServeMux"), "()")
65 // generate http handlers for rpc
66 for _, rpc := range svc.RPCs {
67 if rpc.MsgReply == nil {
71 continue // TODO: implement handler for streaming messages
73 g.P("mux.HandleFunc(", strconv.Quote("/"+rpc.VPP.Request), ", func(w ", httpPkg.Ident("ResponseWriter"), ", req *", httpPkg.Ident("Request"), ") {")
74 g.P("var request = new(", rpc.MsgRequest.GoName, ")")
75 if len(rpc.MsgRequest.Fields) > 0 {
76 g.P("b, err := ", ioutilPkg.Ident("ReadAll"), "(req.Body)")
77 g.P("if err != nil {")
78 g.P(" ", httpPkg.Ident("Error"), "(w, \"read body failed\", ", httpPkg.Ident("StatusBadRequest"), ")")
81 g.P("if err := ", jsonPkg.Ident("Unmarshal"), "(b, request); err != nil {")
82 g.P(" ", httpPkg.Ident("Error"), "(w, \"unmarshal data failed\", ", httpPkg.Ident("StatusBadRequest"), ")")
86 g.P("reply, err := rpc.", rpc.GoName, "(req.Context(), request)")
87 g.P("if err != nil {")
88 g.P(" ", httpPkg.Ident("Error"), "(w, \"request failed: \"+err.Error(), ", httpPkg.Ident("StatusInternalServerError"), ")")
91 g.P("rep, err := ", jsonPkg.Ident("MarshalIndent"), "(reply, \"\", \" \")")
92 g.P("if err != nil {")
93 g.P(" ", httpPkg.Ident("Error"), "(w, \"marshal failed: \"+err.Error(), ", httpPkg.Ident("StatusInternalServerError"), ")")
100 g.P("return ", httpPkg.Ident("HandlerFunc"), "(mux.ServeHTTP)")