Skip to content

Commit

Permalink
parse form
Browse files Browse the repository at this point in the history
  • Loading branch information
JINLEI1 authored and JINLEI1 committed Jan 19, 2018
1 parent 7542c76 commit bb153b3
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions runtime/mux.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
package runtime

import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/textproto"
"strings"

"github.com/davecgh/go-spew/spew"
"github.com/golang/protobuf/proto"
"golang.org/x/net/context"
"google.golang.org/grpc/codes"
Expand Down Expand Up @@ -146,6 +151,34 @@ func (s *ServeMux) Handle(meth string, pat Pattern, h HandlerFunc) {

// ServeHTTP dispatches the request to the first handler whose pattern matches to r.Method and r.Path.
func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {

// log.Printf("Got request: %#v\n", r)
if strings.ToLower(strings.Split(r.Header.Get("Content-Type"), ";")[0]) == "application/x-www-form-urlencoded" {
log.Println("Rewriting form data as json")
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
log.Println("Bad form request", err.Error())
return
}
spew.Dump(r.Form)
jsonMap := make(map[string]interface{}, len(r.Form))
for k, v := range r.Form {
if len(v) > 0 {
jsonMap[k] = v[0]
}
}
spew.Dump(jsonMap)
jsonBody, err := json.Marshal(jsonMap)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
}

r.Body = ioutil.NopCloser(bytes.NewReader(jsonBody))
spew.Dump(string(jsonBody))
r.ContentLength = int64(len(jsonBody))
r.Header.Set("Content-Type", "application/json")
}

ctx := r.Context()

path := r.URL.Path
Expand Down

0 comments on commit bb153b3

Please sign in to comment.