Recognize stat_dir_type_empty
[govpp.git] / binapigen / gen_http.go
1 //  Copyright (c) 2020 Cisco and/or its affiliates.
2 //
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:
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
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.
14
15 package binapigen
16
17 import (
18         "path"
19         "strconv"
20 )
21
22 func init() {
23         RegisterPlugin("http", GenerateHTTP)
24 }
25
26 // library dependencies
27 const (
28         httpPkg   = GoImportPath("net/http")
29         ioutilPkg = GoImportPath("io/ioutil")
30         jsonPkg   = GoImportPath("encoding/json")
31 )
32
33 func GenerateHTTP(gen *Generator, file *File) *GenFile {
34         if file.Service == nil {
35                 return nil
36         }
37
38         logf("----------------------------")
39         logf(" Generate HTTP - %s", file.Desc.Name)
40         logf("----------------------------")
41
42         filename := path.Join(file.FilenamePrefix, file.Desc.Name+"_http.ba.go")
43         g := gen.NewGenFile(filename, file.GoImportPath)
44         g.file = file
45
46         // generate file header
47         g.P("// Code generated by GoVPP's binapi-generator. DO NOT EDIT.")
48         g.P()
49         g.P("package ", file.PackageName)
50         g.P()
51
52         // generate RPC service
53         if len(file.Service.RPCs) > 0 {
54                 genHTTPHandler(g, file.Service)
55         }
56
57         return g
58 }
59
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"), "()")
64
65         // generate http handlers for rpc
66         for _, rpc := range svc.RPCs {
67                 if rpc.MsgReply == nil {
68                         continue
69                 }
70                 if rpc.VPP.Stream {
71                         continue // TODO: implement handler for streaming messages
72                 }
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"), ")")
79                         g.P("   return")
80                         g.P("}")
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"), ")")
83                         g.P("   return")
84                         g.P("}")
85                 }
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"), ")")
89                 g.P("   return")
90                 g.P("}")
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"), ")")
94                 g.P("   return")
95                 g.P("}")
96                 g.P("w.Write(rep)")
97                 g.P("})")
98         }
99
100         g.P("return ", httpPkg.Ident("HandlerFunc"), "(mux.ServeHTTP)")
101         g.P("}")
102         g.P()
103 }