Web Applications
Making a RESTful JSON API in Go
multipart/form-data
I asked a question on this on stackoverflow
package main
import (
"fmt"
"log"
"mime/multipart"
"net/http"
"strings"
)
func handler(resp http.ResponseWriter, req *http.Request) {
switch strings.Split(req.Header.Get("Content-Type"), ";")[0] {
case "multipart/form-data":
req.ParseMultipartForm(2097152)
mw := multipart.NewWriter(resp)
resp.Header().Set("Content-Type", mw.FormDataContentType())
mw.WriteField("name", req.FormValue("user_name"))
mw.WriteField("email", req.FormValue("user_email"))
mw.WriteField("message", req.FormValue("user_message"))
mw.Close()
case "application/x-www-form-urlencoded":
req.ParseForm()
fmt.Fprintf(resp, "%#v", req.PostForm)
case "application/json":
fmt.Fprintf(resp, "%#v", req.Body)
default:
fmt.Fprintf(resp, "%#v", req.Body)
}
}
func main() {
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
RFC 7230 Message Syntax and Routing
Request:
GET /hello.txt HTTP/1.1
User-Agent: curl/7.16.3 libcurl/7.16.3 OpenSSL/0.9.7l zlib/1.2.3
Host: www.example.com
Accept-Language: en, mi
To get the above in go
package main
import (
"fmt"
"log"
"net/http"
)
func handler(response http.ResponseWriter, request *http.Request) {
str := fmt.Sprintf("%v %v %v\n", request.Method, request.RequestURI, request.Proto)
str = str + fmt.Sprintf("User-Agent: %v\n", request.Header["User-Agent"][0])
str = str + fmt.Sprintf("Host: %v\n", request.Host)
str = str + fmt.Sprintf("Accept-Language: %v\n", request.Header["Accept-Language"][0])
fmt.Fprintf(response, str)
}
func main() {
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe(":4153", nil))
}
To access form key: values posted by the browser, request.ParseMultipartForm(maxBytes) is needed for multipart/form-data or request.ParseForm() for application/x-www-form-urlencoded
These values can then be access using request.FormValue(“key”)) or request.PostFormValue(“key”))
[NewWriter]
Response:
HTTP/1.1 200 OK
Date: Mon, 27 Jul 2009 12:28:53 GMT
Server: Apache
Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT
ETag: "34aa387-d-1568eb00"
Accept-Ranges: bytes
Content-Length: 51
Vary: Accept-Encoding
Content-Type: text/plain
Hello World! My payload includes a trailing CRLF.
Writing Web Applications
https://stackoverflow.com/questions/20205796/post-data-using-the-content-type-multipart-form-data
Developing a RESTful API with Go and Gin
package main
import "github.com/gin-gonic/gin"
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
r.Run() // listen and serve on 0.0.0.0:8080
}
gin.Context is the most important part of Gin. It carries request details, validates and serializes JSON, and more. (Despite the similar name, this is different from Go’s built-in context package.)